1/// This module contains the encoding selectors for saving or reopening files with a different encoding.
2/// It provides a modal view that allows the user to choose between saving with a different encoding
3/// or reopening with a different encoding, and then selecting the desired encoding from a list.
4pub mod save_or_reopen {
5 use editor::Editor;
6 use gpui::Styled;
7 use gpui::{AppContext, ParentElement};
8 use picker::Picker;
9 use picker::PickerDelegate;
10 use std::sync::atomic::AtomicBool;
11 use util::ResultExt;
12
13 use fuzzy::{StringMatch, StringMatchCandidate};
14 use gpui::{DismissEvent, Entity, EventEmitter, Focusable, WeakEntity};
15
16 use ui::{Context, HighlightedLabel, ListItem, Render, Window, rems, v_flex};
17 use workspace::{ModalView, Workspace};
18
19 use crate::selectors::encoding::{Action, EncodingSelector};
20
21 /// A modal view that allows the user to select between saving with a different encoding or
22 /// reopening with a different encoding.
23 pub struct EncodingSaveOrReopenSelector {
24 picker: Entity<Picker<EncodingSaveOrReopenDelegate>>,
25 pub current_selection: usize,
26 }
27
28 impl EncodingSaveOrReopenSelector {
29 pub fn new(
30 window: &mut Window,
31 cx: &mut Context<EncodingSaveOrReopenSelector>,
32 workspace: WeakEntity<Workspace>,
33 ) -> Self {
34 let delegate = EncodingSaveOrReopenDelegate::new(cx.entity().downgrade(), workspace);
35
36 let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
37
38 Self {
39 picker,
40 current_selection: 0,
41 }
42 }
43
44 /// Toggle the modal view for selecting between saving with a different encoding or
45 /// reopening with a different encoding.
46 pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
47 let weak_workspace = workspace.weak_handle();
48 workspace.toggle_modal(window, cx, |window, cx| {
49 EncodingSaveOrReopenSelector::new(window, cx, weak_workspace)
50 });
51 }
52 }
53
54 impl Focusable for EncodingSaveOrReopenSelector {
55 fn focus_handle(&self, cx: &ui::App) -> gpui::FocusHandle {
56 self.picker.focus_handle(cx)
57 }
58 }
59
60 impl Render for EncodingSaveOrReopenSelector {
61 fn render(
62 &mut self,
63 _window: &mut Window,
64 _cx: &mut Context<Self>,
65 ) -> impl ui::IntoElement {
66 v_flex().w(rems(34.0)).child(self.picker.clone())
67 }
68 }
69
70 impl ModalView for EncodingSaveOrReopenSelector {}
71
72 impl EventEmitter<DismissEvent> for EncodingSaveOrReopenSelector {}
73
74 pub struct EncodingSaveOrReopenDelegate {
75 selector: WeakEntity<EncodingSaveOrReopenSelector>,
76 current_selection: usize,
77 matches: Vec<StringMatch>,
78 pub actions: Vec<StringMatchCandidate>,
79 workspace: WeakEntity<Workspace>,
80 }
81
82 impl EncodingSaveOrReopenDelegate {
83 pub fn new(
84 selector: WeakEntity<EncodingSaveOrReopenSelector>,
85 workspace: WeakEntity<Workspace>,
86 ) -> Self {
87 Self {
88 selector,
89 current_selection: 0,
90 matches: Vec::new(),
91 actions: vec![
92 StringMatchCandidate::new(0, "Save with encoding"),
93 StringMatchCandidate::new(1, "Reopen with encoding"),
94 ],
95 workspace,
96 }
97 }
98
99 pub fn get_actions(&self) -> (&str, &str) {
100 (&self.actions[0].string, &self.actions[1].string)
101 }
102
103 /// Handle the action selected by the user.
104 pub fn post_selection(
105 &self,
106 cx: &mut Context<Picker<EncodingSaveOrReopenDelegate>>,
107 window: &mut Window,
108 ) -> Option<()> {
109 if self.current_selection == 0 {
110 if let Some(workspace) = self.workspace.upgrade() {
111 let (_, buffer, _) = workspace
112 .read(cx)
113 .active_item(cx)?
114 .act_as::<Editor>(cx)?
115 .read(cx)
116 .active_excerpt(cx)?;
117
118 let weak_workspace = workspace.read(cx).weak_handle();
119
120 workspace.update(cx, |workspace, cx| {
121 workspace.toggle_modal(window, cx, |window, cx| {
122 let selector = EncodingSelector::new(
123 window,
124 cx,
125 Action::Save,
126 buffer.downgrade(),
127 weak_workspace,
128 );
129 selector
130 })
131 });
132 }
133 } else if self.current_selection == 1 {
134 if let Some(workspace) = self.workspace.upgrade() {
135 let (_, buffer, _) = workspace
136 .read(cx)
137 .active_item(cx)?
138 .act_as::<Editor>(cx)?
139 .read(cx)
140 .active_excerpt(cx)?;
141
142 let weak_workspace = workspace.read(cx).weak_handle();
143
144 workspace.update(cx, |workspace, cx| {
145 workspace.toggle_modal(window, cx, |window, cx| {
146 let selector = EncodingSelector::new(
147 window,
148 cx,
149 Action::Reopen,
150 buffer.downgrade(),
151 weak_workspace,
152 );
153 selector
154 });
155 });
156 }
157 }
158
159 Some(())
160 }
161 }
162
163 impl PickerDelegate for EncodingSaveOrReopenDelegate {
164 type ListItem = ListItem;
165
166 fn match_count(&self) -> usize {
167 self.matches.len()
168 }
169
170 fn selected_index(&self) -> usize {
171 self.current_selection
172 }
173
174 fn set_selected_index(
175 &mut self,
176 ix: usize,
177 _window: &mut Window,
178 cx: &mut Context<Picker<Self>>,
179 ) {
180 self.current_selection = ix;
181 self.selector
182 .update(cx, |selector, _cx| {
183 selector.current_selection = ix;
184 })
185 .log_err();
186 }
187
188 fn placeholder_text(&self, _window: &mut Window, _cx: &mut ui::App) -> std::sync::Arc<str> {
189 "Select an action...".into()
190 }
191
192 fn update_matches(
193 &mut self,
194 query: String,
195 window: &mut Window,
196 cx: &mut Context<Picker<Self>>,
197 ) -> gpui::Task<()> {
198 let executor = cx.background_executor().clone();
199 let actions = self.actions.clone();
200
201 cx.spawn_in(window, async move |this, cx| {
202 let matches = if query.is_empty() {
203 actions
204 .into_iter()
205 .enumerate()
206 .map(|(index, value)| StringMatch {
207 candidate_id: index,
208 score: 0.0,
209 positions: vec![],
210 string: value.string,
211 })
212 .collect::<Vec<StringMatch>>()
213 } else {
214 fuzzy::match_strings(
215 &actions,
216 &query,
217 false,
218 false,
219 2,
220 &AtomicBool::new(false),
221 executor,
222 )
223 .await
224 };
225
226 this.update(cx, |picker, cx| {
227 let delegate = &mut picker.delegate;
228 delegate.matches = matches;
229 delegate.current_selection = delegate
230 .current_selection
231 .min(delegate.matches.len().saturating_sub(1));
232 delegate
233 .selector
234 .update(cx, |selector, _cx| {
235 selector.current_selection = delegate.current_selection
236 })
237 .log_err();
238 cx.notify();
239 })
240 .log_err();
241 })
242 }
243
244 fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
245 self.dismissed(window, cx);
246 if self.selector.is_upgradable() {
247 self.post_selection(cx, window);
248 }
249 }
250
251 fn dismissed(&mut self, _window: &mut Window, cx: &mut Context<Picker<Self>>) {
252 self.selector
253 .update(cx, |_, cx| cx.emit(DismissEvent))
254 .log_err();
255 }
256
257 fn render_match(
258 &self,
259 ix: usize,
260 _: bool,
261 _: &mut Window,
262 _: &mut Context<Picker<Self>>,
263 ) -> Option<Self::ListItem> {
264 Some(
265 ListItem::new(ix)
266 .child(HighlightedLabel::new(
267 &self.matches[ix].string,
268 self.matches[ix].positions.clone(),
269 ))
270 .spacing(ui::ListItemSpacing::Sparse),
271 )
272 }
273 }
274
275 pub fn get_current_encoding() -> &'static str {
276 "UTF-8"
277 }
278}
279
280/// This module contains the encoding selector for choosing an encoding to save or reopen a file with.
281pub mod encoding {
282 use std::sync::atomic::AtomicBool;
283
284 use fuzzy::{StringMatch, StringMatchCandidate};
285 use gpui::{AppContext, DismissEvent, Entity, EventEmitter, Focusable, WeakEntity};
286 use language::Buffer;
287 use picker::{Picker, PickerDelegate};
288 use ui::{
289 Context, HighlightedLabel, ListItem, ListItemSpacing, ParentElement, Render, Styled,
290 Window, rems, v_flex,
291 };
292 use util::{ResultExt, TryFutureExt};
293 use workspace::{ModalView, Workspace};
294
295 use crate::encoding_from_name;
296
297 /// A modal view that allows the user to select an encoding from a list of encodings.
298 pub struct EncodingSelector {
299 picker: Entity<Picker<EncodingSelectorDelegate>>,
300 workspace: WeakEntity<Workspace>,
301 }
302
303 pub struct EncodingSelectorDelegate {
304 current_selection: usize,
305 encodings: Vec<StringMatchCandidate>,
306 matches: Vec<StringMatch>,
307 selector: WeakEntity<EncodingSelector>,
308 buffer: WeakEntity<Buffer>,
309 action: Action,
310 }
311
312 impl EncodingSelectorDelegate {
313 pub fn new(
314 selector: WeakEntity<EncodingSelector>,
315 buffer: WeakEntity<Buffer>,
316 action: Action,
317 ) -> EncodingSelectorDelegate {
318 EncodingSelectorDelegate {
319 current_selection: 0,
320 encodings: vec![
321 StringMatchCandidate::new(0, "UTF-8"),
322 StringMatchCandidate::new(1, "Windows-1252"),
323 StringMatchCandidate::new(2, "Windows-1251"),
324 StringMatchCandidate::new(3, "Windows-1250"),
325 StringMatchCandidate::new(4, "ISO 8859-2"),
326 StringMatchCandidate::new(5, "ISO 8859-3"),
327 StringMatchCandidate::new(6, "ISO 8859-4"),
328 StringMatchCandidate::new(7, "ISO 8859-5"),
329 StringMatchCandidate::new(8, "ISO 8859-6"),
330 StringMatchCandidate::new(9, "ISO 8859-7"),
331 StringMatchCandidate::new(10, "ISO 8859-8"),
332 StringMatchCandidate::new(11, "ISO 8859-13"),
333 StringMatchCandidate::new(12, "ISO 8859-15"),
334 StringMatchCandidate::new(13, "KOI8-R"),
335 StringMatchCandidate::new(14, "KOI8-U"),
336 StringMatchCandidate::new(15, "MacRoman"),
337 StringMatchCandidate::new(16, "Mac Cyrillic"),
338 StringMatchCandidate::new(17, "Windows-874"),
339 StringMatchCandidate::new(18, "Windows-1253"),
340 StringMatchCandidate::new(19, "Windows-1254"),
341 StringMatchCandidate::new(20, "Windows-1255"),
342 StringMatchCandidate::new(21, "Windows-1256"),
343 StringMatchCandidate::new(22, "Windows-1257"),
344 StringMatchCandidate::new(23, "Windows-1258"),
345 StringMatchCandidate::new(24, "Windows-949"),
346 StringMatchCandidate::new(25, "EUC-JP"),
347 StringMatchCandidate::new(26, "ISO 2022-JP"),
348 StringMatchCandidate::new(27, "GBK"),
349 StringMatchCandidate::new(28, "GB18030"),
350 StringMatchCandidate::new(29, "Big5"),
351 ],
352 matches: Vec::new(),
353 selector,
354 buffer,
355 action,
356 }
357 }
358 }
359
360 impl PickerDelegate for EncodingSelectorDelegate {
361 type ListItem = ListItem;
362
363 fn match_count(&self) -> usize {
364 self.matches.len()
365 }
366
367 fn selected_index(&self) -> usize {
368 self.current_selection
369 }
370
371 fn set_selected_index(&mut self, ix: usize, _: &mut Window, _: &mut Context<Picker<Self>>) {
372 self.current_selection = ix;
373 }
374
375 fn placeholder_text(&self, _window: &mut Window, _cx: &mut ui::App) -> std::sync::Arc<str> {
376 "Select an encoding...".into()
377 }
378
379 fn update_matches(
380 &mut self,
381 query: String,
382 window: &mut Window,
383 cx: &mut Context<Picker<Self>>,
384 ) -> gpui::Task<()> {
385 let executor = cx.background_executor().clone();
386 let encodings = self.encodings.clone();
387
388 cx.spawn_in(window, async move |picker, cx| {
389 let matches: Vec<StringMatch>;
390
391 if query.is_empty() {
392 matches = encodings
393 .into_iter()
394 .enumerate()
395 .map(|(index, value)| StringMatch {
396 candidate_id: index,
397 score: 0.0,
398 positions: Vec::new(),
399 string: value.string,
400 })
401 .collect();
402 } else {
403 matches = fuzzy::match_strings(
404 &encodings,
405 &query,
406 true,
407 false,
408 30,
409 &AtomicBool::new(false),
410 executor,
411 )
412 .await
413 }
414
415 picker
416 .update(cx, |picker, cx| {
417 let delegate = &mut picker.delegate;
418 delegate.matches = matches;
419 delegate.current_selection = delegate
420 .current_selection
421 .min(delegate.matches.len().saturating_sub(1));
422 cx.notify();
423 })
424 .log_err();
425 })
426 }
427
428 fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
429 if let Some(buffer) = self.buffer.upgrade() {
430 buffer.update(cx, |buffer, cx| {
431 buffer.encoding =
432 encoding_from_name(self.matches[self.current_selection].string.as_str());
433 if self.action == Action::Reopen {
434 let executor = cx.background_executor().clone();
435 executor.spawn(buffer.reload(cx)).detach();
436 } else if self.action == Action::Save {
437 let executor = cx.background_executor().clone();
438
439 let workspace = self
440 .selector
441 .upgrade()
442 .unwrap()
443 .read(cx)
444 .workspace
445 .upgrade()
446 .unwrap();
447
448 executor
449 .spawn(workspace.update(cx, |workspace, cx| {
450 workspace
451 .save_active_item(workspace::SaveIntent::Save, window, cx)
452 .log_err()
453 }))
454 .detach();
455 }
456 });
457 }
458 self.dismissed(window, cx);
459 }
460
461 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
462 self.selector
463 .update(cx, |_, cx| cx.emit(DismissEvent))
464 .log_err();
465 }
466
467 fn render_match(
468 &self,
469 ix: usize,
470 _: bool,
471 _: &mut Window,
472 _: &mut Context<Picker<Self>>,
473 ) -> Option<Self::ListItem> {
474 Some(
475 ListItem::new(ix)
476 .child(HighlightedLabel::new(
477 &self.matches[ix].string,
478 self.matches[ix].positions.clone(),
479 ))
480 .spacing(ListItemSpacing::Sparse),
481 )
482 }
483 }
484
485 /// The action to perform after selecting an encoding.
486 #[derive(PartialEq, Clone)]
487 pub enum Action {
488 Save,
489 Reopen,
490 }
491
492 impl EncodingSelector {
493 pub fn new(
494 window: &mut Window,
495 cx: &mut Context<EncodingSelector>,
496 action: Action,
497 buffer: WeakEntity<Buffer>,
498 workspace: WeakEntity<Workspace>,
499 ) -> EncodingSelector {
500 let delegate = EncodingSelectorDelegate::new(cx.entity().downgrade(), buffer, action);
501 let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
502
503 EncodingSelector { picker, workspace }
504 }
505 }
506
507 impl EventEmitter<DismissEvent> for EncodingSelector {}
508
509 impl Focusable for EncodingSelector {
510 fn focus_handle(&self, cx: &ui::App) -> gpui::FocusHandle {
511 self.picker.focus_handle(cx)
512 }
513 }
514
515 impl ModalView for EncodingSelector {}
516
517 impl Render for EncodingSelector {
518 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl ui::IntoElement {
519 v_flex().w(rems(34.0)).child(self.picker.clone())
520 }
521 }
522}