1use editor::Editor;
2use gpui::{
3 elements::*,
4 platform::{CursorStyle, MouseButton},
5 Entity, Subscription, View, ViewContext, ViewHandle, WeakViewHandle,
6};
7use std::sync::Arc;
8use workspace::{item::ItemHandle, StatusItemView, Workspace};
9
10pub struct ActiveBufferLanguage {
11 active_language: Option<Option<Arc<str>>>,
12 workspace: WeakViewHandle<Workspace>,
13 _observe_active_editor: Option<Subscription>,
14}
15
16impl ActiveBufferLanguage {
17 pub fn new(workspace: &Workspace) -> Self {
18 Self {
19 active_language: None,
20 workspace: workspace.weak_handle(),
21 _observe_active_editor: None,
22 }
23 }
24
25 fn update_language(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
26 self.active_language = Some(None);
27
28 let editor = editor.read(cx);
29 if let Some((_, buffer, _)) = editor.active_excerpt(cx) {
30 if let Some(language) = buffer.read(cx).language() {
31 self.active_language = Some(Some(language.name()));
32 }
33 }
34
35 cx.notify();
36 }
37}
38
39impl Entity for ActiveBufferLanguage {
40 type Event = ();
41}
42
43impl View for ActiveBufferLanguage {
44 fn ui_name() -> &'static str {
45 "ActiveBufferLanguage"
46 }
47
48 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
49 if let Some(active_language) = self.active_language.as_ref() {
50 let active_language_text = if let Some(active_language_text) = active_language {
51 active_language_text.to_string()
52 } else {
53 "Unknown".to_string()
54 };
55 let theme = theme::current(cx).clone();
56
57 MouseEventHandler::new::<Self, _>(0, cx, |state, cx| {
58 let theme = &theme::current(cx).workspace.status_bar;
59 let style = theme.active_language.style_for(state);
60 Label::new(active_language_text, style.text.clone())
61 .contained()
62 .with_style(style.container)
63 })
64 .with_cursor_style(CursorStyle::PointingHand)
65 .on_click(MouseButton::Left, |_, this, cx| {
66 if let Some(workspace) = this.workspace.upgrade(cx) {
67 workspace.update(cx, |workspace, cx| {
68 crate::toggle(workspace, &Default::default(), cx)
69 });
70 }
71 })
72 .with_tooltip::<Self>(0, "Select Language", None, theme.tooltip.clone(), cx)
73 .into_any()
74 } else {
75 Empty::new().into_any()
76 }
77 }
78}
79
80impl StatusItemView for ActiveBufferLanguage {
81 fn set_active_pane_item(
82 &mut self,
83 active_pane_item: Option<&dyn ItemHandle>,
84 cx: &mut ViewContext<Self>,
85 ) {
86 if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
87 self._observe_active_editor = Some(cx.observe(&editor, Self::update_language));
88 self.update_language(editor, cx);
89 } else {
90 self.active_language = None;
91 self._observe_active_editor = None;
92 }
93
94 cx.notify();
95 }
96}