editor_events.rs

 1use editor::{EditorBlurred, EditorCreated, EditorFocused, EditorMode, EditorReleased};
 2use gpui::MutableAppContext;
 3
 4use crate::{state::Mode, Vim};
 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: &mut Vim, cx| {
15        vim.editors.insert(editor.id(), editor.downgrade());
16        vim.sync_editor_options(cx);
17    })
18}
19
20fn editor_focused(EditorFocused(editor): &EditorFocused, cx: &mut MutableAppContext) {
21    Vim::update(cx, |vim, cx| {
22        vim.active_editor = Some(editor.downgrade());
23        vim.selection_subscription = Some(cx.subscribe(editor, |editor, event, cx| {
24            if let editor::Event::SelectionsChanged { local: true } = event {
25                let newest_empty = editor.read(cx).selections.newest::<usize>(cx).is_empty();
26                editor_local_selections_changed(newest_empty, cx);
27            }
28        }));
29
30        if editor.read(cx).mode() != EditorMode::Full {
31            vim.switch_mode(Mode::Insert, cx);
32        }
33    });
34}
35
36fn editor_blurred(EditorBlurred(editor): &EditorBlurred, cx: &mut MutableAppContext) {
37    Vim::update(cx, |vim, cx| {
38        if let Some(previous_editor) = vim.active_editor.clone() {
39            if previous_editor == editor.clone() {
40                vim.active_editor = None;
41            }
42        }
43        vim.sync_editor_options(cx);
44    })
45}
46
47fn editor_released(EditorReleased(editor): &EditorReleased, cx: &mut MutableAppContext) {
48    cx.update_default_global(|vim: &mut Vim, _| {
49        vim.editors.remove(&editor.id());
50        if let Some(previous_editor) = vim.active_editor.clone() {
51            if previous_editor == editor.clone() {
52                vim.active_editor = None;
53            }
54        }
55    });
56}
57
58fn editor_local_selections_changed(newest_empty: bool, cx: &mut MutableAppContext) {
59    Vim::update(cx, |vim, cx| {
60        if vim.state.mode == Mode::Normal && !newest_empty {
61            vim.switch_mode(Mode::Visual { line: false }, cx)
62        }
63    })
64}