editor_events.rs

 1use editor::{EditorBlurred, EditorCreated, EditorFocused, EditorMode, EditorReleased};
 2use gpui::MutableAppContext;
 3
 4use crate::{mode::Mode, SwitchMode, VimState};
 5
 6pub fn init(cx: &mut MutableAppContext) {
 7    cx.subscribe_global(editor_created).detach();
 8    cx.subscribe_global(editor_focused).detach();
 9    cx.subscribe_global(editor_blurred).detach();
10    cx.subscribe_global(editor_released).detach();
11}
12
13fn editor_created(EditorCreated(editor): &EditorCreated, cx: &mut MutableAppContext) {
14    cx.update_default_global(|vim_state: &mut VimState, cx| {
15        vim_state.editors.insert(editor.id(), editor.downgrade());
16        vim_state.sync_editor_options(cx);
17    })
18}
19
20fn editor_focused(EditorFocused(editor): &EditorFocused, cx: &mut MutableAppContext) {
21    let mode = if matches!(editor.read(cx).mode(), EditorMode::SingleLine) {
22        Mode::Insert
23    } else {
24        Mode::normal()
25    };
26
27    VimState::update_global(cx, |state, cx| {
28        state.active_editor = Some(editor.downgrade());
29        state.switch_mode(&SwitchMode(mode), cx);
30    });
31}
32
33fn editor_blurred(EditorBlurred(editor): &EditorBlurred, cx: &mut MutableAppContext) {
34    VimState::update_global(cx, |state, cx| {
35        if let Some(previous_editor) = state.active_editor.clone() {
36            if previous_editor == editor.clone() {
37                state.active_editor = None;
38            }
39        }
40        state.sync_editor_options(cx);
41    })
42}
43
44fn editor_released(EditorReleased(editor): &EditorReleased, cx: &mut MutableAppContext) {
45    cx.update_default_global(|vim_state: &mut VimState, _| {
46        vim_state.editors.remove(&editor.id());
47        if let Some(previous_editor) = vim_state.active_editor.clone() {
48            if previous_editor == editor.clone() {
49                vim_state.active_editor = None;
50            }
51        }
52    });
53}