Skip to main content

mitsuami_widgets/
media.rs

1//! Images, icons, files' icons and GPU surfaces.
2
3use std::rc::Rc;
4
5use mitsuami_core::{
6    Color, Cursor, Element, ElementBuilder, ImageFit, ImageSource, NodeId, Pixels, Prop, Rect, SurfaceHandle,
7    SurfaceInput, SurfaceSize, Tweak, Ui, UiEvent, View, WidgetKind,
8};
9use mitsuami_reactive::{IntoValue, Signal, Value};
10
11/// A picture, in the platform's image view: from a file, or from pixels
12/// in memory. It's as large as the image (in points: pixels over their
13/// scale) unless the layout sizes it; then `fit` says how it fills the
14/// frame, or the platform does as it does by default. Its label is its
15/// accessible name; without one it's decorative.
16///
17/// ```ignore
18/// Image::file("logo.png").label("2ksbox")
19/// Image::new(move || ImageSource::Pixels(frame.get())).label("Preview")
20/// ```
21pub struct Image(Element);
22
23widget!(Image);
24
25impl Image {
26    pub fn new(source: impl IntoValue<ImageSource>) -> Image {
27        let mut element = Element::new(WidgetKind::Image);
28        element.prop(source.into_value(), Prop::Image);
29        Image(element)
30    }
31
32    /// An image file, read by the platform.
33    pub fn file(path: impl Into<std::path::PathBuf>) -> Image {
34        Image::new(ImageSource::File(path.into()))
35    }
36
37    /// Pixels in memory.
38    pub fn pixels(pixels: impl IntoValue<Pixels>) -> Image {
39        let pixels = pixels.into_value();
40        Image::new(match pixels {
41            Value::Static(p) => Value::Static(ImageSource::Pixels(p)),
42            dynamic => Value::Dynamic(Rc::new(move || ImageSource::Pixels(dynamic.get()))),
43        })
44    }
45
46    /// Its accessible name: what the picture shows.
47    pub fn label(mut self, label: impl IntoValue<String>) -> Image {
48        self.0.prop(label.into_value(), Prop::Label);
49        self
50    }
51
52    /// How it fills a frame of another size than its own.
53    pub fn fit(mut self, fit: impl IntoValue<ImageFit>) -> Image {
54        self.0.prop(fit.into_value(), Prop::ImageFit);
55        self
56    }
57
58    /// Raw platform settings, past the semantic ones: see [`Tweak`].
59    pub fn native(mut self, tweak: Tweak<Image>) -> Image {
60        tweak.apply(&mut self.0);
61        self
62    }
63}
64
65/// An icon from the platform's own set, by its name there: an SF Symbol
66/// on macOS, a themed icon's name on Linux (Adwaita's symbolic ones on
67/// GNOME, Breeze's on KDE), a Segoe Fluent Icons glyph on Windows. Names
68/// differ, so pick one per platform with `platform!`. Symbolic icons are
69/// drawn in the colour the platform gives icons, which follows dark mode.
70/// It's as large as the platform makes icons unless
71/// `icon_size` says otherwise. Its label is its accessible name; without
72/// one it's decorative.
73///
74/// ```ignore
75/// Icon::new(platform! {
76///     macos => "trash",
77///     gtk => "user-trash-symbolic",
78///     kde => "edit-delete",
79///     windows => "\u{E74D}",
80/// })
81/// ```
82pub struct Icon(Element);
83
84widget!(Icon);
85
86impl Icon {
87    pub fn new(name: impl IntoValue<String>) -> Icon {
88        let mut element = Element::new(WidgetKind::Icon);
89        element.prop(name.into_value(), Prop::Icon);
90        Icon(element)
91    }
92
93    /// Its accessible name: what the icon stands for.
94    pub fn label(mut self, label: impl IntoValue<String>) -> Icon {
95        self.0.prop(label.into_value(), Prop::Label);
96        self
97    }
98
99    /// Its colour, in place of the one the platform gives icons: a
100    /// semantic one (`Accent`, `SecondaryLabel`, `Error`, …) follows the
101    /// appearance; `Rgba` is fixed. Symbolic icons take it (SF Symbols,
102    /// Adwaita's and Breeze's `-symbolic` icons, Segoe Fluent glyphs);
103    /// icons in full colour keep theirs.
104    pub fn color(mut self, color: impl IntoValue<Color>) -> Icon {
105        self.0.prop(color.into_value(), Prop::TextColor);
106        self
107    }
108
109    /// How big it is, in points: an SF Symbol's point size, as a font's
110    /// (the symbol's own shape sets its frame), a square's side elsewhere.
111    pub fn icon_size(mut self, points: impl IntoValue<f32>) -> Icon {
112        self.0.prop(points.into_value(), Prop::IconSize);
113        self
114    }
115
116    /// Raw platform settings, past the semantic ones: see [`Tweak`].
117    pub fn native(mut self, tweak: Tweak<Icon>) -> Icon {
118        tweak.apply(&mut self.0);
119        self
120    }
121}
122
123/// A file's or folder's own icon, as the platform's file manager shows
124/// it: an app's own, a folder's custom one, a document's by its type (the
125/// icon theme's on Linux). It's a square as big as the platform's small
126/// icons (16 points) unless `icon_size` says otherwise. With `thumbnail`,
127/// a preview of what's in the file (a picture's, a document's first page)
128/// where the platform makes one. The file is read when it's set. Its
129/// label is its accessible name; without one it's decorative, as it
130/// usually sits beside the file's name.
131///
132/// ```ignore
133/// FileIcon::new(&entry.path).icon_size(32.0).thumbnail(true)
134/// ```
135pub struct FileIcon(Element);
136
137widget!(FileIcon);
138
139impl FileIcon {
140    pub fn new(path: impl IntoValue<std::path::PathBuf>) -> FileIcon {
141        let mut element = Element::new(WidgetKind::FileIcon);
142        element.prop(path.into_value(), Prop::File);
143        FileIcon(element)
144    }
145
146    /// Its accessible name, where no text beside it names the file.
147    pub fn label(mut self, label: impl IntoValue<String>) -> FileIcon {
148        self.0.prop(label.into_value(), Prop::Label);
149        self
150    }
151
152    /// Its square's side, in points.
153    pub fn icon_size(mut self, points: impl IntoValue<f32>) -> FileIcon {
154        self.0.prop(points.into_value(), Prop::IconSize);
155        self
156    }
157
158    /// Shows a preview of what's in the file where the platform makes one
159    /// (macOS, Windows, and GNOME's cached ones), its icon until then.
160    pub fn thumbnail(mut self, thumbnail: impl IntoValue<bool>) -> FileIcon {
161        self.0.prop(thumbnail.into_value(), Prop::Thumbnail);
162        self
163    }
164
165    /// Raw platform settings, past the semantic ones: see [`Tweak`].
166    pub fn native(mut self, tweak: Tweak<FileIcon>) -> FileIcon {
167        tweak.apply(&mut self.0);
168        self
169    }
170}
171
172/// A surface the app draws on with its own GPU API (wgpu, Vulkan, Metal,
173/// Direct3D), at its own pace and on its own thread, as it would draw on a
174/// window of its own: an `NSView` backed by a `CAMetalLayer` on AppKit.
175/// It has no natural size; the layout sizes it.
176///
177/// `on_ready` gets its [`SurfaceHandle`] once the native surface exists,
178/// and `on_resize` its size in pixels whenever that or its scale changes;
179/// the handle's `size()` has it too, for a render thread. The handle keeps
180/// the native surface alive after the widget is gone, so drop it (and the
181/// GPU surface made on it) when the app is done presenting.
182///
183/// The surface sits above the window's own content, as the platform
184/// layers it. Its label is its accessible name.
185///
186/// With `on_input` it takes keys and the pointer: a click or Tab focuses
187/// it, and it gets every key the window doesn't take first for its menus'
188/// shortcuts, Tab too (Control+Tab leaves it on AppKit and GTK, as it
189/// leaves a text view). `pointer_lock` hides and holds the cursor and
190/// reports its moves; `keyboard_grab` takes the system's shortcuts and
191/// the app's own as well. The platform ends both when the window stops
192/// being the active one (the grab also when the surface loses focus), and
193/// sets their signals back to `false`: the app locks again, say, on the
194/// next click. `cursor` is the cursor over it: the platform's, none, or
195/// the app's own image.
196///
197/// ```ignore
198/// GpuSurface::new()
199///     .label("Machine")
200///     .on_ready(move |surface| renderer.send(Message::Surface(surface)))
201///     .on_resize(move |size| renderer.send(Message::Resize(size)))
202///     .on_input(move |input| machine.send(Message::Input(input)))
203///     .pointer_lock(captured)
204///     .keyboard_grab(captured)
205/// ```
206pub struct GpuSurface(Element);
207
208widget!(GpuSurface);
209
210impl Default for GpuSurface {
211    fn default() -> GpuSurface {
212        GpuSurface::new()
213    }
214}
215
216impl GpuSurface {
217    pub fn new() -> GpuSurface {
218        GpuSurface(Element::new(WidgetKind::GpuSurface))
219    }
220
221    /// Its accessible name: what the app draws there.
222    pub fn label(mut self, label: impl IntoValue<String>) -> GpuSurface {
223        self.0.prop(label.into_value(), Prop::Label);
224        self
225    }
226
227    /// The native surface exists: make the GPU surface on it. Called once.
228    pub fn on_ready(mut self, handler: impl Fn(SurfaceHandle) + 'static) -> GpuSurface {
229        self.0.on(move |event| {
230            if let UiEvent::SurfaceReady(surface) = event {
231                handler(surface.clone());
232            }
233        });
234        self
235    }
236
237    /// Its size in pixels, or its scale, changed: configure the GPU
238    /// surface for it.
239    pub fn on_resize(mut self, handler: impl Fn(SurfaceSize) + 'static) -> GpuSurface {
240        self.0.on(move |event| {
241            if let UiEvent::SurfaceResized(size) = event {
242                handler(*size);
243            }
244        });
245        self
246    }
247
248    /// Takes keys and the pointer, and reports them: a key down or up, the
249    /// pointer's moves, buttons and scrolling over it, and while it's
250    /// locked, how far it moved. Keys down when it loses focus, or its
251    /// window stops being the active one, are reported released then.
252    pub fn on_input(mut self, handler: impl Fn(SurfaceInput) + 'static) -> GpuSurface {
253        self.0.prop(Value::Static(true), Prop::TakesInput);
254        self.0.on(move |event| {
255            if let UiEvent::SurfaceInput(input) = event {
256                handler(input.clone());
257            }
258        });
259        self
260    }
261
262    /// Hides and holds the cursor while `locked` is true, reporting its
263    /// moves as `SurfaceInput::Motion`, and before the host's acceleration
264    /// as `SurfaceInput::RawMotion`. The platform ends it when the
265    /// window stops being the active one, and `locked` goes back to false.
266    pub fn pointer_lock(mut self, locked: Signal<bool>) -> GpuSurface {
267        self.0.prop(locked.into_value(), Prop::PointerLock);
268        self.0.on(move |event| {
269            if *event == UiEvent::PointerLockEnded {
270                locked.set(false);
271            }
272        });
273        self
274    }
275
276    /// The pointer's cursor over it, while it isn't locked: the
277    /// platform's own, none, or an image of the app's (the one a machine
278    /// gives its pointer, say).
279    pub fn cursor(mut self, cursor: impl IntoValue<Cursor>) -> GpuSurface {
280        self.0.prop(cursor.into_value(), Prop::Cursor);
281        self
282    }
283
284    /// Takes text, as a text field does, while `on` is true: keys report
285    /// what they type (`SurfaceInput::Key`'s `text`), and the platform's
286    /// input methods are on while it has focus, committing as
287    /// `SurfaceInput::Text`. With `on_input`, which reports them.
288    pub fn text_input(mut self, on: impl IntoValue<bool>) -> GpuSurface {
289        self.0.prop(on.into_value(), Prop::TextInput);
290        self
291    }
292
293    /// Whether the platform's input methods are on while it takes text,
294    /// as they are unless `on` is false: off, keys still report what they
295    /// type (layouts, dead keys, AltGr), but nothing composes. For a modal
296    /// editor, whose keys outside insert mode are commands.
297    pub fn input_method(mut self, on: impl IntoValue<bool>) -> GpuSurface {
298        self.0.prop(on.into_value(), Prop::InputMethod);
299        self
300    }
301
302    /// Where the caret is, in points from its top left, while it takes
303    /// text: the input method's candidate window opens by it.
304    pub fn text_cursor(mut self, caret: impl IntoValue<Option<Rect>>) -> GpuSurface {
305        self.0.prop(caret.into_value(), Prop::TextCursor);
306        self
307    }
308
309    /// Lets the window's backdrop show through it while `on` is true,
310    /// where what the app presents isn't opaque: AppKit puts its
311    /// behind-window vibrancy under it, and WinUI's windows have Mica
312    /// already; GTK and Kirigami have no backdrop, so the window's own
313    /// background shows. The app presents with alpha, premultiplied as
314    /// the compositor reads it (wgpu's `PostMultiplied` mode on Metal, a
315    /// composition swapchain with `PreMultiplied` on Direct3D 12).
316    pub fn transparent(mut self, on: impl IntoValue<bool>) -> GpuSurface {
317        self.0.prop(on.into_value(), Prop::Transparent);
318        self
319    }
320
321    /// Takes every key while `grabbed` is true, the system's shortcuts
322    /// (as far as the platform lets an app) and the window's own too, and
323    /// focuses the surface. The platform ends it when the surface or its
324    /// window loses focus, and `grabbed` goes back to false.
325    pub fn keyboard_grab(mut self, grabbed: Signal<bool>) -> GpuSurface {
326        self.0.prop(grabbed.into_value(), Prop::KeyboardGrab);
327        self.0.on(move |event| {
328            if *event == UiEvent::KeyboardGrabEnded {
329                grabbed.set(false);
330            }
331        });
332        self
333    }
334}
335
336impl Image {
337    /// `<Image source=ImageSource::File("logo.png".into()) label="Logo"/>`
338    #[doc(hidden)]
339    pub fn __tag() -> Image {
340        Image(Element::new(WidgetKind::Image))
341    }
342
343    #[doc(hidden)]
344    pub fn source(mut self, source: impl IntoValue<ImageSource>) -> Image {
345        self.0.prop(source.into_value(), Prop::Image);
346        self
347    }
348}
349
350impl Icon {
351    /// `<Icon name="trash" label="Delete"/>`
352    #[doc(hidden)]
353    pub fn __tag() -> Icon {
354        Icon(Element::new(WidgetKind::Icon))
355    }
356
357    #[doc(hidden)]
358    pub fn name(mut self, name: impl IntoValue<String>) -> Icon {
359        self.0.prop(name.into_value(), Prop::Icon);
360        self
361    }
362}
363
364impl FileIcon {
365    /// `<FileIcon path=entry.path icon_size=32.0/>`
366    #[doc(hidden)]
367    pub fn __tag() -> FileIcon {
368        FileIcon(Element::new(WidgetKind::FileIcon))
369    }
370
371    #[doc(hidden)]
372    pub fn path(mut self, path: impl IntoValue<std::path::PathBuf>) -> FileIcon {
373        self.0.prop(path.into_value(), Prop::File);
374        self
375    }
376}
377
378impl GpuSurface {
379    /// `<GpuSurface label="Machine" @ready=… @resize=… @input=… pointer_lock=captured/>`
380    #[doc(hidden)]
381    pub fn __tag() -> GpuSurface {
382        GpuSurface::new()
383    }
384}