Skip to main content

fresh/app/
input_dispatch.rs

1//! Input dispatch using the hierarchical InputHandler system.
2//!
3//! This module provides the bridge between Editor and the InputHandler trait,
4//! dispatching input to modal components and processing deferred actions.
5
6use super::terminal_input::{should_enter_terminal_mode, TerminalModeInputHandler};
7use super::Editor;
8use crate::input::handler::{DeferredAction, InputContext, InputHandler, InputResult};
9use crate::input::keybindings::Action;
10use crate::view::file_browser_input::FileBrowserInputHandler;
11use crate::view::query_replace_input::QueryReplaceConfirmInputHandler;
12use crate::view::ui::MenuInputHandler;
13use anyhow::Result as AnyhowResult;
14use crossterm::event::KeyEvent;
15use rust_i18n::t;
16
17impl Editor {
18    /// Dispatch input when in terminal mode.
19    ///
20    /// Returns `Some(InputResult)` if terminal mode handled the input,
21    /// `None` if not in terminal mode or if a modal is active.
22    pub fn dispatch_terminal_input(&mut self, event: &KeyEvent) -> Option<InputResult> {
23        // Skip if we're in a prompt/popup (those need to handle keys normally)
24        let in_modal = self.is_prompting()
25            || self.global_popups.is_visible()
26            || self.active_state().popups.is_visible()
27            || self.menu_state.active_menu.is_some()
28            || self.settings_state.as_ref().is_some_and(|s| s.visible)
29            || self.calibration_wizard.is_some()
30            || self.keybinding_editor.is_some();
31
32        if in_modal {
33            return None;
34        }
35
36        // Handle terminal mode input
37        if self.terminal_mode {
38            // If the user navigated away from the terminal buffer (e.g. opened
39            // Review Diff via the command palette), the active buffer is no
40            // longer a terminal. Exit terminal mode so the new buffer's
41            // keybindings work.
42            if !self.is_terminal_buffer(self.active_buffer()) {
43                self.terminal_mode = false;
44                self.key_context = crate::input::keybindings::KeyContext::Normal;
45                return None; // fall through to normal input dispatch
46            }
47            let mut ctx = InputContext::new();
48            let keybindings = self.keybindings.read().unwrap();
49            let mut handler = TerminalModeInputHandler::new(self.keyboard_capture, &keybindings);
50            let result = handler.dispatch_input(event, &mut ctx);
51            drop(keybindings);
52            self.process_deferred_actions(ctx);
53            return Some(result);
54        }
55
56        // Check for keys that should re-enter terminal mode from scrollback view.
57        // Any plain character key exits scrollback and is forwarded to the terminal.
58        if self.is_terminal_buffer(self.active_buffer()) && should_enter_terminal_mode(event) {
59            self.enter_terminal_mode();
60            // Forward the key to the terminal so the user's input isn't lost
61            self.send_terminal_key(event.code, event.modifiers);
62            return Some(InputResult::Consumed);
63        }
64
65        None
66    }
67
68    /// Dispatch input to the appropriate modal handler.
69    ///
70    /// Returns `Some(InputResult)` if a modal handled the input,
71    /// `None` if no modal is active and input should be handled normally.
72    pub fn dispatch_modal_input(&mut self, event: &KeyEvent) -> Option<InputResult> {
73        let mut ctx = InputContext::new();
74
75        // Settings has highest priority
76        if let Some(ref mut settings) = self.settings_state {
77            if settings.visible {
78                let result = settings.dispatch_input(event, &mut ctx);
79                self.process_deferred_actions(ctx);
80                return Some(result);
81            }
82        }
83
84        // Keybinding editor is next
85        if self.keybinding_editor.is_some() {
86            let result = self.handle_keybinding_editor_input(event);
87            return Some(result);
88        }
89
90        // Calibration wizard is next (modal, blocks all other input)
91        if self.calibration_wizard.is_some() {
92            let result = self.handle_calibration_input(event);
93            return Some(result);
94        }
95
96        // Menu is next
97        if self.menu_state.active_menu.is_some() {
98            let all_menus: Vec<crate::config::Menu> = self
99                .menus
100                .menus
101                .iter()
102                .chain(self.menu_state.plugin_menus.iter())
103                .cloned()
104                .collect();
105
106            let mut handler = MenuInputHandler::new(&mut self.menu_state, &all_menus);
107            let result = handler.dispatch_input(event, &mut ctx);
108            self.process_deferred_actions(ctx);
109            return Some(result);
110        }
111
112        // Prompt is next
113        if self.prompt.is_some() {
114            // Check for Alt+key keybindings in Prompt context first
115            // Use resolve_in_context_only to bypass Global bindings (like menu mnemonics)
116            // This allows Prompt-specific Alt+key bindings (like encoding toggle) to work
117            if event
118                .modifiers
119                .contains(crossterm::event::KeyModifiers::ALT)
120            {
121                if let crossterm::event::KeyCode::Char(_) = event.code {
122                    let prompt_action = self.keybindings.read().unwrap().resolve_in_context_only(
123                        event,
124                        crate::input::keybindings::KeyContext::Prompt,
125                    );
126                    if let Some(action) = prompt_action {
127                        // For file browser actions, route to handle_file_open_action
128                        if self.is_file_open_active() && self.handle_file_open_action(&action) {
129                            return Some(InputResult::Consumed);
130                        }
131                        // For other prompt actions, use handle_action
132                        if let Err(e) = self.handle_action(action) {
133                            tracing::warn!("Prompt action failed: {}", e);
134                        }
135                        return Some(InputResult::Consumed);
136                    }
137                }
138            }
139
140            // File browser prompts use FileBrowserInputHandler
141            if self.is_file_open_active() {
142                if let (Some(ref mut file_state), Some(ref mut prompt)) =
143                    (&mut self.file_open_state, &mut self.prompt)
144                {
145                    let mut handler = FileBrowserInputHandler::new(file_state, prompt);
146                    let result = handler.dispatch_input(event, &mut ctx);
147                    self.process_deferred_actions(ctx);
148                    return Some(result);
149                }
150            }
151
152            // QueryReplaceConfirm prompts use QueryReplaceConfirmInputHandler
153            use crate::view::prompt::PromptType;
154            let is_query_replace_confirm = self
155                .prompt
156                .as_ref()
157                .is_some_and(|p| p.prompt_type == PromptType::QueryReplaceConfirm);
158            if is_query_replace_confirm {
159                let mut handler = QueryReplaceConfirmInputHandler::new();
160                let result = handler.dispatch_input(event, &mut ctx);
161                self.process_deferred_actions(ctx);
162                return Some(result);
163            }
164
165            if let Some(ref mut prompt) = self.prompt {
166                let result = prompt.dispatch_input(event, &mut ctx);
167                // Only return and process deferred actions if the prompt handled the input
168                // If Ignored, fall through to check global keybindings
169                if result != InputResult::Ignored {
170                    self.process_deferred_actions(ctx);
171                    return Some(result);
172                }
173            }
174        }
175
176        // Editor-level (global) popups take precedence over buffer popups so
177        // that plugin notifications stay focused even when the active buffer
178        // owns its own popup stack.
179        if self.global_popups.is_visible() {
180            let result = self.global_popups.dispatch_input(event, &mut ctx);
181            self.process_deferred_actions(ctx);
182            if result != InputResult::Ignored {
183                return Some(result);
184            }
185            // Re-check visibility — the dispatch may have queued a ClosePopup
186            // that the deferred-action processor has now fired.
187            return None;
188        }
189
190        // Popup is next
191        if self.active_state().popups.is_visible() {
192            let result = self
193                .active_state_mut()
194                .popups
195                .dispatch_input(event, &mut ctx);
196            self.process_deferred_actions(ctx);
197            // If the popup handler returned Ignored (e.g., non-word character,
198            // Ctrl+key, arrow keys), fall through to normal input handling.
199            // The deferred ClosePopup action was already processed above.
200            if result != InputResult::Ignored {
201                return Some(result);
202            }
203        }
204
205        None
206    }
207
208    /// Process deferred actions collected during input handling.
209    pub fn process_deferred_actions(&mut self, ctx: InputContext) {
210        // Set status message if provided
211        if let Some(msg) = ctx.status_message {
212            self.set_status_message(msg);
213        }
214
215        // Process each deferred action
216        for action in ctx.deferred_actions {
217            if let Err(e) = self.execute_deferred_action(action) {
218                self.set_status_message(
219                    t!("error.deferred_action", error = e.to_string()).to_string(),
220                );
221            }
222        }
223    }
224
225    /// Execute a single deferred action.
226    fn execute_deferred_action(&mut self, action: DeferredAction) -> AnyhowResult<()> {
227        match action {
228            // Settings actions
229            DeferredAction::CloseSettings { save } => {
230                if save {
231                    self.save_settings();
232                }
233                self.close_settings(false);
234            }
235            DeferredAction::PasteToSettings => {
236                if let Some(text) = self.clipboard.paste() {
237                    if !text.is_empty() {
238                        if let Some(settings) = &mut self.settings_state {
239                            if let Some(dialog) = settings.entry_dialog_mut() {
240                                dialog.insert_str(&text);
241                            }
242                        }
243                    }
244                }
245            }
246            DeferredAction::OpenConfigFile { layer } => {
247                self.open_config_file(layer)?;
248            }
249
250            // Menu actions
251            DeferredAction::CloseMenu => {
252                self.close_menu_with_auto_hide();
253            }
254            DeferredAction::ExecuteMenuAction { action, args } => {
255                // Convert menu action to keybinding Action and execute
256                if let Some(kb_action) = self.menu_action_to_action(&action, args) {
257                    self.handle_action(kb_action)?;
258                }
259            }
260
261            // Prompt actions
262            DeferredAction::ClosePrompt => {
263                self.cancel_prompt();
264            }
265            DeferredAction::ConfirmPrompt => {
266                self.handle_action(Action::PromptConfirm)?;
267            }
268            DeferredAction::UpdatePromptSuggestions => {
269                self.update_prompt_suggestions();
270            }
271            DeferredAction::PromptHistoryPrev => {
272                self.prompt_history_prev();
273            }
274            DeferredAction::PromptHistoryNext => {
275                self.prompt_history_next();
276            }
277            DeferredAction::PreviewThemeFromPrompt => {
278                if let Some(prompt) = &self.prompt {
279                    if matches!(
280                        prompt.prompt_type,
281                        crate::view::prompt::PromptType::SelectTheme { .. }
282                    ) {
283                        let theme_name = prompt.input.clone();
284                        self.preview_theme(&theme_name);
285                    }
286                }
287            }
288            DeferredAction::PromptSelectionChanged { selected_index } => {
289                // Fire hook for plugin prompts so they can update live preview
290                if let Some(prompt) = &self.prompt {
291                    if let crate::view::prompt::PromptType::Plugin { custom_type } =
292                        &prompt.prompt_type
293                    {
294                        self.plugin_manager.run_hook(
295                            "prompt_selection_changed",
296                            crate::services::plugins::hooks::HookArgs::PromptSelectionChanged {
297                                prompt_type: custom_type.clone(),
298                                selected_index,
299                            },
300                        );
301                    }
302                }
303            }
304
305            // Popup actions
306            DeferredAction::ClosePopup => {
307                // Route through handle_popup_cancel so popup-specific
308                // cleanup runs (e.g. the LSP auto-prompt needs to mark
309                // the language as prompted and drop the pending queue
310                // entry — otherwise the render-time drain would just
311                // re-open the popup on the next frame, defeating Esc).
312                self.handle_popup_cancel();
313            }
314            DeferredAction::ConfirmPopup => {
315                self.handle_action(Action::PopupConfirm)?;
316            }
317            DeferredAction::PopupTypeChar(c) => {
318                self.handle_popup_type_char(c);
319            }
320            DeferredAction::PopupBackspace => {
321                self.handle_popup_backspace();
322            }
323            DeferredAction::CopyToClipboard(text) => {
324                self.clipboard.copy(text);
325                self.set_status_message(t!("clipboard.copied").to_string());
326            }
327
328            // Generic action execution
329            DeferredAction::ExecuteAction(kb_action) => {
330                self.handle_action(kb_action)?;
331            }
332
333            // Character insertion with suggestion update
334            DeferredAction::InsertCharAndUpdate(c) => {
335                if let Some(ref mut prompt) = self.prompt {
336                    prompt.insert_char(c);
337                }
338                self.update_prompt_suggestions();
339            }
340
341            // File browser actions
342            DeferredAction::FileBrowserSelectPrev => {
343                if let Some(state) = &mut self.file_open_state {
344                    state.select_prev();
345                }
346            }
347            DeferredAction::FileBrowserSelectNext => {
348                if let Some(state) = &mut self.file_open_state {
349                    state.select_next();
350                }
351            }
352            DeferredAction::FileBrowserPageUp => {
353                if let Some(state) = &mut self.file_open_state {
354                    state.page_up(10);
355                }
356            }
357            DeferredAction::FileBrowserPageDown => {
358                if let Some(state) = &mut self.file_open_state {
359                    state.page_down(10);
360                }
361            }
362            DeferredAction::FileBrowserConfirm => {
363                // Must call handle_file_open_action directly to get proper
364                // file browser behavior (e.g., project switch triggering restart)
365                self.handle_file_open_action(&Action::PromptConfirm);
366            }
367            DeferredAction::FileBrowserAcceptSuggestion => {
368                self.handle_file_open_action(&Action::PromptAcceptSuggestion);
369            }
370            DeferredAction::FileBrowserGoParent => {
371                // Navigate to parent directory
372                let parent = self
373                    .file_open_state
374                    .as_ref()
375                    .and_then(|s| s.current_dir.parent())
376                    .map(|p| p.to_path_buf());
377                if let Some(parent_path) = parent {
378                    self.load_file_open_directory(parent_path);
379                }
380            }
381            DeferredAction::FileBrowserUpdateFilter => {
382                self.update_file_open_filter();
383            }
384            DeferredAction::FileBrowserToggleHidden => {
385                self.file_open_toggle_hidden();
386            }
387
388            // Interactive replace actions
389            DeferredAction::InteractiveReplaceKey(c) => {
390                self.handle_interactive_replace_key(c)?;
391            }
392            DeferredAction::CancelInteractiveReplace => {
393                self.cancel_prompt();
394                self.interactive_replace_state = None;
395            }
396
397            // Terminal mode actions
398            DeferredAction::ToggleKeyboardCapture => {
399                self.keyboard_capture = !self.keyboard_capture;
400                if self.keyboard_capture {
401                    self.set_status_message(
402                        "Keyboard capture ON - all keys go to terminal (F9 to toggle)".to_string(),
403                    );
404                } else {
405                    self.set_status_message(
406                        "Keyboard capture OFF - UI bindings active (F9 to toggle)".to_string(),
407                    );
408                }
409            }
410            DeferredAction::SendTerminalKey(code, modifiers) => {
411                self.send_terminal_key(code, modifiers);
412            }
413            DeferredAction::SendTerminalMouse {
414                col,
415                row,
416                kind,
417                modifiers,
418            } => {
419                self.send_terminal_mouse(col, row, kind, modifiers);
420            }
421            DeferredAction::ExitTerminalMode { explicit } => {
422                self.terminal_mode = false;
423                self.key_context = crate::input::keybindings::KeyContext::Normal;
424                if explicit {
425                    // User explicitly exited - don't auto-resume when switching back
426                    self.terminal_mode_resume.remove(&self.active_buffer());
427                    self.sync_terminal_to_buffer(self.active_buffer());
428                    self.set_status_message(
429                        "Terminal mode disabled - read only (Ctrl+Space to resume)".to_string(),
430                    );
431                }
432            }
433            DeferredAction::EnterScrollbackMode => {
434                self.terminal_mode = false;
435                self.key_context = crate::input::keybindings::KeyContext::Normal;
436                self.sync_terminal_to_buffer(self.active_buffer());
437                self.set_status_message(
438                    "Scrollback mode - use PageUp/Down to scroll (Ctrl+Space to resume)"
439                        .to_string(),
440                );
441                // Scroll up using normal buffer scrolling
442                self.handle_action(Action::MovePageUp)?;
443            }
444            DeferredAction::EnterTerminalMode => {
445                self.enter_terminal_mode();
446            }
447        }
448
449        Ok(())
450    }
451
452    /// Convert a menu action string to a keybinding Action.
453    fn menu_action_to_action(
454        &self,
455        action_name: &str,
456        args: std::collections::HashMap<String, serde_json::Value>,
457    ) -> Option<Action> {
458        // Try to parse as a built-in action first
459        if let Some(action) = Action::from_str(action_name, &args) {
460            return Some(action);
461        }
462
463        // Otherwise treat as a plugin action
464        Some(Action::PluginAction(action_name.to_string()))
465    }
466
467    /// Navigate to previous history entry in prompt.
468    fn prompt_history_prev(&mut self) {
469        // Get the prompt type and current input
470        let prompt_info = self
471            .prompt
472            .as_ref()
473            .map(|p| (p.prompt_type.clone(), p.input.clone()));
474
475        if let Some((prompt_type, current_input)) = prompt_info {
476            // Get the history key for this prompt type
477            if let Some(key) = Self::prompt_type_to_history_key(&prompt_type) {
478                if let Some(history) = self.prompt_histories.get_mut(&key) {
479                    if let Some(entry) = history.navigate_prev(&current_input) {
480                        if let Some(ref mut prompt) = self.prompt {
481                            prompt.set_input(entry);
482                        }
483                    }
484                }
485            }
486        }
487    }
488
489    /// Navigate to next history entry in prompt.
490    fn prompt_history_next(&mut self) {
491        let prompt_type = self.prompt.as_ref().map(|p| p.prompt_type.clone());
492
493        if let Some(prompt_type) = prompt_type {
494            // Get the history key for this prompt type
495            if let Some(key) = Self::prompt_type_to_history_key(&prompt_type) {
496                if let Some(history) = self.prompt_histories.get_mut(&key) {
497                    if let Some(entry) = history.navigate_next() {
498                        if let Some(ref mut prompt) = self.prompt {
499                            prompt.set_input(entry);
500                        }
501                    }
502                }
503            }
504        }
505    }
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511
512    #[test]
513    fn test_deferred_action_close_menu() {
514        // This is a basic structure test - full integration tests
515        // would require a complete Editor setup
516        let action = DeferredAction::CloseMenu;
517        assert!(matches!(action, DeferredAction::CloseMenu));
518    }
519
520    #[test]
521    fn test_deferred_action_execute_menu_action() {
522        let action = DeferredAction::ExecuteMenuAction {
523            action: "save".to_string(),
524            args: std::collections::HashMap::new(),
525        };
526        if let DeferredAction::ExecuteMenuAction { action: name, .. } = action {
527            assert_eq!(name, "save");
528        } else {
529            panic!("Expected ExecuteMenuAction");
530        }
531    }
532}