1use editor::Editor;
2use encoding_rs::{Encoding, UTF_8};
3use gpui::{
4 Context, Entity, IntoElement, ParentElement, Render, Styled, Subscription, Window, div,
5};
6use ui::{Button, ButtonCommon, Clickable, LabelSize, Tooltip};
7use workspace::{
8 StatusBarSettings, StatusItemView, Workspace,
9 item::{ItemHandle, Settings},
10};
11
12pub struct ActiveBufferEncoding {
13 active_encoding: Option<&'static Encoding>,
14 //workspace: WeakEntity<Workspace>,
15 _observe_active_editor: Option<Subscription>,
16 has_bom: bool,
17}
18
19impl ActiveBufferEncoding {
20 pub fn new(_workspace: &Workspace) -> Self {
21 Self {
22 active_encoding: None,
23 //workspace: workspace.weak_handle(),
24 _observe_active_editor: None,
25 has_bom: false,
26 }
27 }
28
29 fn update_encoding(&mut self, editor: Entity<Editor>, _: &mut Window, cx: &mut Context<Self>) {
30 self.active_encoding = None;
31
32 let editor = editor.read(cx);
33 if let Some((_, buffer, _)) = editor.active_excerpt(cx) {
34 let buffer = buffer.read(cx);
35
36 self.active_encoding = Some(buffer.encoding());
37 self.has_bom = buffer.has_bom();
38 }
39
40 cx.notify();
41 }
42}
43
44impl Render for ActiveBufferEncoding {
45 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
46 let Some(active_encoding) = self.active_encoding else {
47 return div().hidden();
48 };
49
50 let display_option = StatusBarSettings::get_global(cx).active_encoding_button;
51 let is_utf8 = active_encoding == UTF_8;
52 if !display_option.should_show(is_utf8, self.has_bom) {
53 return div().hidden();
54 }
55
56 let mut text = active_encoding.name().to_string();
57 if self.has_bom {
58 text.push_str(" (BOM)");
59 }
60
61 div().child(
62 Button::new("change-encoding", text)
63 .label_size(LabelSize::Small)
64 .on_click(|_, _, _cx| {
65 // No-op
66 })
67 .tooltip(Tooltip::text("Current Encoding")),
68 )
69 }
70}
71
72impl StatusItemView for ActiveBufferEncoding {
73 fn set_active_pane_item(
74 &mut self,
75 active_pane_item: Option<&dyn ItemHandle>,
76 window: &mut Window,
77 cx: &mut Context<Self>,
78 ) {
79 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
80 self._observe_active_editor =
81 Some(cx.observe_in(&editor, window, Self::update_encoding));
82 self.update_encoding(editor, window, cx);
83 } else {
84 self.active_encoding = None;
85 self.has_bom = false;
86 self._observe_active_editor = None;
87 }
88
89 cx.notify();
90 }
91}