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