Skip to main content

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//! All calls are **synchronous**: `open_window` creates the winit
12//! window and registers it before returning; the returned id is
13//! immediately usable for `focus_window`, `window_state`,
14//! `close_window_by_id`. The trait exists to keep teksilo-core
15//! independent of teksilo-app — teksilo-core defines the contract, teksilo-app
16//! provides the implementation.
17
18use super::config::WindowConfig;
19use super::id::TeksiloWindowId;
20use super::state::WindowState;
21use crate::raw_handle::ParentHandle;
22
23/// App-level window operations exposed to handlers.
24///
25/// Implemented by `teksilo_app::WindowManager` (via a short-lived
26/// wrapper that also holds `&ActiveEventLoop`). Passed into every
27/// dispatch site as `&mut dyn WindowOps` and stored on
28/// [`EventContext`](crate::widget::EventContext).
29pub trait WindowOps {
30    /// Open a new window. Creates the winit-level window
31    /// synchronously inside this call and returns its id, which is
32    /// immediately valid for any other method on this trait.
33    fn open_window(&mut self, config: WindowConfig) -> TeksiloWindowId;
34
35    /// Look up a window by the stable string id it was opened with
36    /// (`WindowConfig::id`). Returns `None` if no live window carries
37    /// that id.
38    fn find_window(&self, string_id: &str) -> Option<TeksiloWindowId>;
39
40    /// Read the reactive state for a specific window.
41    fn window_state(&self, id: TeksiloWindowId) -> Option<WindowState>;
42
43    /// Every live window's state, in creation order.
44    fn windows(&self) -> Vec<WindowState>;
45
46    /// Raise a window and give it keyboard focus.
47    fn focus_window(&mut self, id: TeksiloWindowId);
48
49    /// Request an `xdg_activation_v1` token for `id` — to hand to another window
50    /// or a child process so it can raise itself on Wayland. `cb` fires once with
51    /// the token string, or with `None` where unsupported (everything but
52    /// Wayland/X11). Default implementation: immediate `None`.
53    fn request_activation_token(
54        &mut self,
55        _id: TeksiloWindowId,
56        cb: Box<dyn FnOnce(Option<String>)>,
57    ) {
58        cb(None);
59    }
60
61    /// Like [`request_activation_token`](Self::request_activation_token) but for
62    /// the **current dispatching** window — the one whose handler is running.
63    /// Works even mid-dispatch, when that window is temporarily out of the
64    /// manager's map, because it uses the captured window handle instead of an id
65    /// lookup. Use this when a focused widget needs a token to hand to another
66    /// window or process. Default implementation: immediate `None`.
67    fn request_activation_token_self(&mut self, cb: Box<dyn FnOnce(Option<String>)>) {
68        cb(None);
69    }
70
71    /// Close a specific window by id. The window is fully torn down
72    /// before the next event-loop tick.
73    fn close_window_by_id(&mut self, id: TeksiloWindowId);
74
75    /// Extract the platform parent handle of the window currently
76    /// dispatching the event (the one that owns the in-flight
77    /// `EventContext`). Used by native-dialog integrations
78    /// (`teksilo_platform::file_dialog`) to parent OS dialogs to the
79    /// originating Teksilo window.
80    ///
81    /// Returns `None` for the standalone / test sink and on rare
82    /// platform paths where the underlying surface refuses a handle
83    /// (e.g. during shutdown).
84    fn current_parent_handle(&self) -> Option<ParentHandle> {
85        None
86    }
87
88    /// Report the focused text widget's caret rectangle (in window-logical
89    /// pixels) so the platform can position the OS IME candidate window
90    /// next to the insertion point. Called from text-editing widgets
91    /// whenever the caret moves. The app applies it to the in-flight
92    /// window's `set_ime_cursor_area`, deduped against the last value.
93    ///
94    /// No-op on the standalone / test sink.
95    fn set_ime_cursor_area(&mut self, _area: teksilo_canvas::Rect) {}
96
97    /// Hand an OS-level drag to the platform when an in-app drag escalates at
98    /// the window boundary (the pointer left the window carrying an
99    /// OS-exportable payload). The platform backend
100    /// (`teksilo_platform::external_dnd`) starts a native drag session
101    /// (`NSDraggingSource` / `wl_data_source` / OLE `IDropSource`) using
102    /// `data`, optionally drawing `image` as the drag cursor.
103    ///
104    /// Returns `true` if a native drag session actually started. The default
105    /// (standalone / test sink, and platforms without an outbound backend,
106    /// a headless build, or a target with no drop-target implementation)
107    /// returns `false`, in which case the framework cancels the drag
108    /// — the pre-existing "pointer left the window ⇒ drag cancels" behavior.
109    /// `pointer` is the device carrying the drag. It is not decoration: on
110    /// Wayland `wl_data_device::start_drag` must be given the serial of the
111    /// input event that began the implicit grab, and a finger's grab was opened
112    /// by a `wl_touch::down`, not a `wl_pointer::button` — hand the wrong
113    /// serial over and the compositor rejects the request silently and sends no
114    /// terminal event at all.
115    fn begin_os_drag(
116        &mut self,
117        _data: crate::drag_payload::OutboundDragData,
118        _image: Option<crate::drag_payload::DragImageData>,
119        _pointer: teksilo_tokens::PointerKind,
120    ) -> bool {
121        false
122    }
123
124    /// Tell the platform whether the widget under an **inbound** OS drag
125    /// accepts it, so the OS shows the right cursor and permits (or refuses)
126    /// the drop.
127    ///
128    /// An inbound backend must answer the drag source synchronously — XDND
129    /// requires an `XdndStatus` for every `XdndPosition`, and Wayland wants
130    /// `wl_data_offer::accept` + `set_actions` on the offer — which happens on
131    /// the backend's own thread, before the widget tree has seen the sample. So
132    /// the backend's first answer can only be about *format* compatibility;
133    /// this is how the widget's actual verdict gets back to the OS. Called by
134    /// the tree only when the answer changes.
135    ///
136    /// The negotiated *operation* follows from the bit: Copy when accepted,
137    /// none when refused. Copy is the only operation Teksilo advertises in
138    /// either direction, so there is nothing else for a widget to choose — see
139    /// `docs/drag-and-drop.md` §11.5.
140    ///
141    /// Default: no-op — the standalone sink and any platform without an
142    /// inbound backend.
143    fn set_drop_accepted(&mut self, _accepted: bool) {}
144
145    /// Abandon an OS drag started by [`Self::begin_os_drag`] (the user pressed
146    /// Escape).
147    ///
148    /// Only backends that drive the drag themselves can honour this. macOS and
149    /// Windows hand the drag to a modal OS loop that owns Escape already, and
150    /// Wayland's compositor does the same; X11 tracks the pointer on its own
151    /// connection, so without this its drags could only end by releasing the
152    /// button. The backend still reports the terminal `DropOutcome` either way,
153    /// so the source widget's `on_drag_ended` fires exactly once regardless.
154    ///
155    /// Default: no-op.
156    fn cancel_os_drag(&mut self) {}
157
158    /// What the host platform can do about an on-screen keyboard.
159    ///
160    /// Read by a widget that must decide whether a touch-only user can reach a
161    /// keyboard at all: where the answer is [`SoftKeyboardSupport::None`] the
162    /// framework will never raise one and promises nothing about whether the
163    /// platform will, so a text surface that expects a finger has to offer its
164    /// own affordance.
165    ///
166    /// Default: [`SoftKeyboardSupport::None`], which is the truth for a
167    /// standalone tree with no window under it.
168    fn soft_keyboard_support(&self) -> SoftKeyboardSupport {
169        SoftKeyboardSupport::None
170    }
171}
172
173/// What a platform can do about an on-screen keyboard.
174///
175/// Three answers, and the difference between them is what a caller may
176/// *promise a user*, not how much code stands behind them.
177#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash)]
178#[non_exhaustive]
179pub enum SoftKeyboardSupport {
180    /// The framework has no keyboard request to send, and makes no promise
181    /// that anything will rise on its own. Either the platform has no software
182    /// keyboard at all, or it has one whose appearance is the platform's
183    /// business and not reliable enough to promise. A request is dropped, and a
184    /// text surface driven by touch needs its own affordance.
185    #[default]
186    None,
187    /// A keyboard exists and is **guaranteed** to rise when a text control
188    /// takes focus through the accessibility layer, so a touch-driven text
189    /// surface needs no affordance of its own. There is still nothing to ask:
190    /// the framework's ordinary IME-allowance reconcile is what summons it, and
191    /// an explicit ask would at best duplicate that and at worst re-assert
192    /// allowance, which cancels a live composition — so a request resolves to
193    /// "already done".
194    ///
195    /// The guarantee is what separates this from [`None`](Self::None), which
196    /// covers every platform where a keyboard may or may not appear.
197    ViaAccessibility,
198    /// A keyboard exists and can be shown and hidden on demand. Only a backend
199    /// that can honour **both** directions may report this: a toggle whose
200    /// current state is unknown cannot, because "show" would sometimes hide.
201    Explicit,
202}
203
204/// No-op implementation used by standalone `WidgetTree`s constructed
205/// outside of an app (tests, headless scenarios). Every method
206/// returns `None` / does nothing; `open_window` panics because a
207/// standalone tree has no winit back-end to create windows in.
208pub struct NoopWindowOps;
209
210impl WindowOps for NoopWindowOps {
211    fn open_window(&mut self, _config: WindowConfig) -> TeksiloWindowId {
212        panic!("open_window called on a standalone WidgetTree (no app context)");
213    }
214
215    fn find_window(&self, _string_id: &str) -> Option<TeksiloWindowId> {
216        None
217    }
218
219    fn window_state(&self, _id: TeksiloWindowId) -> Option<WindowState> {
220        None
221    }
222
223    fn windows(&self) -> Vec<WindowState> {
224        Vec::new()
225    }
226
227    fn focus_window(&mut self, _id: TeksiloWindowId) {}
228
229    fn close_window_by_id(&mut self, _id: TeksiloWindowId) {}
230}