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