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