Skip to main content

rungui/
types.rs

1//! Small plain-data types shared by the public API and the backends.
2
3use std::fmt;
4
5/// Symbolic, never-reused handle to a widget in the registry. `0` is the "dead" id.
6/// Plain `u64` inside: `Copy`, `Send`, safe to keep after the widget is destroyed
7/// (operations on stale ids are no-ops).
8#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
9pub struct WidgetId(pub u64);
10
11impl WidgetId {
12    /// The id carried by handles whose creation failed.
13    pub const DEAD: WidgetId = WidgetId(0);
14}
15
16/// Largest widget extent or coordinate pushed to a backend, in logical pixels. X11 and Win32 keep
17/// window-system coordinates in 16 bits, so anything beyond this could not be shown anyway; larger
18/// requests are clamped instead of overflowing layout arithmetic or tripping toolkit warnings.
19pub(crate) const MAX_PX: i32 = i16::MAX as i32;
20/// Largest window client size. Toolkits allocate a backing store for a window, so this is kept to
21/// what a real display can have rather than the coordinate limit.
22pub(crate) const MAX_WINDOW_PX: i32 = 1 << 14;
23
24/// Rectangle in logical (DPI-independent) pixels; origin top-left, y grows downward.
25#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
26pub struct Rect {
27    /// Left edge.
28    pub x: i32,
29    /// Top edge.
30    pub y: i32,
31    /// Width.
32    pub w: i32,
33    /// Height.
34    pub h: i32,
35}
36
37impl Rect {
38    /// A rectangle from its position and size.
39    pub const fn new(x: i32, y: i32, w: i32, h: i32) -> Rect {
40        Rect { x, y, w, h }
41    }
42}
43
44/// Width/height in logical pixels.
45#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
46pub struct Size {
47    /// Width.
48    pub w: i32,
49    /// Height.
50    pub h: i32,
51}
52
53impl Size {
54    /// A size from its width and height.
55    pub const fn new(w: i32, h: i32) -> Size {
56        Size { w, h }
57    }
58}
59
60/// A calendar date in the proleptic Gregorian calendar, years 1753 to 9999 (the range every
61/// native calendar control supports).
62#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
63pub struct Date {
64    /// Year, 1753..=9999.
65    pub year: i32,
66    /// Month, 1..=12.
67    pub month: u32,
68    /// Day of the month, 1..=31 (as many as the month has).
69    pub day: u32,
70}
71
72impl Date {
73    /// `None` unless this is a real date in the supported years.
74    pub fn new(year: i32, month: u32, day: u32) -> Option<Date> {
75        let d = Date { year, month, day };
76        d.is_valid().then_some(d)
77    }
78    /// Is this a real date in the supported years?
79    pub fn is_valid(&self) -> bool {
80        (1753..=9999).contains(&self.year)
81            && (1..=12).contains(&self.month)
82            && (1..=days_in_month(self.year, self.month)).contains(&self.day)
83    }
84    /// Today in the user's time zone.
85    pub fn today() -> Date {
86        crate::core::today()
87    }
88    /// The date of a Unix timestamp in UTC (the fallback for backends that cannot tell the local date).
89    pub(crate) fn from_unix_utc(secs: i64) -> Date {
90        // Howard Hinnant's civil-from-days
91        let z = secs.div_euclid(86_400) + 719_468;
92        let era = z.div_euclid(146_097);
93        let doe = z.rem_euclid(146_097);
94        let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
95        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
96        let mp = (5 * doy + 2) / 153;
97        let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
98        let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
99        let year = (yoe + era * 400 + i64::from(month <= 2)) as i32;
100        Date { year: year.clamp(1753, 9999), month, day }
101    }
102}
103
104/// How many days `month` of `year` has (0 for a month outside 1..=12).
105pub(crate) fn days_in_month(year: i32, month: u32) -> u32 {
106    match month {
107        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
108        4 | 6 | 9 | 11 => 30,
109        2 if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 => 29,
110        2 => 28,
111        _ => 0,
112    }
113}
114
115/// Errors. Constructors never return these (they yield a dead handle and record the error,
116/// see [`crate::last_error`]); fallible entry points such as `App::new` do.
117#[derive(Clone, PartialEq, Eq, Debug)]
118#[non_exhaustive]
119pub enum Error {
120    /// The platform backend does not implement this (or is a stub).
121    Unsupported,
122    /// `App::new` was already called on this thread.
123    AlreadyInitialized,
124    /// `App::new` has not been called on this thread (or wrong thread).
125    NotInitialized,
126    /// Stale or wrongly-typed id / parent.
127    InvalidHandle,
128    /// A built-in limit was hit, e.g. widgets nested deeper than [`crate::MAX_NESTING`].
129    LimitExceeded,
130    /// Backend-specific failure message.
131    Backend(String),
132}
133
134impl fmt::Display for Error {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        match self {
137            Error::Unsupported => write!(f, "not supported by this backend"),
138            Error::AlreadyInitialized => write!(f, "rungui already initialized on this thread"),
139            Error::NotInitialized => write!(f, "rungui not initialized on this thread"),
140            Error::InvalidHandle => write!(f, "invalid or stale widget handle"),
141            Error::LimitExceeded => write!(f, "widget nesting limit exceeded"),
142            Error::Backend(s) => write!(f, "backend error: {s}"),
143        }
144    }
145}
146impl std::error::Error for Error {}
147/// `std::result::Result` with this crate's [`Error`].
148pub type Result<T> = std::result::Result<T, Error>;
149
150/// Raw native object, for users who want to write platform-specific code.
151/// The payload is the pointer value (GtkWidget*, HWND/HMENU, NSView*/NSWindow*/NSMenu*...).
152#[derive(Copy, Clone, PartialEq, Eq, Debug)]
153#[non_exhaustive]
154pub enum NativeHandle {
155    /// A `GtkWidget*` (or `GtkMenuItem*` for menus).
156    Gtk(usize),
157    /// An `HWND` (or `HMENU` for menus).
158    Win32(usize),
159    /// An `NSView*`, `NSWindow*` or `NSMenu*`.
160    Cocoa(usize),
161}
162
163impl NativeHandle {
164    /// The raw pointer value.
165    pub fn ptr(self) -> usize {
166        match self {
167            NativeHandle::Gtk(p) | NativeHandle::Win32(p) | NativeHandle::Cocoa(p) => p,
168        }
169    }
170}
171
172/// Cross-axis alignment of a child inside its stack/grid cell.
173#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
174pub enum Align {
175    /// Place at the start (left, or top) of the cell.
176    Start,
177    /// Center in the cell.
178    Center,
179    /// Place at the end (right, or bottom) of the cell.
180    End,
181    #[default]
182    /// Stretch to fill the cell (the default).
183    Fill,
184}
185
186/// Straight (non-premultiplied) RGBA8 pixels, row-major, `rgba.len() == w*h*4`.
187#[derive(Clone, PartialEq, Eq, Debug, Default)]
188pub struct ImageData {
189    /// Width in pixels.
190    pub w: u32,
191    /// Height in pixels.
192    pub h: u32,
193    /// `w * h * 4` bytes: red, green, blue, alpha per pixel.
194    pub rgba: Vec<u8>,
195}
196
197/// Largest image edge accepted, in pixels. Keeps `w * h * 4` far from overflow on every target and
198/// well inside what the toolkits can allocate.
199pub const MAX_IMAGE_EDGE: u32 = 1 << 15;
200
201impl ImageData {
202    /// Is the pixel buffer exactly `w * h * 4` bytes, with both edges in `1..=MAX_IMAGE_EDGE`?
203    /// Invalid images are shown as "no image" by every backend.
204    pub fn is_valid(&self) -> bool {
205        (1..=MAX_IMAGE_EDGE).contains(&self.w)
206            && (1..=MAX_IMAGE_EDGE).contains(&self.h)
207            && self.rgba.len() as u64 == u64::from(self.w) * u64::from(self.h) * 4
208    }
209}
210
211#[derive(Copy, Clone, PartialEq, Eq, Debug)]
212#[non_exhaustive]
213/// Which icon a message box shows.
214pub enum MessageKind {
215    /// Information.
216    Info,
217    /// Warning.
218    Warning,
219    /// Error.
220    Error,
221    /// A question.
222    Question,
223}
224
225#[derive(Copy, Clone, PartialEq, Eq, Debug)]
226#[non_exhaustive]
227/// Which buttons a message box offers.
228pub enum Buttons {
229    /// Just "OK".
230    Ok,
231    /// "OK" and "Cancel".
232    OkCancel,
233    /// "Yes" and "No".
234    YesNo,
235    /// "Yes", "No" and "Cancel".
236    YesNoCancel,
237}
238
239#[derive(Copy, Clone, PartialEq, Eq, Debug)]
240#[non_exhaustive]
241/// The button a message box was answered with.
242pub enum Answer {
243    /// "OK".
244    Ok,
245    /// "Cancel" (also what closing the box counts as when it has one).
246    Cancel,
247    /// "Yes".
248    Yes,
249    /// "No".
250    No,
251}
252
253#[derive(Copy, Clone, PartialEq, Eq, Debug)]
254/// What a file dialog is for.
255pub enum FileMode {
256    /// Choose one existing file.
257    Open,
258    /// Choose several existing files.
259    OpenMany,
260    /// Choose where to save.
261    Save,
262    /// Choose a directory.
263    PickFolder,
264}
265
266/// A modal message box request (title/text are UTF-8).
267#[derive(Clone, Debug)]
268pub struct MessageSpec {
269    /// Which icon to show.
270    pub kind: MessageKind,
271    /// Which buttons to offer.
272    pub buttons: Buttons,
273    /// Window title.
274    pub title: String,
275    /// Message text.
276    pub text: String,
277}
278
279/// A modal file dialog request. `filters` are (label, extensions without dot); empty = all files.
280#[derive(Clone, Debug)]
281pub struct FileSpec {
282    /// What the dialog is for.
283    pub mode: FileMode,
284    /// Dialog title.
285    pub title: String,
286    /// (label, extensions) pairs; empty means all files.
287    pub filters: Vec<(String, Vec<String>)>,
288    /// Directory to start in.
289    pub initial_dir: Option<String>,
290    /// Suggested file name.
291    pub initial_name: Option<String>,
292}
293
294/// Parsed keyboard accelerator such as "Ctrl+Shift+S". `ctrl` means the platform's primary
295/// modifier (Command on macOS). `key` is an upper-case char or a named key ("F5", "Enter",
296/// "Esc", "Del", "Tab", "Space", "Left", ...).
297#[derive(Clone, PartialEq, Eq, Debug, Default)]
298pub struct Accel {
299    /// The platform's primary modifier (Command on macOS).
300    pub ctrl: bool,
301    /// Shift.
302    pub shift: bool,
303    /// Alt (Option on macOS).
304    pub alt: bool,
305    /// The key: an upper-case character or a name such as "F5" or "ENTER".
306    pub key: String,
307}
308
309impl Accel {
310    /// Parse "Ctrl+Shift+S", "Alt+F4", "F5", "Cmd+Q" (Cmd/Meta/Super count as Ctrl). `None` if empty.
311    pub fn parse(s: &str) -> Option<Accel> {
312        let mut a = Accel::default();
313        for part in s.split('+').map(str::trim).filter(|p| !p.is_empty()) {
314            match part.to_ascii_lowercase().as_str() {
315                "ctrl" | "control" | "cmd" | "command" | "meta" | "super" => a.ctrl = true,
316                "shift" => a.shift = true,
317                "alt" | "option" | "opt" => a.alt = true,
318                _ => a.key = part.to_uppercase(),
319            }
320        }
321        if a.key.is_empty() { None } else { Some(a) }
322    }
323}
324
325/// Horizontal text alignment of a [`Column`].
326#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
327pub enum ColumnAlign {
328    #[default]
329    /// Left aligned (the default).
330    Left,
331    /// Centered.
332    Center,
333    /// Right aligned.
334    Right,
335}
336
337/// One column of a table. `width` is in logical pixels (initial width; the user may resize).
338#[derive(Clone, PartialEq, Eq, Debug)]
339pub struct Column {
340    /// Header text.
341    pub title: String,
342    /// Initial width in logical pixels.
343    pub width: i32,
344    /// Alignment of the cells.
345    pub align: ColumnAlign,
346    /// Header click emits `Event::ColumnClicked` (headers of non-sortable columns may still be
347    /// clickable natively; the core forwards the event either way).
348    pub sortable: bool,
349}
350
351impl Column {
352    /// A left-aligned, 100 pixel wide, unsortable column with this header.
353    pub fn new(title: &str) -> Column {
354        Column {
355            title: title.to_string(),
356            width: 100,
357            align: ColumnAlign::Left,
358            sortable: false,
359        }
360    }
361    /// Initial width in logical pixels, clamped to `1..=32767`.
362    pub fn width(mut self, w: i32) -> Self {
363        self.width = w.clamp(1, MAX_PX);
364        self
365    }
366    /// Set the alignment of the cells.
367    pub fn align(mut self, a: ColumnAlign) -> Self {
368        self.align = a;
369        self
370    }
371    /// Say whether clicking the header reports `on_column_click`.
372    pub fn sortable(mut self, s: bool) -> Self {
373        self.sortable = s;
374        self
375    }
376}
377
378/// Handle to a node of a [`crate::Tree`]. Globally unique, never reused; `0` is the dead id
379/// returned when an insertion failed.
380#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
381pub struct TreeNodeId(pub u64);
382
383/// One flattened tree row as sent to the backend in `Prop::TreeRows`.
384#[derive(Clone, PartialEq, Eq, Debug)]
385pub struct TreeRow {
386    /// Opaque node id (`TreeNodeId.0`); echoed back in tree events.
387    pub node: u64,
388    /// 0 for roots.
389    pub depth: u32,
390    /// The node's text.
391    pub text: String,
392    /// Whether the node is expanded.
393    pub expanded: bool,
394    /// True if the node has children OR is flagged as lazily loadable (show an expander).
395    pub has_children: bool,
396}
397
398/// Direction of a [`crate::Splitter`]: `Horizontal` puts the panes side by side (left | right,
399/// mirrored under RTL) with a vertical sash between them; `Vertical` stacks them (top / bottom).
400#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
401pub enum Orientation {
402    #[default]
403    /// Panes side by side (left | right), separated by a vertical sash.
404    Horizontal,
405    /// Panes stacked (top / bottom), separated by a horizontal sash.
406    Vertical,
407}