Skip to main content

unbanished_formats/
ui.rs

1//! `UI::` resources: dialogs, element descriptions, fonts, sprite sheets and string tables.
2//!
3//! Every class level of `Serialize` is its own block and derived classes serialize their base first.
4//! Field meanings come from `ElementDescription` defaults, `Element::Element` and the per-class
5//! `ComputeSize`/`ComputeLayout` code; names marked "unknown" have not been traced to behaviour yet.
6
7mod kinds;
8mod read;
9pub use kinds::{Button, DocumentText, ElementKind, Label, LayoutItem, TableCell, Text};
10use read::read_element;
11
12mod dialogs;
13mod fonts;
14mod sprites;
15pub use dialogs::{dialog, Dialog, DialogBinding};
16pub use fonts::{font, string_table, Font};
17pub use sprites::{cursor, sprite_sheet, Cursor, Sprite, SpriteSheet};
18
19use crate::crc::type_id;
20use crate::crs::{self, Reader};
21use crate::error::{format_err, Error, Result};
22
23type Ref = Option<String>;
24
25fn refs(r: &mut Reader) -> Result<Vec<Ref>> {
26    (0..r.count()?).map(|_| r.external_ref()).collect()
27}
28
29fn strings<const N: usize>(r: &mut Reader) -> Result<[String; N]> {
30    let mut out: [String; N] = std::array::from_fn(|_| String::new());
31    for s in &mut out {
32        *s = r.string()?;
33    }
34    Ok(out)
35}
36
37fn i32s<const N: usize>(r: &mut Reader) -> Result<[i32; N]> {
38    let mut out = [0; N];
39    for v in &mut out {
40        *v = r.i32()?;
41    }
42    Ok(out)
43}
44
45/// Alignment within the space a parent offers: 0..8 = rows top/middle/bottom x columns left/centre/right.
46pub type Alignment = u32;
47
48/// The bits of an element's flags.
49pub mod flags {
50    /// The element is hidden.
51    pub const HIDDEN: u32 = 1 << 0;
52    /// The element fills the width it is given.
53    pub const FILL_WIDTH: u32 = 1 << 2;
54    /// The element fills the height it is given.
55    pub const FILL_HEIGHT: u32 = 1 << 3;
56    /// Height (0x10) / width (0x20) taken from the screen size times the UI scale.
57    pub const SCREEN_HEIGHT: u32 = 1 << 4;
58    /// The width is the screen's width times the interface scale.
59    pub const SCREEN_WIDTH: u32 = 1 << 5;
60    /// Halves the element's alpha (`Element::ComputeColor`).
61    pub const DIM: u32 = 1 << 18;
62    /// Takes the mouse (`SetFlagsOnOff(0x10000)`): a click on it is an event of its own.
63    pub const MOUSE: u32 = 1 << 16;
64    /// Disabled by the tutorial (input passes it by, like a disabled one).
65    ///
66    /// Original: `FUN_1400e7720`.
67    pub const LOCKED: u32 = 1 << 24;
68}
69
70/// Shared by every element.
71///
72/// Original: `UI::ElementDescription`, Runtime `0x180119390`.
73#[derive(Debug, Clone, Default)]
74pub struct ElementBase {
75    /// left, right, top, bottom
76    pub margins: [i32; 4],
77    /// The smallest size, in pixels.
78    pub min_size: [i32; 2],
79    /// How the element sits in the space it is given.
80    pub alignment: Alignment,
81    /// The element's flags ([`flags`]).
82    pub flags: u32,
83    /// ARGB, multiplied into everything the element draws.
84    pub color: u32,
85    // +0x3c
86    /// The mouse cursor shown over it (`Element::GetMouseCursorIndex`; an index into the game's
87    /// cursors: 0 Arrow, 1 Hand, 2 Hourglass, 3 Move, 4 Query, 5 Place). Only the StandardDialog
88    /// title bar sets one (3).
89    pub cursor: i32,
90    /// The element drawn behind it as a border.
91    pub border: Ref,
92    /// The dialog shown as the tooltip, when the tooltip is a dialog.
93    pub tooltip_dialog: Ref,
94    /// The string table the element's own strings come from.
95    pub string_table: Ref,
96    /// The tooltip text, or its key in the string table.
97    pub tooltip: String,
98}
99
100impl ElementBase {
101    fn read(r: &mut Reader) -> Result<Self> {
102        r.block(|r, _| {
103            let margins = i32s(r)?;
104            let min_size = i32s(r)?;
105            let alignment = r.u32()?;
106            let flags = r.u32()?;
107            let color = r.u32()?;
108            let cursor = r.i32()?;
109            Ok(ElementBase {
110                margins,
111                min_size,
112                alignment,
113                flags,
114                color,
115                cursor,
116                border: r.external_ref()?,
117                tooltip_dialog: r.external_ref()?,
118                string_table: r.external_ref()?,
119                tooltip: r.string()?,
120            })
121        })
122    }
123}
124
125/// An element description: its class, the fields every element has, and its class's fields.
126#[derive(Debug, Clone)]
127pub struct Element {
128    /// The element's class name, for example `ButtonDescription`.
129    pub class: &'static str,
130    /// The fields every element has.
131    pub base: ElementBase,
132    /// The class and its own fields.
133    pub kind: ElementKind,
134}
135
136impl Element {
137    /// The references of its child elements.
138    pub fn children(&self) -> &[Ref] {
139        match &self.kind {
140            ElementKind::Group { children }
141            | ElementKind::Page { children, .. }
142            | ElementKind::Radio { children, .. }
143            | ElementKind::Ribbon { children, .. } => children,
144            _ => &[],
145        }
146    }
147}
148
149/// The class names of every element description.
150pub const ELEMENT_CLASSES: &[&str] = &[
151    "GroupDescription",
152    "PageDescription",
153    "RadioDescription",
154    "RibbonDescription",
155    "BorderDescription",
156    "ImageDescription",
157    "AnimatedImageDescription",
158    "FrustumOutlineDescription",
159    "ButtonDescription",
160    "CheckDescription",
161    "ComboDescription",
162    "TextDescription",
163    "LabelDescription",
164    "ClipRegionDescription",
165    "ContainerDescription",
166    "EditDescription",
167    "GraphDescription",
168    "LayoutDescription",
169    "ListDescription",
170    "NumberEditDescription",
171    "NumberDescription",
172    "SliderDescription",
173    "SpinnerDescription",
174    "TabDescription",
175    "ProgressDescription",
176    "ScrollDescription",
177    "TableDescription",
178    "DocumentTextDescription",
179];
180
181/// Decode a resource if it is any element description.
182pub fn element(data: &[u8]) -> Result<Element> {
183    let (_, element) = crs::parse(data, |r, h| {
184        let class = ELEMENT_CLASSES
185            .iter()
186            .find(|c| type_id(c) == h.type_id)
187            .ok_or_else(|| {
188                Error::Format(format!("type id {:#010x} is not an element", h.type_id))
189            })?;
190        read_element(class, r)
191    })?;
192    Ok(element)
193}
194
195/// Whether a type id is one of the element classes.
196pub fn is_element(type_id_value: u32) -> bool {
197    ELEMENT_CLASSES.iter().any(|c| type_id(c) == type_id_value)
198}
199
200// ---------------------------------------------------------------- Dialog
201
202// ---------------------------------------------------------------- SpriteSheet, Font, StringTable
203
204fn expect<T>(data: &[u8], class: &str, read: impl FnOnce(&mut Reader) -> Result<T>) -> Result<T> {
205    let (_, value) = crs::parse(data, |r, h| {
206        if h.type_id != type_id(class) {
207            return format_err(format!(
208                "expected {class}, found type id {:#010x}",
209                h.type_id
210            ));
211        }
212        read(r)
213    })?;
214    Ok(value)
215}