settings_ui.rs

  1//! # settings_ui
  2use std::{rc::Rc, sync::Arc};
  3
  4use editor::Editor;
  5use feature_flags::{FeatureFlag, FeatureFlagAppExt as _};
  6use gpui::{
  7    App, AppContext as _, Context, Div, Entity, IntoElement, ReadGlobal as _, Render, Window,
  8    WindowHandle, WindowOptions, actions, div, px, size,
  9};
 10use project::WorktreeId;
 11use settings::{SettingsContent, SettingsStore};
 12use std::path::Path;
 13use ui::{
 14    ActiveTheme as _, AnyElement, BorrowAppContext as _, Button, Clickable as _, Color,
 15    FluentBuilder as _, Icon, IconName, InteractiveElement as _, Label, LabelCommon as _,
 16    LabelSize, ParentElement, SharedString, StatefulInteractiveElement as _, Styled, Switch,
 17    v_flex,
 18};
 19
 20fn user_settings_data() -> Vec<SettingsPage> {
 21    vec![
 22        SettingsPage {
 23            title: "General Page",
 24            items: vec![
 25                SettingsPageItem::SectionHeader("General Section"),
 26                SettingsPageItem::SettingItem(SettingItem {
 27                    title: "Confirm Quit",
 28                    description: "Whether to confirm before quitting Zed",
 29                    render: Rc::new(|_, cx| {
 30                        render_toggle_button(
 31                            "confirm_quit",
 32                            SettingsFile::User,
 33                            cx,
 34                            |settings_content| &mut settings_content.workspace.confirm_quit,
 35                        )
 36                    }),
 37                }),
 38                SettingsPageItem::SettingItem(SettingItem {
 39                    title: "Auto Update",
 40                    description: "Automatically update Zed (may be ignored on Linux if installed through a package manager)",
 41                    render: Rc::new(|_, cx| {
 42                        render_toggle_button(
 43                            "Auto Update",
 44                            SettingsFile::User,
 45                            cx,
 46                            |settings_content| &mut settings_content.auto_update,
 47                        )
 48                    }),
 49                }),
 50            ],
 51        },
 52        SettingsPage {
 53            title: "Project",
 54            items: vec![
 55                SettingsPageItem::SectionHeader("Worktree Settings Content"),
 56                SettingsPageItem::SettingItem(SettingItem {
 57                    title: "Project Name",
 58                    description: "The displayed name of this project. If not set, the root directory name",
 59                    render: Rc::new(|window, cx| {
 60                        render_text_field(
 61                            "project_name",
 62                            SettingsFile::User,
 63                            window,
 64                            cx,
 65                            |settings_content| &mut settings_content.project.worktree.project_name,
 66                        )
 67                    }),
 68                }),
 69            ],
 70        },
 71    ]
 72}
 73
 74fn project_settings_data() -> Vec<SettingsPage> {
 75    vec![SettingsPage {
 76        title: "Project",
 77        items: vec![
 78            SettingsPageItem::SectionHeader("Worktree Settings Content"),
 79            SettingsPageItem::SettingItem(SettingItem {
 80                title: "Project Name",
 81                description: " The displayed name of this project. If not set, the root directory name",
 82                render: Rc::new(|window, cx| {
 83                    render_text_field(
 84                        "project_name",
 85                        SettingsFile::Local((
 86                            WorktreeId::from_usize(0),
 87                            Arc::from(Path::new("TODO: actually pass through file")),
 88                        )),
 89                        window,
 90                        cx,
 91                        |settings_content| &mut settings_content.project.worktree.project_name,
 92                    )
 93                }),
 94            }),
 95        ],
 96    }]
 97}
 98
 99pub struct SettingsUiFeatureFlag;
