1use std::ops::{Deref, DerefMut};
  2
  3use editor::test::editor_lsp_test_context::EditorLspTestContext;
  4use gpui::{Context, Entity, SemanticVersion, UpdateGlobal};
  5use search::{BufferSearchBar, project_search::ProjectSearchBar};
  6
  7use crate::{state::Operator, *};
  8
  9pub struct VimTestContext {
 10    cx: EditorLspTestContext,
 11}
 12
 13impl VimTestContext {
 14    pub fn init(cx: &mut gpui::TestAppContext) {
 15        if cx.has_global::<VimGlobals>() {
 16            return;
 17        }
 18        env_logger::try_init().ok();
 19        cx.update(|cx| {
 20            let settings = SettingsStore::test(cx);
 21            cx.set_global(settings);
 22            release_channel::init(SemanticVersion::default(), cx);
 23            command_palette::init(cx);
 24            project_panel::init(cx);
 25            git_ui::init(cx);
 26            crate::init(cx);
 27            search::init(cx);
 28            workspace::init_settings(cx);
 29            language::init(cx);
 30            editor::init_settings(cx);
 31            project::Project::init_settings(cx);
 32            theme::init(theme::LoadThemes::JustBase, cx);
 33            settings_ui::init(cx);
 34        });
 35    }
 36
 37    pub async fn new(cx: &mut gpui::TestAppContext, enabled: bool) -> VimTestContext {
 38        Self::init(cx);
 39        let lsp = EditorLspTestContext::new_rust(Default::default(), cx).await;
 40        Self::new_with_lsp(lsp, enabled)
 41    }
 42
 43    pub async fn new_html(cx: &mut gpui::TestAppContext) -> VimTestContext {
 44        Self::init(cx);
 45        Self::new_with_lsp(EditorLspTestContext::new_html(cx).await, true)
 46    }
 47
 48    pub async fn new_typescript(cx: &mut gpui::TestAppContext) -> VimTestContext {
 49        Self::init(cx);
 50        Self::new_with_lsp(
 51            EditorLspTestContext::new_typescript(
 52                lsp::ServerCapabilities {
 53                    completion_provider: Some(lsp::CompletionOptions {
 54                        trigger_characters: Some(vec![".".to_string()]),
 55                        ..Default::default()
 56                    }),
 57                    rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
 58                        prepare_provider: Some(true),
 59                        work_done_progress_options: Default::default(),
 60                    })),
 61                    ..Default::default()
 62                },
 63                cx,
 64            )
 65            .await,
 66            true,
 67        )
 68    }
 69
 70    pub async fn new_tsx(cx: &mut gpui::TestAppContext) -> VimTestContext {
 71        Self::init(cx);
 72        Self::new_with_lsp(
 73            EditorLspTestContext::new_tsx(
 74                lsp::ServerCapabilities {
 75                    completion_provider: Some(lsp::CompletionOptions {
 76                        trigger_characters: Some(vec![".".to_string()]),
 77                        ..Default::default()
 78                    }),
 79                    rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
 80                        prepare_provider: Some(true),
 81                        work_done_progress_options: Default::default(),
 82                    })),
 83                    ..Default::default()
 84                },
 85                cx,
 86            )
 87            .await,
 88            true,
 89        )
 90    }
 91
 92    pub fn init_keybindings(enabled: bool, cx: &mut App) {
 93        SettingsStore::update_global(cx, |store, cx| {
 94            store.update_user_settings(cx, |s| s.vim_mode = Some(enabled));
 95        });
 96        let mut default_key_bindings = settings::KeymapFile::load_asset_allow_partial_failure(
 97            "keymaps/default-macos.json",
 98            cx,
 99        )
100        .unwrap();
101        for key_binding in &mut default_key_bindings {
102            key_binding.set_meta(settings::KeybindSource::Default.meta());
103        }
104        cx.bind_keys(default_key_bindings);
105        if enabled {
106            let vim_key_bindings = settings::KeymapFile::load_asset(
107                "keymaps/vim.json",
108                Some(settings::KeybindSource::Vim),
109                cx,
110            )
111            .unwrap();
112            cx.bind_keys(vim_key_bindings);
113        }
114    }
115
116    pub fn new_with_lsp(mut cx: EditorLspTestContext, enabled: bool) -> VimTestContext {
117        cx.update(|_, cx| {
118            Self::init_keybindings(enabled, cx);
119        });
120
121        // Setup search toolbars and keypress hook
122        cx.update_workspace(|workspace, window, cx| {
123            workspace.active_pane().update(cx, |pane, cx| {
124                pane.toolbar().update(cx, |toolbar, cx| {
125                    let buffer_search_bar = cx.new(|cx| BufferSearchBar::new(None, window, cx));
126                    toolbar.add_item(buffer_search_bar, window, cx);
127
128                    let project_search_bar = cx.new(|_| ProjectSearchBar::new());
129                    toolbar.add_item(project_search_bar, window, cx);
130                })
131            });
132            workspace.status_bar().update(cx, |status_bar, cx| {
133                let vim_mode_indicator = cx.new(|cx| ModeIndicator::new(window, cx));
134                status_bar.add_right_item(vim_mode_indicator, window, cx);
135            });
136        });
137
138        Self { cx }
139    }
140
141    pub fn update_entity<F, T, R>(&mut self, entity: Entity<T>, update: F) -> R
142    where
143        T: 'static,
144        F: FnOnce(&mut T, &mut Window, &mut Context<T>) -> R + 'static,
145    {
146        let window = self.window;
147        self.update_window(window, move |_, window, cx| {
148            entity.update(cx, |t, cx| update(t, window, cx))
149        })
150        .unwrap()
151    }
152
153    pub fn workspace<F, T>(&mut self, update: F) -> T
154    where
155        F: FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
156    {
157        self.cx.update_workspace(update)
158    }
159
160    pub fn enable_vim(&mut self) {
161        self.cx.update(|_, cx| {
162            SettingsStore::update_global(cx, |store, cx| {
163                store.update_user_settings(cx, |s| s.vim_mode = Some(true));
164            });
165        })
166    }
167
168    pub fn disable_vim(&mut self) {
169        self.cx.update(|_, cx| {
170            SettingsStore::update_global(cx, |store, cx| {
171                store.update_user_settings(cx, |s| s.vim_mode = Some(false));
172            });
173        })
174    }
175
176    pub fn enable_helix(&mut self) {
177        self.cx.update(|_, cx| {
178            SettingsStore::update_global(cx, |store, cx| {
179                store.update_user_settings(cx, |s| s.helix_mode = Some(true));
180            });
181        })
182    }
183
184    pub fn mode(&mut self) -> Mode {
185        self.update_editor(|editor, _, cx| editor.addon::<VimAddon>().unwrap().entity.read(cx).mode)
186    }
187
188    pub fn forced_motion(&mut self) -> bool {
189        self.update_editor(|_, _, cx| cx.global::<VimGlobals>().forced_motion)
190    }
191
192    pub fn active_operator(&mut self) -> Option<Operator> {
193        self.update_editor(|editor, _, cx| {
194            editor
195                .addon::<VimAddon>()
196                .unwrap()
197                .entity
198                .read(cx)
199                .operator_stack
200                .last()
201                .cloned()
202        })
203    }
204
205    pub fn set_state(&mut self, text: &str, mode: Mode) {
206        self.cx.set_state(text);
207        let vim =
208            self.update_editor(|editor, _window, _cx| editor.addon::<VimAddon>().cloned().unwrap());
209
210        self.update(|window, cx| {
211            vim.entity.update(cx, |vim, cx| {
212                vim.switch_mode(mode, true, window, cx);
213            });
214        });
215        self.cx.cx.cx.run_until_parked();
216    }
217
218    #[track_caller]
219    pub fn assert_state(&mut self, text: &str, mode: Mode) {
220        self.assert_editor_state(text);
221        assert_eq!(self.mode(), mode, "{}", self.assertion_context());
222    }
223
224    pub fn assert_binding(
225        &mut self,
226        keystrokes: &str,
227        initial_state: &str,
228        initial_mode: Mode,
229        state_after: &str,
230        mode_after: Mode,
231    ) {
232        self.set_state(initial_state, initial_mode);
233        self.cx.simulate_keystrokes(keystrokes);
234        self.cx.assert_editor_state(state_after);
235        assert_eq!(self.mode(), mode_after, "{}", self.assertion_context());
236        assert_eq!(self.active_operator(), None, "{}", self.assertion_context());
237    }
238
239    pub fn assert_binding_normal(
240        &mut self,
241        keystrokes: &str,
242        initial_state: &str,
243        state_after: &str,
244    ) {
245        self.set_state(initial_state, Mode::Normal);
246        self.cx.simulate_keystrokes(keystrokes);
247        self.cx.assert_editor_state(state_after);
248        assert_eq!(self.mode(), Mode::Normal, "{}", self.assertion_context());
249        assert_eq!(self.active_operator(), None, "{}", self.assertion_context());
250    }
251
252    pub fn shared_clipboard(&mut self) -> VimClipboard {
253        VimClipboard {
254            editor: self
255                .read_from_clipboard()
256                .map(|item| item.text().unwrap())
257                .unwrap_or_default(),
258        }
259    }
260}
261
262pub struct VimClipboard {
263    editor: String,
264}
265
266impl VimClipboard {
267    #[track_caller]
268    pub fn assert_eq(&self, expected: &str) {
269        assert_eq!(self.editor, expected);
270    }
271}
272
273impl Deref for VimTestContext {
274    type Target = EditorLspTestContext;
275
276    fn deref(&self) -> &Self::Target {
277        &self.cx
278    }
279}
280
281impl DerefMut for VimTestContext {
282    fn deref_mut(&mut self) -> &mut Self::Target {
283        &mut self.cx
284    }
285}