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(_: &SignIn, window: &mut Window, cx: &mut App) {
242 let client = Client::global(cx);
243
244 window
245 .spawn(cx, async move |cx| {
246 client
247 .sign_in_with_optional_connect(true, cx)
248 .await
249 .notify_async_err(cx);
250 })
251 .detach();
252 }
253
254 fn handle_open_account(_: &OpenAccount, _: &mut Window, cx: &mut App) {
255 cx.open_url(&zed_urls::account_url(cx))
256 }
257
258 fn render_page(&mut self, cx: &mut Context<Self>) -> AnyElement {
259 crate::basics_page::render_basics_page(cx).into_any_element()
260 }
261}
262
263impl Render for Onboarding {
264 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
265 div()
266 .image_cache(gpui::retain_all("onboarding-page"))
267 .key_context({
268 let mut ctx = KeyContext::new_with_defaults();
269 ctx.add("Onboarding");
270 ctx.add("menu");
271 ctx
272 })
273 .track_focus(&self.focus_handle)
274 .size_full()
275 .bg(cx.theme().colors().editor_background)
276 .on_action(Self::on_finish)
277 .on_action(Self::handle_sign_in)
278 .on_action(Self::handle_open_account)
279 .on_action(cx.listener(|_, _: &menu::SelectNext, window, cx| {
280 window.focus_next(cx);
281 cx.notify();
282 }))
283 .on_action(cx.listener(|_, _: &menu::SelectPrevious, window, cx| {
284 window.focus_prev(cx);
285 cx.notify();
286 }))
287 .child(
288 div()
289 .max_w(Rems(48.0))
290 .size_full()
291 .mx_auto()
292 .child(
293 v_flex()
294 .id("page-content")
295 .m_auto()
296 .p_12()
297 .size_full()
298 .max_w_full()
299 .min_w_0()
300 .gap_6()
301 .overflow_y_scroll()
302 .child(
303 h_flex()
304 .w_full()
305 .gap_4()
306 .justify_between()
307 .child(
308 h_flex()
309 .gap_4()
310 .child(Vector::square(VectorName::ZedLogo, rems(2.5)))
311 .child(
312 v_flex()
313 .child(
314 Headline::new("Welcome to Zed")
315 .size(HeadlineSize::Small),
316 )
317 .child(
318 Label::new("The editor for what's next")
319 .color(Color::Muted)
320 .size(LabelSize::Small)
321 .italic(),
322 ),
323 ),
324 )
325 .child({
326 Button::new("finish_setup", "Finish Setup")
327 .style(ButtonStyle::Filled)
328 .size(ButtonSize::Medium)
329 .width(Rems(12.0))
330 .key_binding(
331 KeyBinding::for_action_in(
332 &Finish,
333 &self.focus_handle,
334 cx,
335 )
336 .size(rems_from_px(12.)),
337 )
338 .on_click(|_, window, cx| {
339 window.dispatch_action(Finish.boxed_clone(), cx);
340 })
341 }),
342 )
343 .child(Divider::horizontal().color(ui::DividerColor::BorderVariant))
344 .child(self.render_page(cx))
345 .track_scroll(&self.scroll_handle),
346 )
347 .vertical_scrollbar_for(&self.scroll_handle, window, cx),
348 )
349 }
350}
351
352impl EventEmitter<ItemEvent> for Onboarding {}
353
354impl Focusable for Onboarding {
355 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
356 self.focus_handle.clone()
357 }
358}
359
360impl Item for Onboarding {
361 type Event = ItemEvent;
362
363 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
364 "Onboarding".into()
365 }
366
367 fn telemetry_event_text(&self) -> Option<&'static str> {
368 Some("Onboarding Page Opened")
369 }
370
371 fn show_toolbar(&self) -> bool {
372 false
373 }
374
375 fn can_split(&self) -> bool {
376 true
377 }
378
379 fn clone_on_split(
380 &self,
381 _workspace_id: Option<WorkspaceId>,
382 _: &mut Window,
383 cx: &mut Context<Self>,
384 ) -> Task<Option<Entity<Self>>> {
385 Task::ready(Some(cx.new(|cx| Onboarding {
386 workspace: self.workspace.clone(),
387 user_store: self.user_store.clone(),
388 scroll_handle: ScrollHandle::new(),
389 focus_handle: cx.focus_handle(),
390 _settings_subscription: cx.observe_global::<SettingsStore>(move |_, cx| cx.notify()),
391 })))
392 }
393
394 fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
395 f(*event)
396 }
397}
398
399fn go_to_welcome_page(cx: &mut App) {
400 with_active_or_new_workspace(cx, |workspace, window, cx| {
401 let Some((onboarding_id, onboarding_idx)) = workspace
402 .active_pane()
403 .read(cx)
404 .items()
405 .enumerate()
406 .find_map(|(idx, item)| {
407 let _ = item.downcast::<Onboarding>()?;
408 Some((item.item_id(), idx))
409 })
410 else {
411 return;
412 };
413
414 workspace.active_pane().update(cx, |pane, cx| {
415 // Get the index here to get around the borrow checker
416 let idx = pane.items().enumerate().find_map(|(idx, item)| {
417 let _ = item.downcast::<WelcomePage>()?;
418 Some(idx)
419 });
420
421 if let Some(idx) = idx {
422 pane.activate_item(idx, true, true, window, cx);
423 } else {
424 let item = Box::new(
425 cx.new(|cx| WelcomePage::new(workspace.weak_handle(), false, window, cx)),
426 );
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}