teksilo_core/window/ops.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! App-level window-operation sink.
5//!
6//! [`WindowOps`] is the trait implemented by the app-level window
7//! manager (`teksilo_app::WindowManager`) and handed to every
8//! [`EventContext`](crate::widget::EventContext) during event
9//! dispatch. Handlers reach the multi-window API through it.
10//!
11//! Calls are **synchronous** except the two activation-token requests,
12//! which answer through a callback on a later event-loop tick, and a quit
13//! request, which the application carries out over the ticks that follow:
14//! `open_window` creates the winit window and registers it before
15//! returning; the returned id is immediately usable for
16//! `focus_window`, `window_state`, `close_window_by_id`. The trait exists to keep teksilo-core
17//! independent of teksilo-app — teksilo-core defines the contract, teksilo-app
18//! provides the implementation.
19
20use super::config::WindowConfig;
21use super::id::TeksiloWindowId;
22use super::state::WindowState;
23use super::string_id::WindowStringIdError;
24use crate::raw_handle::ParentHandle;
25
26/// App-level window operations exposed to handlers.
27///
28/// Implemented by `teksilo_app::WindowManager` (via a short-lived
29/// wrapper that also holds `&ActiveEventLoop`). Passed into every
30/// dispatch site as `&mut dyn WindowOps` and stored on
31/// [`EventContext`](crate::widget::EventContext).
32pub trait WindowOps {
33 /// Open a new window. Creates the winit-level window
34 /// synchronously inside this call and returns its id, which is
35 /// immediately valid for any other method on this trait.
36 fn open_window(&mut self, config: WindowConfig) -> TeksiloWindowId;
37
38 /// Look up a window by the stable string id it was opened with
39 /// (`WindowConfig::id`). Returns `None` if no live window carries
40 /// that id.
41 fn find_window(&self, string_id: &str) -> Option<TeksiloWindowId>;
42
43 /// Give the open window `window` the string id `new_id`, in place of
44 /// the one it was opened with (or as its first, for a window opened
45 /// without one). See
46 /// [`EventContext::set_window_string_id`](crate::widget::EventContext::set_window_string_id)
47 /// for what it changes and when it refuses.
48 ///
49 /// Default implementation: [`WindowStringIdError::Unsupported`], so an
50 /// implementation written before this method existed keeps compiling
51 /// and says plainly that it cannot rename.
52 fn set_window_string_id(
53 &mut self,
54 _window: TeksiloWindowId,
55 _new_id: String,
56 ) -> Result<(), WindowStringIdError> {
57 Err(WindowStringIdError::Unsupported)
58 }
59
60 /// Read the reactive state for a specific window.
61 fn window_state(&self, id: TeksiloWindowId) -> Option<WindowState>;
62
63 /// Every live window's state, in creation order.
64 fn windows(&self) -> Vec<WindowState>;
65
66 /// Raise a window and give it keyboard focus, restoring it first if it
67 /// is minimised.
68 fn focus_window(&mut self, id: TeksiloWindowId);
69
70 /// Request an `xdg_activation_v1` token for `id` — to hand to another window
71 /// or a child process so it can raise itself on Wayland. `cb` fires once with
72 /// the token string, or with `None` where unsupported (everything but
73 /// Wayland/X11). Default implementation: immediate `None`.
74 fn request_activation_token(
75 &mut self,
76 _id: TeksiloWindowId,
77 cb: Box<dyn FnOnce(Option<String>)>,
78 ) {
79 cb(None);
80 }
81
82 /// Like [`request_activation_token`](Self::request_activation_token) but for
83 /// the **current dispatching** window — the one whose handler is running.
84 /// Works even mid-dispatch, when that window is temporarily out of the
85 /// manager's map, because it uses the captured window handle instead of an id
86 /// lookup. Use this when a focused widget needs a token to hand to another
87 /// window or process. Default implementation: immediate `None`.
88 fn request_activation_token_self(&mut self, cb: Box<dyn FnOnce(Option<String>)>) {
89 cb(None);
90 }
91
92 /// Close a specific window by id. The window is fully torn down
93 /// before the next event-loop tick.
94 fn close_window_by_id(&mut self, id: TeksiloWindowId);
95
96 /// Extract the platform parent handle of the window currently
97 /// dispatching the event (the one that owns the in-flight
98 /// `EventContext`). Used by native-dialog integrations
99 /// (`teksilo_platform::file_dialog`) to parent OS dialogs to the
100 /// originating Teksilo window.
101 ///
102 /// Returns `None` for the standalone / test sink and on rare
103 /// platform paths where the underlying surface refuses a handle
104 /// (e.g. during shutdown).
105 fn current_parent_handle(&self) -> Option<ParentHandle> {
106 None
107 }
108
109 /// Report the focused text widget's caret rectangle (in window-logical
110 /// pixels) so the platform can position the OS IME candidate window
111 /// next to the insertion point. Called from text-editing widgets
112 /// whenever the caret moves. The app applies it to the in-flight
113 /// window's `set_ime_cursor_area`, deduped against the last value.
114 ///
115 /// No-op on the standalone / test sink.
116 fn set_ime_cursor_area(&mut self, _area: teksilo_canvas::Rect) {}
117
118 /// Tell the platform's input method that the focused field's composition
119 /// is over (a click elsewhere, a focus change), and return the text the
120 /// input method committed for it, if it committed one: the field keeps
121 /// that text in place of what the composition showed. On Windows the input
122 /// method is asked to complete the composition, as a native edit control
123 /// does, and its commit can differ from what it showed (Microsoft Pinyin
124 /// commits "nihao" for the "ni'hao" it showed). `None` keeps what the
125 /// composition showed: the platform keeps that (macOS, Linux), or the
126 /// input method committed nothing.
127 ///
128 /// The field calls it while it still holds the composition, and keeps the
129 /// text right after, in the same handler. Whatever the platform delivers
130 /// for the composition arrives after the handler returns (an empty update,
131 /// an empty commit), and must find nothing left to change; a copy of the
132 /// commit returned here is not delivered.
133 ///
134 /// `None` on the standalone / test sink.
135 fn finish_ime_composition(&mut self) -> Option<String> {
136 None
137 }
138
139 /// Ask the platform to start a native OS drag for an in-app drag carrying
140 /// an OS-exportable payload. The framework asks when the pointer leaves the
141 /// window, or, for a payload with
142 /// [`OsHandoff::Eager`](crate::OsHandoff::Eager), on the first pointer
143 /// move. The platform backend (`teksilo_platform::external_dnd`) starts a
144 /// native drag session (`NSDraggingSource` / `wl_data_source` / OLE
145 /// `IDropSource` / XDND) using `data`, optionally drawing `image` as the
146 /// drag cursor.
147 ///
148 /// The answer decides what happens to the in-app session:
149 ///
150 /// - [`OsDragStart::Declined`](crate::OsDragStart::Declined): nothing
151 /// started, and the in-app drag continues; a later pointer move may ask
152 /// again. This is the default, for the standalone / test sink and for a
153 /// platform without an outbound backend.
154 /// - [`OsDragStart::Started`](crate::OsDragStart::Started): the native drag
155 /// is running (macOS starts it inside the request). The in-app session is
156 /// handed over at once.
157 /// - [`OsDragStart::Pending`](crate::OsDragStart::Pending): the platform
158 /// starts the drag on its own loop (Wayland, X11, Windows), under the
159 /// [`OsDragId`](crate::OsDragId) it carries. The in-app session stays
160 /// alive until the platform confirms that drag's start through
161 /// [`WidgetTree::confirm_os_drag`](crate::WidgetTree::confirm_os_drag). A
162 /// release before that ends the drag as `Cancelled` and calls
163 /// [`Self::cancel_os_drag`]; a start that fails ends it through
164 /// [`WidgetTree::handle_os_drag_ended_for`](crate::WidgetTree::handle_os_drag_ended_for).
165 /// Events naming another drag's id change nothing.
166 ///
167 /// A failure known now (nothing to drag from, nothing to export) is a
168 /// `Declined`, never a `Pending` that fails later: a decline keeps the
169 /// in-app drag, a failure ends it.
170 ///
171 /// `pointer` is the device carrying the drag. It is not decoration: on
172 /// Wayland `wl_data_device::start_drag` must be given the serial of the
173 /// input event that began the implicit grab, and a finger's grab was opened
174 /// by a `wl_touch::down`, not a `wl_pointer::button`; hand the wrong
175 /// serial over and the compositor rejects the request silently and sends no
176 /// terminal event at all.
177 fn begin_os_drag(
178 &mut self,
179 _data: crate::drag_payload::OutboundDragData,
180 _image: Option<crate::drag_payload::DragImageData>,
181 _pointer: teksilo_tokens::PointerKind,
182 ) -> crate::drag_payload::OsDragStart {
183 crate::drag_payload::OsDragStart::Declined
184 }
185
186 /// Tell the platform whether the widget under an **inbound** OS drag
187 /// accepts it, so the OS shows the right cursor and permits (or refuses)
188 /// the drop.
189 ///
190 /// An inbound backend must answer the drag source synchronously — XDND
191 /// requires an `XdndStatus` for every `XdndPosition`, and Wayland wants
192 /// `wl_data_offer::accept` + `set_actions` on the offer — which happens on
193 /// the backend's own thread, before the widget tree has seen the sample. So
194 /// the backend's first answer can only be about *format* compatibility;
195 /// this is how the widget's actual verdict gets back to the OS. Called by
196 /// the tree only when the answer changes.
197 ///
198 /// The negotiated *operation* follows from the bit: Copy when accepted,
199 /// none when refused. Copy is the only operation Teksilo advertises in
200 /// either direction, so there is nothing else for a widget to choose — see
201 /// `docs/drag-and-drop.md` §11.5.
202 ///
203 /// Default: no-op — the standalone sink and any platform without an
204 /// inbound backend.
205 fn set_drop_accepted(&mut self, _accepted: bool) {}
206
207 /// Abandon an OS drag requested with [`Self::begin_os_drag`]: the user
208 /// pressed Escape, or released the pointer before a pending start was
209 /// confirmed.
210 ///
211 /// A start that is still pending must not happen after this: the backend
212 /// drops it, or, if the native drag has already started, ends it. Once the
213 /// drag runs, macOS and Windows hand it to a modal OS loop that owns Escape
214 /// already, and this does nothing there; Wayland ends it by destroying its
215 /// data source (an Escape this window still receives, over one of its own
216 /// surfaces); X11 tracks the pointer on its own connection, so without this
217 /// its drags could only end by releasing the button. A backend that ends a running drag still reports the
218 /// terminal `DropOutcome`, so the source widget's `on_drag_ended` fires
219 /// exactly once regardless.
220 ///
221 /// Default: no-op.
222 fn cancel_os_drag(&mut self) {}
223
224 /// What the host platform can do about an on-screen keyboard.
225 ///
226 /// Read by a widget that must decide whether a touch-only user can reach a
227 /// keyboard at all: where the answer is [`SoftKeyboardSupport::None`] the
228 /// framework will never raise one and promises nothing about whether the
229 /// platform will, so a text surface that expects a finger has to offer its
230 /// own affordance.
231 ///
232 /// Default: [`SoftKeyboardSupport::None`], which is the truth for a
233 /// standalone tree with no window under it.
234 fn soft_keyboard_support(&self) -> SoftKeyboardSupport {
235 SoftKeyboardSupport::None
236 }
237
238 /// Ask the application to quit, asking every open window's close guard
239 /// in turn. See [`EventContext::quit`](crate::widget::EventContext::quit).
240 ///
241 /// Default: no-op, for a sink with no application behind it.
242 fn quit(&mut self) {}
243
244 /// Quit the application without asking any close guard. See
245 /// [`EventContext::quit_forced`](crate::widget::EventContext::quit_forced).
246 ///
247 /// Default: no-op, for a sink with no application behind it.
248 fn quit_forced(&mut self) {}
249
250 /// Whether a quit is under way: requested, and neither finished nor
251 /// abandoned. Default: `false`.
252 fn quit_in_progress(&self) -> bool {
253 false
254 }
255
256 /// Where the quit under way came from, or `None` when no quit is under
257 /// way. Default: `None`.
258 fn quit_source(&self) -> Option<crate::window::QuitSource> {
259 None
260 }
261
262 /// Abandon the quit under way, if it is a guarded one; see
263 /// [`EventContext::cancel_quit`](crate::widget::EventContext::cancel_quit).
264 /// Default: no-op.
265 fn cancel_quit(&mut self) {}
266
267 /// Take the activation token the event being dispatched carried, while
268 /// no window operation has used it: an intent kept for another tree takes
269 /// it with it, and nothing else can use it afterwards (a token is good
270 /// for one activation). Default: `None`, for a sink with no application
271 /// behind it.
272 #[doc(hidden)]
273 fn take_activation_token(&mut self) -> Option<String> {
274 None
275 }
276
277 /// Hold `token`, which an intent routed from another tree carried, for
278 /// the first window the actions it reaches open or raise. Paired with
279 /// [`release_activation_token`](Self::release_activation_token).
280 /// Default: no-op.
281 #[doc(hidden)]
282 fn hold_activation_token(&mut self, _token: String) {}
283
284 /// The routed intent's actions have run: a token they did not use is
285 /// left to a `WindowState::focus()` they queued, for this turn only, as
286 /// after any event that carried one, unless a token already waits for
287 /// such a focus (an earlier handler of the turn left it): that one
288 /// stays, whether this one was used or not. Default: no-op.
289 #[doc(hidden)]
290 fn release_activation_token(&mut self) {}
291}
292
293/// What a platform can do about an on-screen keyboard.
294///
295/// Three answers, and the difference between them is what a caller may
296/// *promise a user*, not how much code stands behind them.
297#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash)]
298#[non_exhaustive]
299pub enum SoftKeyboardSupport {
300 /// The framework has no keyboard request to send, and makes no promise
301 /// that anything will rise on its own. Either the platform has no software
302 /// keyboard at all, or it has one whose appearance is the platform's
303 /// business and not reliable enough to promise. A request is dropped, and a
304 /// text surface driven by touch needs its own affordance.
305 #[default]
306 None,
307 /// A keyboard exists and is **guaranteed** to rise when a text control
308 /// takes focus through the accessibility layer, so a touch-driven text
309 /// surface needs no affordance of its own. There is still nothing to ask:
310 /// the framework's ordinary IME-allowance reconcile is what summons it, and
311 /// an explicit ask would at best duplicate that and at worst re-assert
312 /// allowance, which cancels a live composition — so a request resolves to
313 /// "already done".
314 ///
315 /// The guarantee is what separates this from [`None`](Self::None), which
316 /// covers every platform where a keyboard may or may not appear.
317 ViaAccessibility,
318 /// A keyboard exists and can be shown and hidden on demand. Only a backend
319 /// that can honour **both** directions may report this: a toggle whose
320 /// current state is unknown cannot, because "show" would sometimes hide.
321 Explicit,
322}
323
324/// No-op implementation used by standalone `WidgetTree`s constructed
325/// outside of an app (tests, headless scenarios). Every method
326/// returns `None` / does nothing; `open_window` panics because a
327/// standalone tree has no winit back-end to create windows in.
328pub struct NoopWindowOps;
329
330impl WindowOps for NoopWindowOps {
331 fn open_window(&mut self, _config: WindowConfig) -> TeksiloWindowId {
332 panic!("open_window called on a standalone WidgetTree (no app context)");
333 }
334
335 fn find_window(&self, _string_id: &str) -> Option<TeksiloWindowId> {
336 None
337 }
338
339 fn window_state(&self, _id: TeksiloWindowId) -> Option<WindowState> {
340 None
341 }
342
343 fn windows(&self) -> Vec<WindowState> {
344 Vec::new()
345 }
346
347 fn focus_window(&mut self, _id: TeksiloWindowId) {}
348
349 fn close_window_by_id(&mut self, _id: TeksiloWindowId) {}
350}