Skip to main content

iced_code_editor/canvas_editor/
focus.rs

1//! Editor focus management: programmatic focus/blur and the canvas focus
2//! lock used to suppress input during focus transitions.
3
4use std::sync::atomic::Ordering;
5
6use crate::canvas_editor::{CodeEditor, FOCUSED_EDITOR_ID};
7
8impl CodeEditor {
9    /// Requests focus for this editor.
10    ///
11    /// This method programmatically sets the focus to this editor instance,
12    /// allowing it to receive keyboard events. Other editors will automatically
13    /// lose focus.
14    ///
15    /// # Example
16    ///
17    /// ```
18    /// use iced_code_editor::CodeEditor;
19    ///
20    /// let mut editor1 = CodeEditor::new("fn main() {}", "rs");
21    /// let mut editor2 = CodeEditor::new("fn test() {}", "rs");
22    ///
23    /// // Give focus to editor2
24    /// editor2.request_focus();
25    /// ```
26    pub fn request_focus(&self) {
27        FOCUSED_EDITOR_ID.store(self.editor_id, Ordering::Relaxed);
28    }
29
30    /// Checks if this editor currently has focus.
31    ///
32    /// Returns `true` if this editor will receive keyboard events,
33    /// `false` otherwise.
34    ///
35    /// # Returns
36    ///
37    /// `true` if focused, `false` otherwise
38    ///
39    /// # Example
40    ///
41    /// ```
42    /// use iced_code_editor::CodeEditor;
43    ///
44    /// let editor = CodeEditor::new("fn main() {}", "rs");
45    /// if editor.is_focused() {
46    ///     println!("Editor has focus");
47    /// }
48    /// ```
49    pub fn is_focused(&self) -> bool {
50        FOCUSED_EDITOR_ID.load(Ordering::Relaxed) == self.editor_id
51    }
52
53    /// Removes canvas focus from this editor.
54    ///
55    /// This method programmatically removes focus from the canvas, preventing
56    /// it from receiving keyboard events. The cursor will be hidden, but the
57    /// selection will remain visible.
58    ///
59    /// Call this when focus should move to another widget (e.g., text input).
60    ///
61    /// # Example
62    ///
63    /// ```
64    /// use iced_code_editor::CodeEditor;
65    ///
66    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
67    /// editor.lose_focus();
68    /// ```
69    pub fn lose_focus(&mut self) {
70        self.has_canvas_focus = false;
71        self.show_cursor = false;
72        self.ime_preedit = None;
73    }
74
75    /// Resets the focus lock state.
76    ///
77    /// This method can be called to manually unlock focus processing
78    /// after a focus transition has completed. This is useful when
79    /// you want to allow the editor to process input again after
80    /// programmatic focus changes.
81    ///
82    /// # Example
83    ///
84    /// ```
85    /// use iced_code_editor::CodeEditor;
86    ///
87    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
88    /// editor.reset_focus_lock();
89    /// ```
90    pub fn reset_focus_lock(&mut self) {
91        self.focus_locked = false;
92    }
93}