active_buffer_language.rs

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