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, FileLookup, ImageFit, ImageSource, NodeId, Pixels, Prop, Rect,
7    SurfaceHandle, SurfaceInput, SurfaceSize, Tweak, Ui, UiEvent, VectorIcon, 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    /// The app's own icon, drawn from path data: see [`VectorIcon`]. It
94    /// takes the size and colour a named icon takes, and shows in place of
95    /// one. `Icon::new("")` makes an icon without a name.
96    pub fn vector(mut self, icon: impl IntoValue<VectorIcon>) -> Icon {
97        self.0.prop(crate::some(icon.into_value()), Prop::VectorIcon);
98        self
99    }
100
101    /// Its accessible name: what the icon stands for.
102    pub fn label(mut self, label: impl IntoValue<String>) -> Icon {
103        self.0.prop(label.into_value(), Prop::Label);
104        self
105    }
106
107    /// Its colour, in place of the one the platform gives icons: a
108    /// semantic one (`Accent`, `SecondaryLabel`, `Error`, …) follows the
109    /// appearance; `Rgba` is fixed. Symbolic icons take it (SF Symbols,
110    /// Adwaita's and Breeze's `-symbolic` icons, Segoe Fluent glyphs);
111    /// icons in full colour keep theirs.
112    pub fn color(mut self, color: impl IntoValue<Color>) -> Icon {
113        self.0.prop(color.into_value(), Prop::TextColor);
114        self
115    }
116
117    /// How big it is, in points: an SF Symbol's point size, as a font's
118    /// (the symbol's own shape sets its frame), a square's side elsewhere.
119    pub fn icon_size(mut self, points: impl IntoValue<f32>) -> Icon {
120        self.0.prop(points.into_value(), Prop::IconSize);
121        self
122    }
123
124    /// Raw platform settings, past the semantic ones: see [`Tweak`].
125    pub fn native(mut self, tweak: Tweak<Icon>) -> Icon {
126        tweak.apply(&mut self.0);
127        self
128    }
129}
130
131/// A file's or folder's own icon, as the platform's file manager shows
132/// it: an app's own, a folder's custom one, a document's by its type (the
133/// icon theme's on Linux). It's a square as big as the platform's small
134/// icons (16 points) unless `icon_size` says otherwise. With `thumbnail`,
135/// a preview of what's in the file (a picture's, a document's first page)
136/// where the platform makes one. The file is read when it's set, unless
137/// `lookup` says to go by its name alone. Its label is its accessible
138/// name; without one it's decorative, as it usually sits beside the
139/// file's name.
140///
141/// ```ignore
142/// FileIcon::new(&entry.path).icon_size(32.0).thumbnail(true)
143/// FileIcon::new(&member.name).lookup(FileLookup::FileName)
144/// ```
145pub struct FileIcon(Element);
146
147widget!(FileIcon);
148
149impl FileIcon {
150    pub fn new(path: impl IntoValue<std::path::PathBuf>) -> FileIcon {
151        let mut element = Element::new(WidgetKind::FileIcon);
152        element.prop(path.into_value(), Prop::File);
153        FileIcon(element)
154    }
155
156    /// Its accessible name, where no text beside it names the file.
157    pub fn label(mut self, label: impl IntoValue<String>) -> FileIcon {
158        self.0.prop(label.into_value(), Prop::Label);
159        self
160    }
161
162    /// Its square's side, in points.
163    pub fn icon_size(mut self, points: impl IntoValue<f32>) -> FileIcon {
164        self.0.prop(points.into_value(), Prop::IconSize);
165        self
166    }
167
168    /// Shows a preview of what's in the file where the platform makes one
169    /// (macOS, Windows, and GNOME's cached ones), its icon until then.
170    pub fn thumbnail(mut self, thumbnail: impl IntoValue<bool>) -> FileIcon {
171        self.0.prop(thumbnail.into_value(), Prop::Thumbnail);
172        self
173    }
174
175    /// Where its icon comes from: the file on disk (the default), or only
176    /// its name, for a file that isn't there (nothing is read, and
177    /// `thumbnail` is ignored).
178    pub fn lookup(mut self, lookup: impl IntoValue<FileLookup>) -> FileIcon {
179        self.0.prop(lookup.into_value(), Prop::FileLookup);
180        self
181    }
182
183    /// Raw platform settings, past the semantic ones: see [`Tweak`].
184    pub fn native(mut self, tweak: Tweak<FileIcon>) -> FileIcon {
185        tweak.apply(&mut self.0);
186        self
187    }
188}
189
190/// A surface the app draws on with its own GPU API (wgpu, Vulkan, Metal,
191/// Direct3D), at its own pace and on its own thread, as it would draw on a
192/// window of its own: an `NSView` backed by a `CAMetalLayer` on AppKit.
193/// It has no natural size; the layout sizes it.
194///
195/// `on_ready` gets its [`SurfaceHandle`] once the native surface exists,
196/// and `on_resize` its size in pixels whenever that or its scale changes;
197/// the handle's `size()` has it too, for a render thread. The handle keeps
198/// the native surface alive after the widget is gone, so drop it (and the
199/// GPU surface made on it) when the app is done presenting.
200///
201/// The surface sits above the window's own content, as the platform
202/// layers it. Its label is its accessible name.
203///
204/// With `on_input` it takes keys and the pointer: a click or Tab focuses
205/// it, and it gets every key the window doesn't take first for its menus'
206/// shortcuts, Tab too (Control+Tab leaves it on AppKit and GTK, as it
207/// leaves a text view). `pointer_lock` hides and holds the cursor and
208/// reports its moves; `keyboard_grab` takes the system's shortcuts and
209/// the app's own as well. The platform ends both when the window stops
210/// being the active one (the grab also when the surface loses focus), and
211/// sets their signals back to `false`: the app locks again, say, on the
212/// next click. `cursor` is the cursor over it: the platform's, none, or
213/// the app's own image.
214///
215/// ```ignore
216/// GpuSurface::new()
217///     .label("Machine")
218///     .on_ready(move |surface| renderer.send(Message::Surface(surface)))
219///     .on_resize(move |size| renderer.send(Message::Resize(size)))
220///     .on_input(move |input| machine.send(Message::Input(input)))
221///     .pointer_lock(captured)
222///     .keyboard_grab(captured)
223/// ```
224pub struct GpuSurface(Element);
225
226widget!(GpuSurface);
227
228impl Default for GpuSurface {
229    fn default() -> GpuSurface {
230        GpuSurface::new()
231    }
232}
233
234impl GpuSurface {
235    pub fn new() -> GpuSurface {
236        GpuSurface(Element::new(WidgetKind::GpuSurface))
237    }
238
239    /// Its accessible name: what the app draws there.
240    pub fn label(mut self, label: impl IntoValue<String>) -> GpuSurface {
241        self.0.prop(label.into_value(), Prop::Label);
242        self
243    }
244
245    /// The window it's in became the active one, or stopped being it. The surface keeps its
246    /// focus through this: a caret it paints should stop anyway, as a text field's does.
247    pub fn on_window_active(mut self, handler: impl Fn(bool) + 'static) -> GpuSurface {
248        self.0.on(move |event| {
249            if let UiEvent::WindowActiveChanged(active) = event {
250                handler(*active);
251            }
252        });
253        self
254    }
255
256    /// The native surface exists: make the GPU surface on it. Called once.
257    pub fn on_ready(mut self, handler: impl Fn(SurfaceHandle) + 'static) -> GpuSurface {
258        self.0.on(move |event| {
259            if let UiEvent::SurfaceReady(surface) = event {
260                handler(surface.clone());
261            }
262        });
263        self
264    }
265
266    /// Its size in pixels, or its scale, changed: configure the GPU
267    /// surface for it.
268    pub fn on_resize(mut self, handler: impl Fn(SurfaceSize) + 'static) -> GpuSurface {
269        self.0.on(move |event| {
270            if let UiEvent::SurfaceResized(size) = event {
271                handler(*size);
272            }
273        });
274        self
275    }
276
277    /// Takes keys and the pointer, and reports them: a key down or up, the
278    /// pointer's moves, buttons and scrolling over it, and while it's
279    /// locked, how far it moved. Keys down when it loses focus, or its
280    /// window stops being the active one, are reported released then.
281    pub fn on_input(mut self, handler: impl Fn(SurfaceInput) + 'static) -> GpuSurface {
282        self.0.prop(Value::Static(true), Prop::TakesInput);
283        self.0.on(move |event| {
284            if let UiEvent::SurfaceInput(input) = event {
285                handler(input.clone());
286            }
287        });
288        self
289    }
290
291    /// Hides and holds the cursor while `locked` is true, reporting its
292    /// moves as `SurfaceInput::Motion`, and before the host's acceleration
293    /// as `SurfaceInput::RawMotion`. The platform ends it when the
294    /// window stops being the active one, and `locked` goes back to false.
295    pub fn pointer_lock(mut self, locked: Signal<bool>) -> GpuSurface {
296        self.0.prop(locked.into_value(), Prop::PointerLock);
297        self.0.on(move |event| {
298            if *event == UiEvent::PointerLockEnded {
299                locked.set(false);
300            }
301        });
302        self
303    }
304
305    /// The pointer's cursor over it, while it isn't locked: the
306    /// platform's own, none, or an image of the app's (the one a machine
307    /// gives its pointer, say).
308    pub fn cursor(mut self, cursor: impl IntoValue<Cursor>) -> GpuSurface {
309        self.0.prop(cursor.into_value(), Prop::Cursor);
310        self
311    }
312
313    /// Takes text, as a text field does, while `on` is true: keys report
314    /// what they type (`SurfaceInput::Key`'s `text`), and the platform's
315    /// input methods are on while it has focus, committing as
316    /// `SurfaceInput::Text`. With `on_input`, which reports them.
317    pub fn text_input(mut self, on: impl IntoValue<bool>) -> GpuSurface {
318        self.0.prop(on.into_value(), Prop::TextInput);
319        self
320    }
321
322    /// Whether the platform's input methods are on while it takes text,
323    /// as they are unless `on` is false: off, keys still report what they
324    /// type (layouts, dead keys, AltGr), but nothing composes. For a modal
325    /// editor, whose keys outside insert mode are commands.
326    pub fn input_method(mut self, on: impl IntoValue<bool>) -> GpuSurface {
327        self.0.prop(on.into_value(), Prop::InputMethod);
328        self
329    }
330
331    /// Where the caret is, in points from its top left, while it takes
332    /// text: the input method's candidate window opens by it.
333    pub fn text_cursor(mut self, caret: impl IntoValue<Option<Rect>>) -> GpuSurface {
334        self.0.prop(caret.into_value(), Prop::TextCursor);
335        self
336    }
337
338    /// Lets the window's backdrop show through it while `on` is true,
339    /// where what the app presents isn't opaque: AppKit puts its
340    /// behind-window vibrancy under it, and WinUI's windows have Mica
341    /// already; GTK and Kirigami have no backdrop, so the window's own
342    /// background shows. The app presents with alpha, premultiplied as
343    /// the compositor reads it (wgpu's `PostMultiplied` mode on Metal, a
344    /// composition swapchain with `PreMultiplied` on Direct3D 12).
345    pub fn transparent(mut self, on: impl IntoValue<bool>) -> GpuSurface {
346        self.0.prop(on.into_value(), Prop::Transparent);
347        self
348    }
349
350    /// Takes every key while `grabbed` is true, the system's shortcuts
351    /// (as far as the platform lets an app) and the window's own too, and
352    /// focuses the surface. The platform ends it when the surface or its
353    /// window loses focus, and `grabbed` goes back to false.
354    pub fn keyboard_grab(mut self, grabbed: Signal<bool>) -> GpuSurface {
355        self.0.prop(grabbed.into_value(), Prop::KeyboardGrab);
356        self.0.on(move |event| {
357            if *event == UiEvent::KeyboardGrabEnded {
358                grabbed.set(false);
359            }
360        });
361        self
362    }
363}
364
365impl Image {
366    /// `<Image source=ImageSource::File("logo.png".into()) label="Logo"/>`
367    #[doc(hidden)]
368    pub fn __tag() -> Image {
369        Image(Element::new(WidgetKind::Image))
370    }
371
372    #[doc(hidden)]
373    pub fn source(mut self, source: impl IntoValue<ImageSource>) -> Image {
374        self.0.prop(source.into_value(), Prop::Image);
375        self
376    }
377}
378
379impl Icon {
380    /// `<Icon name="trash" label="Delete"/>`
381    #[doc(hidden)]
382    pub fn __tag() -> Icon {
383        Icon(Element::new(WidgetKind::Icon))
384    }
385
386    #[doc(hidden)]
387    pub fn name(mut self, name: impl IntoValue<String>) -> Icon {
388        self.0.prop(name.into_value(), Prop::Icon);
389        self
390    }
391}
392
393impl FileIcon {
394    /// `<FileIcon path=entry.path icon_size=32.0/>`
395    #[doc(hidden)]
396    pub fn __tag() -> FileIcon {
397        FileIcon(Element::new(WidgetKind::FileIcon))
398    }
399
400    #[doc(hidden)]
401    pub fn path(mut self, path: impl IntoValue<std::path::PathBuf>) -> FileIcon {
402        self.0.prop(path.into_value(), Prop::File);
403        self
404    }
405}
406
407impl GpuSurface {
408    /// `<GpuSurface label="Machine" @ready=… @resize=… @input=… pointer_lock=captured/>`
409    #[doc(hidden)]
410    pub fn __tag() -> GpuSurface {
411        GpuSurface::new()
412    }
413}