Skip to main content

rpfm_lib/files/uic/
mod.rs

1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! UI Component (UIC) files for Total War games.
12//!
13//! UIC files define the layout, appearance, and behaviour of UI elements in the game.
14//! They contain hierarchical component definitions with states, images, animations,
15//! and callback bindings.
16//!
17//! # Format History
18//!
19//! - **Pre-Three Kingdoms**: Binary format (not yet implemented)
20//! - **Three Kingdoms onwards**: XML format (partially implemented)
21//!
22//! # Status
23//!
24//! **This module is incomplete and experimental.** Only XML parsing for version 138
25//! is partially implemented. Binary format support is not yet available.
26
27use serde_derive::{Serialize, Deserialize};
28
29use std::collections::HashMap;
30use std::io::SeekFrom;
31
32use crate::binary::{ReadBytes, WriteBytes};
33use crate::error::Result;
34use crate::files::{DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable};
35
36pub use crate::files::detection::uic::{BASE_PATH, EXTENSIONS};
37
38mod xml;
39
40//#[cfg(test)] mod uic_test;
41
42//---------------------------------------------------------------------------//
43//                              Enum & Structs
44//---------------------------------------------------------------------------//
45
46/// In-memory representation of a decoded UI Component file.
47///
48/// Contains the complete UI component definition including its hierarchy,
49/// component definitions, and metadata.
50///
51/// # Fields
52///
53/// * `version` - Format version number.
54/// * `source_is_xml` - `true` if decoded from XML format, `false` if binary.
55/// * `comment` - Optional comment/description for the component.
56/// * `precache_condition` - Condition for precaching this component.
57/// * `hierarchy` - Tree structure of UI element relationships.
58/// * `components` - Map of component IDs to their definitions.
59#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
60pub struct UIC {
61    version: u32,
62    source_is_xml: bool,
63    comment: String,
64    precache_condition: String,
65    hierarchy: HashMap<String, HierarchyItem>,
66    components: HashMap<String, Component>,
67}
68
69/// A node in the UI component hierarchy tree.
70#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
71pub struct HierarchyItem {
72    /// Unique identifier for this hierarchy node.
73    this: String,
74    /// Child nodes in the hierarchy.
75    childs: HashMap<String, HierarchyItem>,
76}
77
78/// A UI component definition with all its properties and sub-elements.
79#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
80pub struct Component {
81    /// Unique identifier for this component.
82    this: String,
83    /// Human-readable component ID.
84    id: String,
85    /// Whether horizontal resizing is allowed.
86    allowhorizontalresize: Option<bool>,
87    /// Rendering priority.
88    priority: Option<u8>,
89    /// Whether tooltips should be localised.
90    tooltipslocalised: Option<bool>,
91    /// Globally unique identifier (typically same as `this`).
92    uniqueguid: String,
93    /// Whether to update this component when not visible.
94    update_when_not_visible: Option<bool>,
95    /// GUID of the current visual state.
96    current_state: Option<String>,
97    /// GUID of the default visual state.
98    default_state: Option<String>,
99
100    /// Event callbacks with context bindings.
101    callbackwithcontextlist: Option<HashMap<String, CallbackWithContext>>,
102    /// Image resources used by this component.
103    componentimages: Option<HashMap<String, ComponentImage>>,
104    /// Visual states (e.g., normal, hover, pressed).
105    states: Option<HashMap<String, State>>,
106    /// Animation definitions.
107    animations: Option<HashMap<String, Animation>>,
108    /// Layout engine configuration.
109    layout_engine: Option<LayoutEngine>,
110}
111
112/// An event callback binding with optional context.
113#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
114pub struct CallbackWithContext {
115    /// Identifier of the callback function.
116    callback_id: String,
117    /// Optional context object for the callback.
118    context_object_id: Option<String>,
119    /// Optional context function for the callback.
120    context_function_id: Option<String>,
121    /// User-defined properties for this callback.
122    child_m_user_properties: Option<HashMap<String, Property>>,
123}
124
125/// A key-value property pair.
126#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
127pub struct Property {
128    /// Property name.
129    name: String,
130    /// Property value.
131    value: String,
132}
133
134/// An image resource reference for a UI component.
135#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
136pub struct ComponentImage {
137    /// Unique identifier for this image reference.
138    this: String,
139    /// Globally unique identifier.
140    uniqueguid: String,
141    /// Path to the image file.
142    imagepath: Option<String>,
143}
144
145/// A visual state definition for a UI component.
146///
147/// States define how a component appears under different conditions
148/// (e.g., normal, hovered, pressed, disabled).
149#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
150pub struct State {
151    /// Unique identifier for this state.
152    this: String,
153    /// Human-readable state name.
154    name: String,
155    /// Component width in this state.
156    width: Option<u32>,
157    /// Text content to display.
158    text: Option<String>,
159    /// Horizontal text alignment.
160    text_h_align: Option<String>,
161    /// Vertical text offset.
162    text_y_offset: Option<String>,
163    /// Horizontal text behaviour.
164    text_h_behaviour: Option<String>,
165    /// Whether the text should be localised.
166    text_localised: Option<bool>,
167    /// Localisation key for the text.
168    text_label: Option<String>,
169    /// Font family name.
170    font_m_font_name: Option<String>,
171    /// Font size.
172    font_m_size: Option<u8>,
173    /// Font colour (hex format).
174    font_m_colour: Option<String>,
175    /// Line spacing (leading).
176    font_m_leading: Option<u8>,
177    /// Font category name.
178    fontcat_name: Option<String>,
179    /// Whether this state is interactive.
180    interactive: Option<bool>,
181    /// Globally unique identifier (typically same as `this`).
182    uniqueguid: String,
183    /// Image metrics for this state.
184    imagemetrics: Option<HashMap<String, Image>>,
185}
186
187/// Image display properties within a UI state.
188#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
189pub struct Image {
190    /// Unique identifier for this image instance.
191    this: String,
192    /// Globally unique identifier.
193    uniqueguid: String,
194    /// Reference to a ComponentImage.
195    componentimage: String,
196    /// Position offset.
197    offset: Option<String>,
198    /// Colour tint (hex format).
199    colour: Option<String>,
200    /// Docking anchor point.
201    dockpoint: Option<String>,
202    /// Offset from dock point.
203    dock_offset: Option<String>,
204    /// Whether height can be resized.
205    canresizeheight: Option<bool>,
206    /// Whether width can be resized.
207    canresizewidth: Option<bool>,
208    /// Colour preset key reference.
209    ui_colour_preset_type_key: Option<String>,
210}
211
212/// An animation definition with keyframes.
213#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
214pub struct Animation {
215    /// Animation identifier.
216    id: String,
217    /// Keyframes in this animation.
218    frames: Vec<Frame>,
219}
220
221/// A single keyframe in an animation.
222#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
223pub struct Frame {
224    /// Time to interpolate to this frame (milliseconds).
225    interpolationtime: Option<u32>,
226    /// Bitmask of properties to interpolate.
227    interpolationpropertymask: Option<u8>,
228    /// Target height at this keyframe.
229    targetmetrics_m_height: Option<i32>,
230    /// Target width at this keyframe.
231    targetmetrics_m_width: Option<i32>
232}
233
234/// Layout engine configuration for arranging child components.
235#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
236pub struct LayoutEngine {
237    /// Layout type (e.g., "horizontal", "vertical", "grid").
238    r#type: String,
239    /// Spacing between child elements.
240    spacing: String,
241    /// Whether to resize to fit content.
242    sizetocontent: bool,
243    /// Margin values.
244    margins: String,
245    /// Fixed column widths for grid layouts.
246    columnwidths: Vec<i32>,
247}
248
249//---------------------------------------------------------------------------//
250//                           Implementation of Text
251//---------------------------------------------------------------------------//
252
253impl Decodeable for UIC {
254
255    fn decode<R: ReadBytes>(data: &mut R, extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
256        let mut data_local = vec![];
257        let read = data.read_to_end(&mut data_local)?;
258        data.seek(SeekFrom::Current(-(read as i64)))?;
259
260        // TODO: Unhardcode this version.
261        if content_inspector::inspect(&data_local).is_text() {
262            Ok(Self::from(xml::v138::XmlLayout::decode(data, extra_data)?))
263        } else {
264            todo!()
265        }
266    }
267}
268
269impl Encodeable for UIC {
270
271    fn encode<W: WriteBytes>(&mut self, _buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
272        if self.source_is_xml {
273            //xml::v138::XmlLayout::encode(&mut self, buffer, extra_data)
274            todo!()
275        } else {
276            todo!()
277        }
278    }
279}