Skip to main content

oa/input/
actions.rs

1//! `InputSystem` — named key-action registry with context dispatch.
2//!
3//! Donor: `oa/ui/input.h` and `oa/ui/input.cpp`.
4//!
5//! ```ignore
6//! let mut input = InputSystem::new();
7//! input.register_action(KeyAction {
8//!     name: "screenshot".into(),
9//!     binding: KeyBinding { key: Key::F12, modifiers: INPUT_MOD_NONE },
10//!     context: InputContext::Global,
11//!     allow_repeat: false,
12//!     callback: None,
13//! });
14//! // per-frame:
15//! for event in events { input.dispatch(&event); }
16//! ```
17//!
18//! Bindings can be serialized to / loaded from a versioned YAML document on
19//! donor builds that link yaml-cpp. This build has no YAML backend, so the
20//! persistence entry points report [`crate::ErrorKind::MissingCapability`],
21//! matching the donor's documented fallback. Application callbacks are never
22//! serialized.
23
24use super::types::{
25	INPUT_MOD_CTRL, INPUT_MOD_NONE, InputEvent, InputEventKind, InputModifiers, Key,
26};
27use crate::{Error, Result};
28
29/// Focus domain gating which actions a key event may reach.
30///
31/// `Global` actions are always active; other contexts only fire while the
32/// matching focus is set through [`InputSystem::set_context`].
33///
34/// Donor: `oa::InputContext`.
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
36pub enum InputContext {
37	/// Always active.
38	#[default]
39	Global,
40	/// Active when the node canvas has focus.
41	NodeCanvas,
42	/// Active when a text field has focus.
43	TextInput,
44	/// Active when the timeline has focus.
45	Timeline,
46}
47
48/// One key-plus-modifiers trigger.
49///
50/// Donor: `oa::KeyBinding`.
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
52pub struct KeyBinding {
53	pub key: Key,
54	pub modifiers: InputModifiers,
55}
56
57impl KeyBinding {
58	/// Return whether `event` is a key-down matching key and modifiers exactly.
59	#[must_use]
60	pub fn matches(&self, event: &InputEvent) -> bool {
61		event.kind == InputEventKind::KeyDown
62			&& event.key == self.key
63			&& event.modifiers == self.modifiers
64	}
65}
66
67/// One named action: trigger, focus context, repeat policy, and callback.
68///
69/// Donor: `oa::KeyAction`.
70pub struct KeyAction {
71	pub name: String,
72	pub binding: KeyBinding,
73	pub context: InputContext,
74	pub allow_repeat: bool,
75	pub callback: Option<Box<dyn FnMut()>>,
76}
77
78impl std::fmt::Debug for KeyAction {
79	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80		f.debug_struct("KeyAction")
81			.field("name", &self.name)
82			.field("binding", &self.binding)
83			.field("context", &self.context)
84			.field("allow_repeat", &self.allow_repeat)
85			.field("callback", &self.callback.is_some())
86			.finish()
87	}
88}
89
90/// Named key-action registry with context dispatch.
91///
92/// Donor: `oa::InputSystem`.
93#[derive(Default)]
94pub struct InputSystem {
95	actions: Vec<KeyAction>,
96	context: InputContext,
97}
98
99impl InputSystem {
100	pub fn new() -> Self {
101		Self::default()
102	}
103
104	/// Register `action`, replacing any existing action with the same name.
105	pub fn register_action(&mut self, action: KeyAction) {
106		if let Some(existing) = self
107			.actions
108			.iter_mut()
109			.find(|existing| existing.name == action.name)
110		{
111			*existing = action;
112			return;
113		}
114		self.actions.push(action);
115	}
116
117	/// Remove the action named `name`, if present.
118	pub fn unregister_action(&mut self, name: &str) {
119		if let Some(index) = self.actions.iter().position(|action| action.name == name) {
120			self.actions.swap_remove(index);
121		}
122	}
123
124	/// Attach or replace the callback of the action named `name`.
125	pub fn set_callback(&mut self, name: &str, callback: impl FnMut() + 'static) {
126		if let Some(action) = self.actions.iter_mut().find(|action| action.name == name) {
127			action.callback = Some(Box::new(callback));
128		}
129	}
130
131	/// Replace the trigger of the action named `name`.
132	pub fn rebind(&mut self, name: &str, binding: KeyBinding) {
133		if let Some(action) = self.actions.iter_mut().find(|action| action.name == name) {
134			action.binding = binding;
135		}
136	}
137
138	/// Set the active focus context.
139	pub fn set_context(&mut self, context: InputContext) {
140		self.context = context;
141	}
142
143	/// Return the active focus context.
144	#[must_use]
145	pub const fn context(&self) -> InputContext {
146		self.context
147	}
148
149	/// Return the number of registered actions.
150	#[must_use]
151	pub fn action_count(&self) -> usize {
152		self.actions.len()
153	}
154
155	/// Dispatch `event` to the first matching action in context.
156	///
157	/// Returns `true` when an action's binding matched — including the case
158	/// where a repeated key event is consumed without firing because
159	/// `allow_repeat` is false.
160	pub fn dispatch(&mut self, event: &InputEvent) -> bool {
161		if event.kind != InputEventKind::KeyDown {
162			return false;
163		}
164		for action in &mut self.actions {
165			if action.context != InputContext::Global && action.context != self.context {
166				continue;
167			}
168			if action.binding.matches(event) {
169				if event.key_repeat && !action.allow_repeat {
170					return true;
171				}
172				if let Some(callback) = &mut action.callback {
173					callback();
174				}
175				return true;
176			}
177		}
178		false
179	}
180
181	/// Register the reusable Realm tool bindings.
182	///
183	/// Installs named callback-free actions; the application attaches each
184	/// behavior through [`Self::set_callback`]:
185	///
186	/// | action          | binding  | context    |
187	/// |-----------------|----------|------------|
188	/// | `screenshot`    | F12      | Global     |
189	/// | `record`        | Ctrl+R   | Global     |
190	/// | `toggle_camera` | Space    | Global     |
191	/// | `undo`          | Ctrl+Z   | NodeCanvas |
192	/// | `redo`          | Ctrl+Y   | NodeCanvas |
193	/// | `save`          | Ctrl+S   | Global     |
194	/// | `fit_view`      | F        | NodeCanvas |
195	pub fn register_defaults(&mut self) {
196		self.register_action(KeyAction {
197			name: "screenshot".into(),
198			binding: KeyBinding {
199				key: Key::F12,
200				modifiers: INPUT_MOD_NONE,
201			},
202			context: InputContext::Global,
203			allow_repeat: false,
204			callback: None,
205		});
206		self.register_action(KeyAction {
207			name: "record".into(),
208			binding: KeyBinding {
209				key: Key::R,
210				modifiers: INPUT_MOD_CTRL,
211			},
212			context: InputContext::Global,
213			allow_repeat: false,
214			callback: None,
215		});
216		self.register_action(KeyAction {
217			name: "toggle_camera".into(),
218			binding: KeyBinding {
219				key: Key::Space,
220				modifiers: INPUT_MOD_NONE,
221			},
222			context: InputContext::Global,
223			allow_repeat: false,
224			callback: None,
225		});
226		self.register_action(KeyAction {
227			name: "undo".into(),
228			binding: KeyBinding {
229				key: Key::Z,
230				modifiers: INPUT_MOD_CTRL,
231			},
232			context: InputContext::NodeCanvas,
233			allow_repeat: false,
234			callback: None,
235		});
236		self.register_action(KeyAction {
237			name: "redo".into(),
238			binding: KeyBinding {
239				key: Key::Y,
240				modifiers: INPUT_MOD_CTRL,
241			},
242			context: InputContext::NodeCanvas,
243			allow_repeat: false,
244			callback: None,
245		});
246		self.register_action(KeyAction {
247			name: "save".into(),
248			binding: KeyBinding {
249				key: Key::S,
250				modifiers: INPUT_MOD_CTRL,
251			},
252			context: InputContext::Global,
253			allow_repeat: false,
254			callback: None,
255		});
256		self.register_action(KeyAction {
257			name: "fit_view".into(),
258			binding: KeyBinding {
259				key: Key::F,
260				modifiers: INPUT_MOD_NONE,
261			},
262			context: InputContext::NodeCanvas,
263			allow_repeat: false,
264			callback: None,
265		});
266	}
267
268	/// Load bindings from a versioned YAML document.
269	///
270	/// Loading is transactional: a syntax or schema error leaves registered
271	/// actions untouched. Persisted rebinds preserve existing callbacks; new
272	/// actions arrive callback-free.
273	///
274	/// # Errors
275	///
276	/// Returns [`ErrorKind::InvalidArgument`] for an empty path, and
277	/// [`ErrorKind::MissingCapability`] while no YAML backend is linked — the
278	/// donor's documented behavior without yaml-cpp.
279	///
280	/// [`ErrorKind::InvalidArgument`]: crate::ErrorKind::InvalidArgument
281	/// [`ErrorKind::MissingCapability`]: crate::ErrorKind::MissingCapability
282	pub fn load_bindings_yaml(&mut self, path: &str) -> Result<()> {
283		if path.is_empty() {
284			return Err(Error::invalid_argument(
285				"InputSystem::load_bindings_yaml requires a path",
286			));
287		}
288		Err(Error::missing_capability(
289			"InputSystem YAML persistence requires a YAML backend",
290		))
291	}
292
293	/// Save bindings to a versioned YAML document.
294	///
295	/// # Errors
296	///
297	/// Returns [`ErrorKind::InvalidArgument`] for an empty path, and
298	/// [`ErrorKind::MissingCapability`] while no YAML backend is linked.
299	///
300	/// [`ErrorKind::InvalidArgument`]: crate::ErrorKind::InvalidArgument
301	/// [`ErrorKind::MissingCapability`]: crate::ErrorKind::MissingCapability
302	pub fn save_bindings_yaml(&self, path: &str) -> Result<()> {
303		if path.is_empty() {
304			return Err(Error::invalid_argument(
305				"InputSystem::save_bindings_yaml requires a path",
306			));
307		}
308		Err(Error::missing_capability(
309			"InputSystem YAML persistence requires a YAML backend",
310		))
311	}
312}