theme_selector.rs

  1use fs::Fs;
  2use fuzzy::{match_strings, StringMatch, StringMatchCandidate};
  3use gpui::{actions, elements::*, AnyElement, AppContext, Element, MouseState, ViewContext};
  4use picker::{Picker, PickerDelegate, PickerEvent};
  5use settings::{update_settings_file, Settings};
  6use staff_mode::StaffMode;
  7use std::sync::Arc;
  8use theme::{Theme, ThemeMeta, ThemeRegistry};
  9use util::ResultExt;
 10use workspace::Workspace;
 11
 12actions!(theme_selector, [Toggle, Reload]);
 13
 14pub fn init(cx: &mut AppContext) {
 15    cx.add_action(toggle);
 16    ThemeSelector::init(cx);
 17}
 18
 19pub fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
 20    workspace.toggle_modal(cx, |workspace, cx| {
 21        let themes = workspace.app_state().themes.clone();
 22        let fs = workspace.app_state().fs.clone();
 23        cx.add_view(|cx| ThemeSelector::new(ThemeSelectorDelegate::new(fs, themes, cx), cx))
 24    });
 25}
 26
 27#[cfg(debug_assertions)]
 28pub fn reload(themes: Arc<ThemeRegistry>, cx: &mut AppContext) {
 29    let current_theme_name = cx.global::<Settings>().theme.meta.name.clone();
 30    themes.clear();
 31    match themes.get(&current_theme_name) {
 32        Ok(theme) => {
 33            ThemeSelectorDelegate::set_theme(theme, cx);
 34            log::info!("reloaded theme {}", current_theme_name);
 35        }
 36        Err(error) => {
 37            log::error!("failed to load theme {}: {:?}", current_theme_name, error)
 38        }
 39    }
 40}
 41
 42pub type ThemeSelector = Picker<ThemeSelectorDelegate>;
 43
 44pub struct ThemeSelectorDelegate {
 45    fs: Arc<dyn Fs>,
 46    registry: Arc<ThemeRegistry>,
 47    theme_data: Vec<ThemeMeta>,
 48    matches: Vec<StringMatch>,
 49    original_theme: Arc<Theme>,
 50    selection_completed: bool,
 51    selected_index: usize,
 52}
 53
 54impl ThemeSelectorDelegate {
 55    fn new(
 56        fs: Arc<dyn Fs>,
 57        registry: Arc<ThemeRegistry>,
 58        cx: &mut ViewContext<ThemeSelector>,
 59    ) -> Self {
 60        let settings = cx.global::<Settings>();
 61
 62        let original_theme = settings.theme.clone();
 63
 64        let mut theme_names = registry
 65            .list(**cx.default_global::<StaffMode>())
 66            .collect::<Vec<_>>();
 67        theme_names.sort_unstable_by(|a, b| a.is_light.cmp(&b.is_light).then(a.name.cmp(&b.name)));
 68        let matches = theme_names
 69            .iter()
 70            .map(|meta| StringMatch {
 71                candidate_id: 0,
 72                score: 0.0,
 73                positions: Default::default(),
 74                string: meta.name.clone(),
 75            })
 76            .collect();
 77        let mut this = Self {
 78            fs,
 79            registry,
 80            theme_data: theme_names,
 81            matches,
 82            original_theme: original_theme.clone(),
 83            selected_index: 0,
 84            selection_completed: false,
 85        };
 86        this.select_if_matching(&original_theme.meta.name);
 87        this
 88    }
 89
 90    fn show_selected_theme(&mut self, cx: &mut ViewContext<ThemeSelector>) {
 91        if let Some(mat) = self.matches.get(self.selected_index) {
 92            match self.registry.get(&mat.string) {
 93                Ok(theme) => {
 94                    Self::set_theme(theme, cx);
 95                }
 96                Err(error) => {
 97                    log::error!("error loading theme {}: {}", mat.string, error)
 98                }
 99            }
100        }
101    }
102
103    fn select_if_matching(&mut self, theme_name: &str) {
104        self.selected_index = self
105            .matches
106            .iter()
107            .position(|mat| mat.string == theme_name)
108            .unwrap_or(self.selected_index);
109    }
110
111    fn set_theme(theme: Arc<Theme>, cx: &mut AppContext) {
112        cx.update_global::<Settings, _, _>(|settings, cx| {
113            settings.theme = theme;
114            cx.refresh_windows();
115        });
116    }
117}
118
119impl PickerDelegate for ThemeSelectorDelegate {
120    fn placeholder_text(&self) -> Arc<str> {
121        "Select Theme...".into()
122    }
123
124    fn match_count(&self) -> usize {
125        self.matches.len()
126    }
127
128    fn confirm(&mut self, cx: &mut ViewContext<ThemeSelector>) {
129        self.selection_completed = true;
130
131        let theme_name = cx.global::<Settings>().theme.meta.name.clone();
132        update_settings_file(self.fs.clone(), cx, |settings_content| {
133            settings_content.theme = Some(theme_name);
134        });
135
136        cx.emit(PickerEvent::Dismiss);
137    }
138
139    fn dismissed(&mut self, cx: &mut ViewContext<ThemeSelector>) {
140        if !self.selection_completed {
141            Self::set_theme(self.original_theme.clone(), cx);
142            self.selection_completed = true;
143        }
144    }
145
146    fn selected_index(&self) -> usize {
147        self.selected_index
148    }
149
150    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<ThemeSelector>) {
151        self.selected_index = ix;
152        self.show_selected_theme(cx);
153    }
154
155    fn update_matches(
156        &mut self,
157        query: String,
158        cx: &mut ViewContext<ThemeSelector>,
159    ) -> gpui::Task<()> {
160        let background = cx.background().clone();
161        let candidates = self
162            .theme_data
163            .iter()
164            .enumerate()
165            .map(|(id, meta)| StringMatchCandidate {
166                id,
167                char_bag: meta.name.as_str().into(),
168                string: meta.name.clone(),
169            })
170            .collect::<Vec<_>>();
171
172        cx.spawn(|this, mut cx| async move {
173            let matches = if query.is_empty() {
174                candidates
175                    .into_iter()
176                    .enumerate()
177                    .map(|(index, candidate)| StringMatch {
178                        candidate_id: index,
179                        string: candidate.string,
180                        positions: Vec::new(),
181                        score: 0.0,
182                    })
183                    .collect()
184            } else {
185                match_strings(
186                    &candidates,
187                    &query,
188                    false,
189                    100,
190                    &Default::default(),
191                    background,
192                )
193                .await
194            };
195
196            this.update(&mut cx, |this, cx| {
197                let delegate = this.delegate_mut();
198                delegate.matches = matches;
199                delegate.selected_index = delegate
200                    .selected_index
201                    .min(delegate.matches.len().saturating_sub(1));
202                delegate.show_selected_theme(cx);
203            })
204            .log_err();
205        })
206    }
207
208    fn render_match(
209        &self,
210        ix: usize,
211        mouse_state: &mut MouseState,
212        selected: bool,
213        cx: &AppContext,
214    ) -> AnyElement<Picker<Self>> {
215        let settings = cx.global::<Settings>();
216        let theme = &settings.theme;
217        let theme_match = &self.matches[ix];
218        let style = theme.picker.item.style_for(mouse_state, selected);
219
220        Label::new(theme_match.string.clone(), style.label.clone())
221            .with_highlights(theme_match.positions.clone())
222            .contained()
223            .with_style(style.container)
224            .into_any()
225    }
226}