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                                                    cx,
341                                                )
342                                                .size(rems_from_px(12.)),
343                                            )
344                                            .on_click(|_, window, cx| {
345                                                window.dispatch_action(Finish.boxed_clone(), cx);
346                                            })
347                                    }),
348                            )
349                            .child(Divider::horizontal().color(ui::DividerColor::BorderVariant))
350                            .child(self.render_page(cx))
351                            .track_scroll(&self.scroll_handle),
352                    )
353                    .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx),
354            )
355    }
356}
357
358impl EventEmitter<ItemEvent> for Onboarding {}
359
360impl Focusable for Onboarding {
361    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
362        self.focus_handle.clone()
363    }
364}
365
366impl Item for Onboarding {
367    type Event = ItemEvent;
368
369    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
370        "Onboarding".into()
371    }
372
373    fn telemetry_event_text(&self) -> Option<&'static str> {
374        Some("Onboarding Page Opened")
375    }
376
377    fn show_toolbar(&self) -> bool {
378        false
379    }
380
381    fn clone_on_split(
382        &self,
383        _workspace_id: Option<WorkspaceId>,
384        _: &mut Window,
385        cx: &mut Context<Self>,
386    ) -> Option<Entity<Self>> {
387        Some(cx.new(|cx| Onboarding {
388            workspace: self.workspace.clone(),
389            user_store: self.user_store.clone(),
390            scroll_handle: ScrollHandle::new(),
391            focus_handle: cx.focus_handle(),
392            _settings_subscription: cx.observe_global::<SettingsStore>(move |_, cx| cx.notify()),
393        }))
394    }
395
396    fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
397        f(*event)
398    }
399}
400
401fn go_to_welcome_page(cx: &mut App) {
402    with_active_or_new_workspace(cx, |workspace, window, cx| {
403        let Some((onboarding_id, onboarding_idx)) = workspace
404            .active_pane()
405            .read(cx)
406            .items()
407            .enumerate()
408            .find_map(|(idx, item)| {
409                let _ = item.downcast::<Onboarding>()?;
410                Some((item.item_id(), idx))
411            })
412        else {
413            return;
414        };
415
416        workspace.active_pane().update(cx, |pane, cx| {
417            // Get the index here to get around the borrow checker
418            let idx = pane.items().enumerate().find_map(|(idx, item)| {
419                let _ = item.downcast::<WelcomePage>()?;
420                Some(idx)
421            });
422
423            if let Some(idx) = idx {
424                pane.activate_item(idx, true, true, window, cx);
425            } else {
426                let item = Box::new(WelcomePage::new(window, cx));
427                pane.add_item(item, true, true, Some(onboarding_idx), window, cx);
428            }
429
430            pane.remove_item(onboarding_id, false, false, window, cx);
431        });
432    });
433}
434
435pub async fn handle_import_vscode_settings(
436    workspace: WeakEntity<Workspace>,
437    source: VsCodeSettingsSource,
438    skip_prompt: bool,
439    fs: Arc<dyn Fs>,
440    cx: &mut AsyncWindowContext,
441) {
442    use util::truncate_and_remove_front;
443
444    let vscode_settings =
445        match settings::VsCodeSettings::load_user_settings(source, fs.clone()).await {
446            Ok(vscode_settings) => vscode_settings,
447            Err(err) => {
448                zlog::error!("{err}");
449                let _ = cx.prompt(
450                    gpui::PromptLevel::Info,
451                    &format!("Could not find or load a {source} settings file"),
452                    None,
453                    &["Ok"],
454                );
455                return;
456            }
457        };
458
459    if !skip_prompt {
460        let prompt = cx.prompt(
461            gpui::PromptLevel::Warning,
462            &format!(
463                "Importing {} settings may overwrite your existing settings. \
464                Will import settings from {}",
465                vscode_settings.source,
466                truncate_and_remove_front(&vscode_settings.path.to_string_lossy(), 128),
467            ),
468            None,
469            &["Ok", "Cancel"],
470        );
471        let result = cx.spawn(async move |_| prompt.await.ok()).await;
472        if result != Some(0) {
473            return;
474        }
475    };
476
477    let Ok(result_channel) = cx.update(|_, cx| {
478        let source = vscode_settings.source;
479        let path = vscode_settings.path.clone();
480        let result_channel = cx
481            .global::<SettingsStore>()
482            .import_vscode_settings(fs, vscode_settings);
483        zlog::info!("Imported {source} settings from {}", path.display());
484        result_channel
485    }) else {
486        return;
487    };
488
489    let result = result_channel.await;
490    workspace
491        .update_in(cx, |workspace, _, cx| match result {
492            Ok(_) => {
493                let confirmation_toast = StatusToast::new(
494                    format!("Your {} settings were successfully imported.", source),
495                    cx,
496                    |this, _| {
497                        this.icon(ToastIcon::new(IconName::Check).color(Color::Success))
498                            .dismiss_button(true)
499                    },
500                );
501                SettingsImportState::update(cx, |state, _| match source {
502                    VsCodeSettingsSource::VsCode => {
503                        state.vscode = true;
504                    }
505                    VsCodeSettingsSource::Cursor => {
506                        state.cursor = true;
507                    }
508                });
509                workspace.toggle_status_toast(confirmation_toast, cx);
510            }
511            Err(_) => {
512                let error_toast = StatusToast::new(
513                    "Failed to import settings. See log for details",
514                    cx,
515                    |this, _| {
516                        this.icon(ToastIcon::new(IconName::Close).color(Color::Error))
517                            .action("Open Log", |window, cx| {
518                                window.dispatch_action(workspace::OpenLog.boxed_clone(), cx)
519                            })
520                            .dismiss_button(true)
521                    },
522                );
523                workspace.toggle_status_toast(error_toast, cx);
524            }
525        })
526        .ok();
527}
528
529#[derive(Default, Copy, Clone)]
530pub struct SettingsImportState {
531    pub cursor: bool,
532    pub vscode: bool,
533}
534
535impl Global for SettingsImportState {}
536
537impl SettingsImportState {
538    pub fn global(cx: &App) -> Self {
539        cx.try_global().cloned().unwrap_or_default()
540    }
541    pub fn update<R>(cx: &mut App, f: impl FnOnce(&mut Self, &mut App) -> R) -> R {
542        cx.update_default_global(f)
543    }
544}
545
546impl workspace::SerializableItem for Onboarding {
547    fn serialized_item_kind() -> &'static str {
548        "OnboardingPage"
549    }
550
551    fn cleanup(
552        workspace_id: workspace::WorkspaceId,
553        alive_items: Vec<workspace::ItemId>,
554        _window: &mut Window,
555        cx: &mut App,
556    ) -> gpui::Task<gpui::Result<()>> {
557        workspace::delete_unloaded_items(
558            alive_items,
559            workspace_id,
560            "onboarding_pages",
561            &persistence::ONBOARDING_PAGES,
562            cx,
563        )
564    }
565
566    fn deserialize(
567        _project: Entity<project::Project>,
568        workspace: WeakEntity<Workspace>,
569        workspace_id: workspace::WorkspaceId,
570        item_id: workspace::ItemId,
571        window: &mut Window,
572        cx: &mut App,
573    ) -> gpui::Task<gpui::Result<Entity<Self>>> {
574        window.spawn(cx, async move |cx| {
575            if let Some(_) =
576                persistence::ONBOARDING_PAGES.get_onboarding_page(item_id, workspace_id)?
577            {
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        Some(cx.background_spawn(async move {
596            persistence::ONBOARDING_PAGES
597                .save_onboarding_page(item_id, workspace_id)
598                .await
599        }))
600    }
601
602    fn should_serialize(&self, event: &Self::Event) -> bool {
603        event == &ItemEvent::UpdateTab
604    }
605}
606
607mod persistence {
608    use db::{
609        query,
610        sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
611        sqlez_macros::sql,
612    };
613    use workspace::WorkspaceDb;
614
615    pub struct OnboardingPagesDb(ThreadSafeConnection);
616
617    impl Domain for OnboardingPagesDb {
618        const NAME: &str = stringify!(OnboardingPagesDb);
619
620        const MIGRATIONS: &[&str] = &[
621            sql!(
622                        CREATE TABLE onboarding_pages (
623                            workspace_id INTEGER,
624                            item_id INTEGER UNIQUE,
625                            page_number INTEGER,
626
627                            PRIMARY KEY(workspace_id, item_id),
628                            FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
629                            ON DELETE CASCADE
630                        ) STRICT;
631            ),
632            sql!(
633                        CREATE TABLE onboarding_pages_2 (
634                            workspace_id INTEGER,
635                            item_id INTEGER UNIQUE,
636
637                            PRIMARY KEY(workspace_id, item_id),
638                            FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
639                            ON DELETE CASCADE
640                        ) STRICT;
641                        INSERT INTO onboarding_pages_2 SELECT workspace_id, item_id FROM onboarding_pages;
642                        DROP TABLE onboarding_pages;
643                        ALTER TABLE onboarding_pages_2 RENAME TO onboarding_pages;
644            ),
645        ];
646    }
647
648    db::static_connection!(ONBOARDING_PAGES, OnboardingPagesDb, [WorkspaceDb]);
649
650    impl OnboardingPagesDb {
651        query! {
652            pub async fn save_onboarding_page(
653                item_id: workspace::ItemId,
654                workspace_id: workspace::WorkspaceId
655            ) -> Result<()> {
656                INSERT OR REPLACE INTO onboarding_pages(item_id, workspace_id)
657                VALUES (?, ?)
658            }
659        }
660
661        query! {
662            pub fn get_onboarding_page(
663                item_id: workspace::ItemId,
664                workspace_id: workspace::WorkspaceId
665            ) -> Result<Option<workspace::ItemId>> {
666                SELECT item_id
667                FROM onboarding_pages
668                WHERE item_id = ? AND workspace_id = ?
669            }
670        }
671    }
672}