100
101impl FeatureFlag for SettingsUiFeatureFlag {
102    const NAME: &'static str = "settings-ui";
103}
104
105actions!(
106    zed,
107    [
108        /// Opens Settings Editor.
109        OpenSettingsEditor
110    ]
111);
112
113pub fn init(cx: &mut App) {
114    cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
115        workspace.register_action_renderer(|div, _, _, cx| {
116            let settings_ui_actions = [std::any::TypeId::of::<OpenSettingsEditor>()];
117            let has_flag = cx.has_flag::<SettingsUiFeatureFlag>();
118            command_palette_hooks::CommandPaletteFilter::update_global(cx, |filter, _| {
119                if has_flag {
120                    filter.show_action_types(&settings_ui_actions);
121                } else {
122                    filter.hide_action_types(&settings_ui_actions);
123                }
124            });
125            if has_flag {
126                div.on_action(cx.listener(|_, _: &OpenSettingsEditor, _, cx| {
127                    open_settings_editor(cx).ok();
128                }))
129            } else {
130                div
131            }
132        });
133    })
134    .detach();
135}
136
137pub fn open_settings_editor(cx: &mut App) -> anyhow::Result<WindowHandle<SettingsWindow>> {
138    cx.open_window(
139        WindowOptions {
140            titlebar: None,
141            focus: true,
142            show: true,
143            kind: gpui::WindowKind::Normal,
144            window_min_size: Some(size(px(300.), px(500.))), // todo(settings_ui): Does this min_size make sense?
145            ..Default::default()
146        },
147        |window, cx| cx.new(|cx| SettingsWindow::new(window, cx)),
148    )
149}
150
151pub struct SettingsWindow {
152    files: Vec<SettingsFile>,
153    current_file: SettingsFile,
154    pages: Vec<SettingsPage>,
155    search: Entity<Editor>,
156    current_page: usize, // Index into pages - should probably be (usize, Option<usize>) for section + page
157}
158
159#[derive(Clone)]
160struct SettingsPage {
161    title: &'static str,
162    items: Vec<SettingsPageItem>,
163}
164
165#[derive(Clone)]
166enum SettingsPageItem {
167    SectionHeader(&'static str),
168    SettingItem(SettingItem),
169}
170
171impl SettingsPageItem {
172    fn render(&self, window: &mut Window, cx: &mut App) -> AnyElement {
173        match self {
174            SettingsPageItem::SectionHeader(header) => Label::new(SharedString::new_static(header))
175                .size(LabelSize::Large)
176                .into_any_element(),
177            SettingsPageItem::SettingItem(setting_item) => div()
178                .child(setting_item.title)
179                .child(setting_item.description)
180                .child((setting_item.render)(window, cx))
181                .into_any_element(),
182        }
183    }
184}
185
186impl SettingsPageItem {
187    fn _header(&self) -> Option<&'static str> {
188        match self {
189            SettingsPageItem::SectionHeader(header) => Some(header),
190            _ => None,
191        }
192    }
193}
194
195#[derive(Clone)]
196struct SettingItem {
197    title: &'static str,
198    description: &'static str,
199    render: std::rc::Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>,
200}
201
202#[allow(unused)]
203#[derive(Clone)]
204enum SettingsFile {
205    User,                           // Uses all settings.
206    Local((WorktreeId, Arc<Path>)), // Has a special name, and special set of settings
207    Server(&'static str),           // Uses a special name, and the user settings
208}
209
210impl SettingsFile {
211    fn pages(&self) -> Vec<SettingsPage> {
212        match self {
213            SettingsFile::User => user_settings_data(),
214            SettingsFile::Local(_) => project_settings_data(),
215            SettingsFile::Server(_) => user_settings_data(),
216        }
217    }
218
219    fn name(&self) -> String {
220        match self {
221            SettingsFile::User => "User".to_string(),
222            SettingsFile::Local((_, path)) => format!("Local ({})", path.display()),
223            SettingsFile::Server(file) => format!("Server ({})", file),
224        }
225    }
226}
227
228impl SettingsWindow {
229    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
230        let current_file = SettingsFile::User;
231        let search = cx.new(|cx| {
232            let mut editor = Editor::single_line(window, cx);
233            editor.set_placeholder_text("Search Settings", window, cx);
234            editor
235        });
236        let mut this = Self {
237            files: vec![
238                SettingsFile::User,
239                SettingsFile::Local((
240                    WorktreeId::from_usize(0),
241                    Arc::from(Path::new("/my-project/")),
242                )),
243            ],
244            current_file: current_file,
245            pages: vec![],
246            current_page: 0,
247            search,
248        };
249        cx.observe_global_in::<SettingsStore>(window, move |_, _, cx| {
250            cx.notify();
251        })
252        .detach();
253
254        this.build_ui();
255        this
256    }
257
258    fn build_ui(&mut self) {
259        self.pages = self.current_file.pages();
260    }
261
262    fn change_file(&mut self, ix: usize) {
263        self.current_file = self.files[ix].clone();
264        self.build_ui();
265    }
266
267    fn render_files(&self, _window: &mut Window, cx: &mut Context<SettingsWindow>) -> Div {
268        div()
269            .flex()
270            .flex_row()
271            .gap_1()
272            .children(self.files.iter().enumerate().map(|(ix, file)| {
273                Button::new(ix, file.name())
274                    .on_click(cx.listener(move |this, _, _window, _cx| this.change_file(ix)))
275            }))
276    }
277
278    fn render_search(&self, _window: &mut Window, _cx: &mut App) -> Div {
279        div()
280            .child(Icon::new(IconName::MagnifyingGlass))
281            .child(self.search.clone())
282    }
283
284    fn render_nav(&self, window: &mut Window, cx: &mut Context<SettingsWindow>) -> Div {
285        let mut nav = v_flex()
286            .p_4()
287            .gap_2()
288            .child(div().h_10()) // Files spacer;
289            .child(self.render_search(window, cx));
290
291        for (ix, page) in self.pages.iter().enumerate() {
292            nav = nav.child(
293                div()
294                    .id(page.title)
295                    .child(
296                        Label::new(page.title)
297                            .size(LabelSize::Large)
298                            .when(self.is_page_selected(ix), |this| {
299                                this.color(Color::Selected)
300                            }),
301                    )
302                    .on_click(cx.listener(move |this, _, _, cx| {
303                        this.current_page = ix;
304                        cx.notify();
305                    })),
306            );
307        }
308        nav
309    }
310
311    fn render_page(
312        &self,
313        page: &SettingsPage,
314        window: &mut Window,
315        cx: &mut Context<SettingsWindow>,
316    ) -> Div {
317        div()
318            .child(self.render_files(window, cx))
319            .child(Label::new(page.title))
320            .children(page.items.iter().map(|item| item.render(window, cx)))
321    }
322
323    fn current_page(&self) -> &SettingsPage {
324        &self.pages[self.current_page]
325    }
326
327    fn is_page_selected(&self, ix: usize) -> bool {
328        ix == self.current_page
329    }
330}
331
332impl Render for SettingsWindow {
333    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
334        div()
335            .size_full()
336            .bg(cx.theme().colors().background)
337            .flex()
338            .flex_row()
339            .text_color(cx.theme().colors().text)
340            .child(self.render_nav(window, cx).w(px(300.0)))
341            .child(self.render_page(self.current_page(), window, cx).w_full())
342    }
343}
344
345fn write_setting_value<T: Send + 'static>(
346    get_value: fn(&mut SettingsContent) -> &mut Option<T>,
347    value: Option<T>,
348    cx: &mut App,
349) {
350    cx.update_global(|store: &mut SettingsStore, cx| {
351        store.update_settings_file(<dyn fs::Fs>::global(cx), move |settings, _cx| {
352            *get_value(settings) = value;
353        });
354    });
355}
356
357fn render_text_field(
358    id: &'static str,
359    _file: SettingsFile,
360    window: &mut Window,
361    cx: &mut App,
362    get_value: fn(&mut SettingsContent) -> &mut Option<String>,
363) -> AnyElement {
364    // TODO: Updating file does not cause the editor text to reload, suspicious it may be a missing global update/notify in SettingsStore
365
366    // TODO: in settings window state
367    let store = SettingsStore::global(cx);
368
369    // TODO: This clone needs to go!!
370    let mut defaults = store.raw_default_settings().clone();
371    let mut user_settings = store
372        .raw_user_settings()
373        .cloned()
374        .unwrap_or_default()
375        .content;
376
377    // TODO: unwrap_or_default here because project name is null
378    let initial_text = get_value(user_settings.as_mut())
379        .clone()
380        .unwrap_or_else(|| get_value(&mut defaults).clone().unwrap_or_default());
381
382    let editor = window.use_keyed_state((id.into(), initial_text.clone()), cx, {
383        move |window, cx| {
384            let mut editor = Editor::single_line(window, cx);
385            editor.set_text(initial_text, window, cx);
386            editor
387        }
388    });
389
390    let weak_editor = editor.downgrade();
391    let theme_colors = cx.theme().colors();
392
393    div()
394        .child(editor)
395        .bg(theme_colors.editor_background)
396        .border_1()
397        .rounded_lg()
398        .border_color(theme_colors.border)
399        .on_action::<menu::Confirm>({
400            move |_, _, cx| {
401                let Some(editor) = weak_editor.upgrade() else {
402                    return;
403                };
404                let new_value = editor.read_with(cx, |editor, cx| editor.text(cx));
405                let new_value = (!new_value.is_empty()).then_some(new_value);
406                write_setting_value(get_value, new_value, cx);
407                editor.update(cx, |_, cx| {
408                    cx.notify();
409                });
410            }
411        })
412        .into_any_element()
413}
414
415fn render_toggle_button(
416    id: &'static str,
417    _: SettingsFile,
418    cx: &mut App,
419    get_value: fn(&mut SettingsContent) -> &mut Option<bool>,
420) -> AnyElement {
421    // TODO: in settings window state
422    let store = SettingsStore::global(cx);
423
424    // TODO: This clone needs to go!!
425    let mut defaults = store.raw_default_settings().clone();
426    let mut user_settings = store
427        .raw_user_settings()
428        .cloned()
429        .unwrap_or_default()
430        .content;
431
432    let toggle_state =
433        if get_value(&mut user_settings).unwrap_or_else(|| get_value(&mut defaults).unwrap()) {
434            ui::ToggleState::Selected
435        } else {
436            ui::ToggleState::Unselected
437        };
438
439    Switch::new(id, toggle_state)
440        .on_click({
441            move |state, _window, cx| {
442                write_setting_value(get_value, Some(*state == ui::ToggleState::Selected), cx);
443            }
444        })
445        .into_any_element()
446}