Skip to main content

walkit/runtime/
build.rs

1// SPDX-License-Identifier: GPL-3.0-or-later
2
3//! Loading a skin: its XML with every include expanded, the definitions it collects, and the
4//! objects it builds from containers, layouts and groupdefs.
5
6use std::collections::{HashMap, HashSet};
7use std::rc::Rc;
8
9use super::{SkinRuntime, MAX_INCLUDE_DEPTH, MAX_NODES, MAX_OBJECTS, MAX_XML_DEPTH, PLAYLIST_GUID};
10use crate::draw::{BitmapDef, BitmapFontDef, FontDef, Gamma};
11use crate::files::BASE_PREFIX;
12use crate::gui::{
13    to_int_lenient, AnimData, Behavior, BucketData, ButtonData, ButtonKind, EqVisData, FrameData,
14    GradientData, GridData, ImagesData, Kind, LayerData, LayoutData, LayoutStatusData, MenuData,
15    Obj, ObjId, PlaylistData, ProgressData, RectData, SliderData, StatusData, ThemeListData,
16    XFadeData,
17};
18use crate::maki::{Handle, SystemObject};
19use crate::text::TextData;
20use crate::xml::{self, XmlNode};
21
22/// Everything a groupdef holds, and its attributes that are no params of the group.
23const ALL_CONTENT: [&str; 3] = ["params", "xui", "scripts"];
24const DEF_ATTRS: [&str; 7] = [
25    "id",
26    "xuitag",
27    "inherit_group",
28    "inherit_content",
29    "inherit_params",
30    "behavior",
31    "contentrect",
32];
33const FILE_NODES: [&str; 4] = ["bitmap", "bitmapfont", "truetypefont", "script"];
34const GUI_ATTRS: [&str; 20] = [
35    "id",
36    "x",
37    "y",
38    "w",
39    "h",
40    "relatx",
41    "relaty",
42    "relatw",
43    "relath",
44    "visible",
45    "alpha",
46    "ghost",
47    "sysregion",
48    "tooltip",
49    "fitparent",
50    "background",
51    "drawbackground",
52    "instance_id",
53    "instanceid",
54    "name",
55];
56const KNOWN_CLASSES: [(&str, &str); 18] = [
57    ("grid", "GuiObject"),
58    ("progressgrid", "GuiObject"),
59    ("rect", "GuiObject"),
60    ("albumart", "AlbumArtLayer"),
61    ("layoutstatus", "LayoutStatus"),
62    ("menu", "Menu"),
63    ("browser", "Browser"),
64    ("edit", "Edit"),
65    ("checkbox", "CheckBox"),
66    ("dropdownlist", "DropDownList"),
67    ("guilist", "GuiList"),
68    ("guitree", "GuiTree"),
69    ("tabsheet", "TabSheet"),
70    ("wasabi:tabsheet", "TabSheet"),
71    ("playlisteditor", "GuiObject"),
72    ("wasabi:titlebar", "GuiObject"),
73    ("mouseredir", "MouseRedir"),
74    ("images", "GuiObject"),
75];
76
77/// Whether an object made from `tag` with no definition stands in for something the skin lacks:
78/// a namespaced tag, or one no known class has. A known class the engine does not draw is not.
79pub(crate) fn is_undefined_tag(tag: &str) -> bool {
80    tag.contains(':') || !KNOWN_CLASSES.iter().any(|(t, _)| *t == tag)
81}
82
83/// `<sendparams>`, `<hideobject>` and `<showobject>` met while a group fills, with how many
84/// children the group had then.
85type Meta = Vec<(Rc<XmlNode>, usize)>;
86
87fn node_key(n: &Rc<XmlNode>) -> usize {
88    Rc::as_ptr(n) as usize
89}
90
91fn dir_of(path: &str) -> String {
92    path.rsplit_once('/')
93        .map(|(d, _)| d.to_string())
94        .unwrap_or_default()
95}
96
97fn utf8(bytes: &[u8]) -> String {
98    String::from_utf8_lossy(bytes).into_owned()
99}
100
101impl SkinRuntime {
102    /// Loads `skin.xml` and everything it includes, builds the windows and starts the scripts.
103    pub fn load(&mut self) {
104        // Winamp's wasabi base first, when the app has it (files under wasabi-base/): a
105        // skin's definitions then override it, as they do in Winamp
106        if let Some(base_xml) = self.files.read(&format!("{BASE_PREFIX}wasabi.xml")) {
107            let base_nodes = self.expand(
108                xml::parse(&utf8(&base_xml)),
109                BASE_PREFIX.trim_end_matches('/'),
110                &[],
111                0,
112            );
113            self.collecting_base = true;
114            for node in base_nodes {
115                let prefixed = prefix_files(&node, BASE_PREFIX);
116                self.collect_defs(&prefixed);
117            }
118            self.collecting_base = false;
119        }
120        // a classic skin's windows are generated around its bitmaps
121        if crate::classic::is_classic(&*self.files) {
122            self.classic_skin = true;
123            let inner =
124                std::mem::replace(&mut self.files, Box::new(crate::files::MemoryFiles::new()));
125            self.files = Box::new(crate::classic::ClassicFiles::new(inner));
126            self.classic_sheets = Rc::new(crate::classic::Sheets::of(&*self.files));
127            if let Some(text) = self.files.read("region.txt") {
128                self.classic_regions = crate::classic::region::parse(&utf8(&text));
129            }
130            if let Some(text) = self.files.read("pledit.txt") {
131                self.classic_pledit = crate::classic::pledit::parse(&utf8(&text));
132            }
133            self.measure_classic_row();
134            if let Some(text) = self.files.read("viscolor.txt") {
135                self.classic_palette = crate::classic::viscolor::parse(&utf8(&text));
136            }
137        }
138        let root_text = self
139            .files
140            .read("skin.xml")
141            .map(|b| utf8(&b))
142            .expect("no skin.xml");
143        let root = xml::parse(&root_text);
144        if let Some(v) = root
145            .iter()
146            .find(|n| n.name == "winampabstractionlayer" || n.name == "wasabixml")
147            .and_then(|n| n.get("version"))
148            .and_then(|v| crate::maki::value::parse_double(v.trim()))
149        {
150            self.wal_version = v;
151        }
152        let expanded = self.expand(root, "", &[], 0);
153        for node in &expanded {
154            self.collect_defs(node);
155        }
156        for node in &expanded {
157            self.build_top(node, None);
158        }
159        self.do_layout();
160        // the main window where the phone draws it, before a script reads its place
161        for c in 0..self.containers.len() {
162            self.fit_viewport(c);
163        }
164        self.scripts_started = true;
165        for s in 0..self.systems.len() {
166            self.start_script(s);
167        }
168        for c in 0..self.containers.len() {
169            if let Some(l) = self.containers[c].current {
170                self.dispatch(crate::maki::Handle::Gui(l), "onstartup", &[]);
171            }
172        }
173        // a bucket's script picks its first entry from here (Winamp Modern's options menu)
174        self.start_buckets();
175        // the layouts on screen hear that they are, once every script runs
176        for c in 0..self.containers.len() {
177            if self.containers[c].visible {
178                if let Some(l) = self.containers[c].current {
179                    self.announce_visible(l, true);
180                }
181            }
182        }
183        self.ensure_layout();
184        for o in 0..self.objects.len() {
185            if matches!(self.objects[o].kind, Kind::AnimatedLayer(..)) {
186                self.anim_start_if_auto(o);
187            }
188        }
189        // the main window has the focus from the start, so the first press moves no focus
190        if self.focused.is_none() {
191            self.focused = self.main_layout();
192        }
193        self.relayout();
194    }
195
196    /// Winamp's placeholders in attribute values: `@HAVE_LIBRARY@` is "1" when the Media
197    /// Library is there, `@SKINSPATH@` the skins folder (resolved by the files).
198    fn substituted(&self, attrs: &[(String, String)]) -> Vec<(String, String)> {
199        if !attrs.iter().any(|(_, v)| v.contains("@HAVE_")) {
200            return attrs.to_vec();
201        }
202        attrs
203            .iter()
204            .map(|(k, v)| {
205                (
206                    k.clone(),
207                    v.replace("@HAVE_LIBRARY@", if self.have_library { "1" } else { "0" })
208                        .replace("@HAVE_VIDEO@", "1"),
209                )
210            })
211            .collect()
212    }
213
214    /// Replaces every `<include>` by the nodes of the file it names, relative to the including
215    /// file. A file that includes itself (directly or round about), includes nested past the
216    /// limit and anything past the node limit are left out.
217    fn expand(
218        &mut self,
219        nodes: Vec<Rc<XmlNode>>,
220        dir: &str,
221        chain: &[String],
222        depth: usize,
223    ) -> Vec<Rc<XmlNode>> {
224        let mut out = Vec::new();
225        for n in nodes {
226            self.expanded_nodes += 1;
227            if self.expanded_nodes > MAX_NODES || depth > MAX_XML_DEPTH {
228                if self.expanded_nodes == MAX_NODES + 1 {
229                    self.host
230                        .log(&format!("skin too large: stopped at {MAX_NODES} nodes"));
231                }
232                continue;
233            }
234            if n.name == "include" {
235                let Some(file) = n.get("file") else { continue };
236                let file = file.replace('\\', "/");
237                let file = file
238                    .strip_prefix("@DEFAULTSKINPATH@")
239                    .unwrap_or(&file)
240                    .to_string();
241                let candidates = [
242                    if dir.is_empty() {
243                        file.clone()
244                    } else {
245                        format!("{dir}/{file}")
246                    },
247                    file.clone(),
248                ];
249                let path = candidates.iter().find(|p| self.files.exists(p)).cloned();
250                match path {
251                    None => self
252                        .host
253                        .log(&format!("include not found: {file} (from {dir})")),
254                    Some(path) if chain.contains(&path) || chain.len() >= MAX_INCLUDE_DEPTH => {
255                        self.host.log(&format!(
256                            "include skipped: {file} (includes itself or nests too deep)"
257                        ));
258                    }
259                    Some(path) => {
260                        let text = utf8(&self.files.read(&path).expect("exists"));
261                        let mut next = chain.to_vec();
262                        next.push(path.clone());
263                        out.extend(self.expand(
264                            xml::parse(&text),
265                            &dir_of(&path),
266                            &next,
267                            depth + 1,
268                        ));
269                    }
270                }
271            } else {
272                let children = self.expand(n.children.clone(), dir, chain, depth + 1);
273                out.push(Rc::new(XmlNode {
274                    name: n.name.clone(),
275                    attrs: self.substituted(&n.attrs),
276                    children,
277                    text: n.text.clone(),
278                }));
279            }
280        }
281        out
282    }
283
284    fn collect_defs(&mut self, node: &Rc<XmlNode>) {
285        match node.name.as_str() {
286            "bitmap" => {
287                if let (Some(id), Some(given)) = (node.get("id"), node.get("file")) {
288                    // a picture Winamp makes itself: a made-up name the hosts' files answer
289                    let file = if given
290                        .rsplit('/')
291                        .next()
292                        .is_some_and(|n| n.eq_ignore_ascii_case("$solid"))
293                    {
294                        crate::generated::solid_name(
295                            node.get("w").and_then(to_int_lenient),
296                            node.get("h").and_then(to_int_lenient),
297                            node.get("color"),
298                            node.get("alpha").and_then(to_int_lenient),
299                        )
300                    } else {
301                        given.to_string()
302                    };
303                    let key = id.to_lowercase();
304                    // a picture defined under an old name (studio.button.upperLeft) is the
305                    // picture its alias names from then on, as a later definition of that name
306                    // would be: MMD3 defines both, and Winamp draws its buttons with the old ones
307                    let names: Vec<String> = std::iter::once(key.clone())
308                        .chain(self.aliases.get(&key).cloned())
309                        .collect();
310                    for key in names {
311                        if self.collecting_base {
312                            self.base_bitmaps.insert(key.clone());
313                        } else {
314                            self.base_bitmaps.remove(&key);
315                        }
316                        let def = BitmapDef::new(
317                            &key,
318                            &file,
319                            node.get("x").and_then(to_int_lenient).unwrap_or(0),
320                            node.get("y").and_then(to_int_lenient).unwrap_or(0),
321                            node.get("w").and_then(to_int_lenient),
322                            node.get("h").and_then(to_int_lenient),
323                            node.get("gammagroup").map(|g| g.to_lowercase()).as_deref(),
324                        );
325                        self.bitmaps.insert(key, def);
326                    }
327                    self.bitmap_lookups.clear();
328                }
329            }
330            "bitmapfont" => {
331                if let (Some(id), Some(file)) = (node.get("id"), node.get("file")) {
332                    let key = id.to_lowercase();
333                    self.bitmap_fonts.insert(
334                        key.clone(),
335                        BitmapFontDef {
336                            id: Rc::from(key.as_str()),
337                            file: Rc::from(file),
338                            char_width: node.get("charwidth").and_then(to_int_lenient).unwrap_or(5),
339                            char_height: node
340                                .get("charheight")
341                                .and_then(to_int_lenient)
342                                .unwrap_or(6),
343                            h_spacing: node.get("hspacing").and_then(to_int_lenient).unwrap_or(0),
344                            v_spacing: node.get("vspacing").and_then(to_int_lenient).unwrap_or(0),
345                            ox: 0,
346                            oy: 0,
347                            gamma_group: node
348                                .get("gammagroup")
349                                .map(|g| Rc::from(g.to_lowercase().as_str())),
350                        },
351                    );
352                    self.resolved_fonts.remove(&key);
353                }
354            }
355            "truetypefont" => {
356                if let (Some(id), Some(file)) = (node.get("id"), node.get("file")) {
357                    let key = id.to_lowercase();
358                    self.fonts.insert(key.clone(), FontDef::new(&key, file));
359                }
360            }
361            "color" => {
362                if let Some(id) = node.get("id") {
363                    let key = id.to_lowercase();
364                    if self.collecting_base {
365                        self.base_colors.insert(key.clone());
366                    } else {
367                        self.base_colors.remove(&key);
368                    }
369                    if let Some(v) = node.get("value") {
370                        self.define_color(&key, v);
371                    }
372                    if let Some(g) = node.get("gammagroup") {
373                        self.color_groups.insert(key, g.to_lowercase());
374                    }
375                }
376            }
377            "gammaset" => {
378                if let Some(id) = node.get("id") {
379                    let groups: HashMap<String, Gamma> = node
380                        .children
381                        .iter()
382                        .filter(|c| c.name == "gammagroup")
383                        .map(|g| {
384                            let v: Vec<i32> = g
385                                .get("value")
386                                .unwrap_or("0,0,0")
387                                .split(',')
388                                .map(|p| p.trim().parse().unwrap_or(0))
389                                .collect();
390                            (
391                                g.get("id").unwrap_or("").to_lowercase(),
392                                Gamma {
393                                    r: v.first().copied().unwrap_or(0),
394                                    g: v.get(1).copied().unwrap_or(0),
395                                    b: v.get(2).copied().unwrap_or(0),
396                                    boost: g.get("boost").and_then(to_int_lenient).unwrap_or(0),
397                                    gray: g.get("gray").and_then(to_int_lenient).unwrap_or(0),
398                                },
399                            )
400                        })
401                        .collect();
402                    match self.gamma_sets.iter_mut().find(|(n, _)| n == id) {
403                        Some(entry) => entry.1 = groups,
404                        None => self.gamma_sets.push((id.to_string(), groups)),
405                    }
406                    if self.current_gamma_set.is_none() {
407                        self.current_gamma_set = Some(id.to_string());
408                    }
409                    self.gammas.clear();
410                }
411            }
412            "elementalias" => {
413                if let (Some(id), Some(target)) = (node.get("id"), node.get("target")) {
414                    self.aliases
415                        .insert(id.to_lowercase(), target.to_lowercase());
416                    self.bitmap_lookups.clear();
417                }
418            }
419            "groupdef" => {
420                if let Some(id) = node.get("id") {
421                    let key = id.to_lowercase();
422                    if let Some(earlier) = self.group_defs.insert(key.clone(), node.clone()) {
423                        self.earlier_defs.insert(node_key(node), earlier);
424                    }
425                    if self.collecting_base {
426                        self.base_group_defs.insert(node_key(node));
427                    }
428                    if let Some(tag) = node.get("xuitag") {
429                        self.xui_tags.insert(tag.to_lowercase(), key.clone());
430                    }
431                    if let Some(wt) = node.get("windowtype") {
432                        let list = self
433                            .window_types
434                            .entry(wt.trim().to_lowercase())
435                            .or_default();
436                        if !list.contains(&key) {
437                            list.push(key.clone());
438                        }
439                    }
440                }
441            }
442            // getSkinName() is the skin's folder name, which the host sets; <skininfo> names it only when it did not
443            "skininfo" if self.skin_name.is_empty() => {
444                if let Some(n) = node.children.iter().find(|c| c.name == "name") {
445                    self.skin_name = if n.text.is_empty() {
446                        n.get("text").unwrap_or(&self.skin_name).to_string()
447                    } else {
448                        n.text.clone()
449                    };
450                }
451            }
452            _ => {}
453        }
454        for c in &node.children {
455            self.collect_defs(c);
456        }
457    }
458
459    /// A `<color>`'s value under the lowercase id `k`. A value that is no RGB names another
460    /// color; the later definition wins in either form.
461    fn define_color(&mut self, k: &str, v: &str) {
462        if let Some(rgb) = crate::gui::parse_rgb(v) {
463            self.colors.insert(k.to_string(), rgb);
464            self.color_aliases.remove(k);
465        } else {
466            self.color_aliases.insert(k.to_string(), v.to_lowercase());
467            self.colors.remove(k);
468        }
469    }
470
471    fn build_top(&mut self, node: &Rc<XmlNode>, parent: Option<ObjId>) {
472        match node.name.as_str() {
473            "wasabixml"
474            | "winampabstractionlayer"
475            | "elements"
476            | "scripts"
477            | "skininfo"
478            | "gammaset"
479            | "accelerators" => {
480                let walk_into = node.name == "scripts"
481                    || !["elements", "skininfo", "gammaset", "accelerators"]
482                        .contains(&node.name.as_str());
483                if walk_into {
484                    for c in &node.children {
485                        self.build_top(c, parent);
486                    }
487                }
488            }
489            "container" => self.build_container(node),
490            "script" => self.attach_script(node, parent),
491            "groupdef" | "bitmap" | "bitmapfont" | "truetypefont" | "color" | "elementalias"
492            | "colorthemes:list" | "colorthemes:mgr" => {}
493            _ => self.host.log(&format!("top-level <{}> ignored", node.name)),
494        }
495    }
496
497    fn build_container(&mut self, node: &Rc<XmlNode>) {
498        let Some(id) = node.get("id").map(|s| s.to_lowercase()) else {
499            return;
500        };
501        let c = self.containers.len();
502        self.containers
503            .push(crate::gui::Container::new(&id, node.attrs.clone()));
504        for child in &node.children {
505            match child.name.as_str() {
506                "layout" => {
507                    let layout = self.new_layout(c);
508                    self.fill_group(layout, child, child.get("id"));
509                    self.containers[c].layouts.push(layout);
510                }
511                "script" => self.attach_script(child, None),
512                "scripts" => {
513                    for s in &child.children {
514                        self.attach_script(s, None);
515                    }
516                }
517                "groupdef" => {}
518                _ => self
519                    .host
520                    .log(&format!("<{}> in container {id} ignored", child.name)),
521            }
522        }
523        let layouts = self.containers[c].layouts.clone();
524        self.containers[c].current = layouts
525            .iter()
526            .copied()
527            .find(|l| self.objects[*l].base.id == "normal")
528            .or(layouts.first().copied());
529        // a new main window, for what is worked out from the windows
530        self.change_count += 1;
531    }
532
533    /// A new layout of container `c`, placed at the container's default position.
534    fn new_layout(&mut self, c: usize) -> ObjId {
535        let window_id = self.new_window_id();
536        let mut data = LayoutData::new(window_id);
537        data.container = Some(c);
538        data.view_x = self.containers[c].default_x;
539        data.view_y = self.containers[c].default_y;
540        let id = self.objects.len();
541        self.objects
542            .push(Obj::new("layout", Kind::Layout(Box::new(data)), true));
543        self.register_layout(id);
544        id
545    }
546
547    /// Applies a groupdef, its inherited chain first, then the node's attributes and children.
548    pub(crate) fn fill_group(&mut self, group: ObjId, node: &Rc<XmlNode>, def_id: Option<&str>) {
549        let mut meta: Meta = Vec::new();
550        if let Some(def_id) = def_id {
551            if let Some(def) = self.group_defs.get(&def_id.to_lowercase()).cloned() {
552                self.apply_group_def(group, &def, &ALL_CONTENT, &mut meta, &mut HashSet::new());
553            }
554        }
555        self.set_params(group, &node.attrs);
556        for c in &node.children {
557            self.build_child(c, group, &mut meta);
558        }
559        self.apply_meta(group, &meta);
560    }
561
562    /// Builds `def` into `group`, only the `want`ed parts ("params", "xui" objects, "scripts").
563    /// The base comes first: `inherit_group`, else the groupdef this one redefined. What of the
564    /// base is used is `inherit_content` ("1" all, "0" none, or a list; objects and scripts by
565    /// default with an `inherit_group`, nothing without), plus its params unless `inherit_params="0"`.
566    fn apply_group_def(
567        &mut self,
568        group: ObjId,
569        def: &Rc<XmlNode>,
570        want: &[&str],
571        meta: &mut Meta,
572        seen: &mut HashSet<usize>,
573    ) {
574        if !seen.insert(node_key(def)) {
575            return;
576        }
577        if self.base_group_defs.contains(&node_key(def)) {
578            self.base_usage.insert(format!(
579                "group:{}",
580                def.get("id").unwrap_or("").to_lowercase()
581            ));
582        }
583        if let Some(b) = behavior_of(def) {
584            if let Some(g) = self.objects[group].group.as_mut() {
585                g.behavior = Some(b);
586            }
587        }
588        let own_id = def.get("id").map(|s| s.to_lowercase());
589        let named = def
590            .get("inherit_group")
591            .map(|s| s.to_lowercase())
592            .filter(|n| Some(n) != own_id.as_ref());
593        let base = named
594            .as_ref()
595            .and_then(|n| self.group_defs.get(n).cloned())
596            .or_else(|| self.earlier_defs.get(&node_key(def)).cloned());
597        if let Some(base) = base {
598            let content: Vec<String> =
599                match def.get("inherit_content").map(|c| c.trim().to_lowercase()) {
600                    None => {
601                        if named.is_some() {
602                            vec!["xui".into(), "scripts".into()]
603                        } else {
604                            vec![]
605                        }
606                    }
607                    Some(c) if c == "1" => vec!["xui".into(), "scripts".into()],
608                    Some(c) if c == "0" => vec![],
609                    Some(c) => c.split([';', ',']).map(|s| s.trim().to_string()).collect(),
610                };
611            let mut inherited = content;
612            if def.get("inherit_params").map(|p| p.trim()) != Some("0") {
613                inherited.push("params".into());
614            }
615            let wanted: Vec<&str> = want
616                .iter()
617                .copied()
618                .filter(|w| inherited.iter().any(|i| i == w))
619                .collect();
620            self.apply_group_def(group, &base, &wanted, meta, seen);
621        }
622        if want.contains(&"params") {
623            for (k, v) in &def.attrs {
624                if !DEF_ATTRS.contains(&k.as_str()) {
625                    self.set_param(group, k, v);
626                }
627            }
628        }
629        for c in &def.children {
630            let part = if c.name == "script" { "scripts" } else { "xui" };
631            if want.contains(&part) {
632                self.build_child(c, group, meta);
633            }
634        }
635    }
636
637    fn new_object(&mut self, tag: &str, kind: Kind) -> ObjId {
638        let grouped = super::is_grouped(&kind);
639        let id = self.objects.len();
640        self.objects.push(Obj::new(tag, kind, grouped));
641        id
642    }
643
644    fn build_child(&mut self, node: &Rc<XmlNode>, parent: ObjId, meta: &mut Meta) {
645        self.built += 1;
646        if self.built > MAX_OBJECTS {
647            if self.built == MAX_OBJECTS + 1 {
648                self.host
649                    .log(&format!("skin too large: stopped at {MAX_OBJECTS} objects"));
650            }
651            return;
652        }
653        let name = node.name.as_str();
654        // Wasabi's tags (Wasabi:Button, Wasabi:Text, ...) are xui groups of the wasabi base when it
655        // defines them: a framed button inside a group, and so on
656        if name.starts_with("wasabi:") {
657            if let Some(def_id) = self.xui_tags.get(name).cloned() {
658                self.build_xui(node, parent, &def_id);
659                return;
660            }
661        }
662        let kind = match name {
663            "layer" => Kind::Layer(LayerData::default()),
664            "animatedlayer" => Kind::AnimatedLayer(LayerData::default(), AnimData::default()),
665            "button" | "wasabi:button" => Kind::Button(ButtonData::new(ButtonKind::Plain)),
666            "nstatesbutton" => Kind::Button(ButtonData::new(ButtonKind::NStates {
667                states: 2,
668                values: None,
669                cfg_attrib: None,
670                local_state: 0,
671                auto_elements: true,
672            })),
673            "togglebutton" => Kind::Button(ButtonData::new(ButtonKind::Toggle {
674                cfg_attrib: None,
675                cfg_val: 1,
676                auto_toggle: true,
677            })),
678            "text" | "wasabi:text" => Kind::Text(Box::default()),
679            // a songticker is a text that shows the song name and its length unless told otherwise
680            "songticker" => Kind::Text(Box::new(TextData::song_ticker())),
681            "slider" | "wasabi:hslider" | "wasabi:vslider" => Kind::Slider(SliderData::default()),
682            "status" => Kind::Status(StatusData::default()),
683            "grid" => Kind::Grid(GridData::default()),
684            "progressgrid" => Kind::ProgressGrid(GridData::default(), ProgressData::default()),
685            "albumart" => Kind::AlbumArt { not_found: None },
686            "rect" => Kind::RectObj(RectData::default()),
687            "images" => Kind::Images(ImagesData::default()),
688            "menu" => Kind::Menu(MenuData::default()),
689            // Winamp's playlist editor, which a skin embeds as a component, or a window
690            // holder for it (Bento): the playlist view either way
691            "component" | "windowholder" => {
692                if Self::holds(&node.attrs, PLAYLIST_GUID) {
693                    Kind::PlaylistView(PlaylistData::default())
694                } else {
695                    let g = self.new_object(name, Kind::Group);
696                    self.fill_group(g, node, node.get("id"));
697                    self.add_child(parent, g);
698                    return;
699                }
700            }
701            "wasabi:frame" | "frame" => {
702                let f = self.new_object(name, Kind::Frame(FrameData::default()));
703                self.fill_group(f, node, None);
704                self.add_child(parent, f);
705                return;
706            }
707            "componentbucket" => {
708                let b = self.new_object(name, Kind::Bucket(BucketData::default()));
709                self.fill_group(b, node, node.get("id"));
710                self.bucket_fill(b);
711                self.add_child(parent, b);
712                self.starting_buckets.push(b);
713                return;
714            }
715            "groupxfade" => {
716                let g = self.new_object(name, Kind::XFade(XFadeData::default()));
717                self.fill_group(g, node, node.get("id"));
718                self.add_child(parent, g);
719                return;
720            }
721            "group" | "cfggroup" => {
722                let g = self.new_object(name, Kind::Group);
723                self.fill_group(g, node, node.get("id"));
724                self.add_child(parent, g);
725                return;
726            }
727            "vis" => Kind::Vis(Box::default()),
728            "classicwindow" => Kind::ClassicWindow(crate::classic::ClassicWindow::Main),
729            "eqvis" => Kind::EqVis(EqVisData::default()),
730            "colorthemes:list" => Kind::ColorThemeList(ThemeListData::default()),
731            "gradient" => Kind::Gradient(GradientData::default()),
732            "layoutstatus" => {
733                let o = self.new_object(name, Kind::LayoutStatus(LayoutStatusData::default()));
734                self.set_params(o, &node.attrs);
735                self.status_field(o);
736                self.add_child(parent, o);
737                return;
738            }
739            "layout" => {
740                let pid = self.objects[parent].base.id.clone();
741                self.host.log(&format!("nested <layout> in {pid} ignored"));
742                return;
743            }
744            "script" => {
745                self.attach_script(node, Some(parent));
746                return;
747            }
748            "scripts" => {
749                for c in &node.children {
750                    self.attach_script(c, Some(parent));
751                }
752                return;
753            }
754            "sendparams" | "hideobject" | "showobject" => {
755                // with how many children the group had then: it reaches only objects made before it
756                meta.push((node.clone(), self.objects[parent].children().len()));
757                return;
758            }
759            "bitmap" | "bitmapfont" | "color" | "truetypefont" | "elementalias" | "elements"
760            | "groupdef" | "gammaset" | "snappoint" | "accelerators" | "include" => return,
761            _ => {
762                if let Some(def_id) = self.xui_tags.get(name).cloned() {
763                    self.build_xui_with_content(node, parent, &def_id);
764                    return;
765                }
766                let class_name = KNOWN_CLASSES
767                    .iter()
768                    .find(|(t, _)| *t == name)
769                    .map(|(_, c)| *c)
770                    .unwrap_or("GuiObject");
771                if is_undefined_tag(name) {
772                    self.host
773                        .log(&format!("<{name}> unknown, placed as {class_name}"));
774                }
775                Kind::Unknown {
776                    class_name: class_name.to_string(),
777                }
778            }
779        };
780        let o = self.new_object(name, kind);
781        self.set_params(o, &node.attrs);
782        self.add_child(parent, o);
783    }
784
785    /// A xui element with the group its `content` attribute names inside it, when no script of
786    /// the element runs: the standard frame scripts build the content group themselves, but
787    /// only when they run.
788    fn build_xui_with_content(&mut self, node: &Rc<XmlNode>, parent: ObjId, def_id: &str) {
789        let g = self.build_xui(node, parent, def_id);
790        let Some(content) = node.get("content") else {
791            return;
792        };
793        if !self.objects[g]
794            .group
795            .as_ref()
796            .expect("a group")
797            .system_objects
798            .is_empty()
799        {
800            return;
801        }
802        let inner = self.new_object("group", Kind::Group);
803        let spec = Rc::new(XmlNode {
804            name: "group".into(),
805            attrs: vec![
806                ("id".into(), content.to_string()),
807                ("x".into(), "0".into()),
808                ("y".into(), "0".into()),
809                ("w".into(), "0".into()),
810                ("h".into(), "0".into()),
811                ("relatw".into(), "1".into()),
812                ("relath".into(), "1".into()),
813            ],
814            children: Vec::new(),
815            text: String::new(),
816        });
817        self.fill_group(inner, &spec, Some(content));
818        self.add_child(g, inner);
819    }
820
821    /// A xui element: a group made from the definition that names `node`'s tag. Its GUI
822    /// attributes place the group; the others go to its scripts as xui parameters and to the
823    /// child the group embeds.
824    fn build_xui(&mut self, node: &Rc<XmlNode>, parent: ObjId, def_id: &str) -> ObjId {
825        let g = self.new_object(&node.name, Kind::Group);
826        let gui: Vec<(String, String)> = node
827            .attrs
828            .iter()
829            .filter(|(k, _)| GUI_ATTRS.contains(&k.as_str()) || k == "move")
830            .cloned()
831            .collect();
832        let rest: Vec<(String, String)> = node
833            .attrs
834            .iter()
835            .filter(|(k, _)| !(GUI_ATTRS.contains(&k.as_str()) || k == "move"))
836            .cloned()
837            .collect();
838        let spec = Rc::new(node.with_attrs(gui));
839        self.fill_group(g, &spec, Some(def_id));
840        for (k, v) in &rest {
841            self.objects[g]
842                .group
843                .as_mut()
844                .expect("a group")
845                .xui_params
846                .push((k.clone(), v.clone()));
847        }
848        if let Some(e) = self.embedded(g) {
849            self.set_params(e, &rest);
850        }
851        self.add_child(parent, g);
852        if !self.group_defs.contains_key(&def_id.to_lowercase()) {
853            self.host
854                .log(&format!("xui {}: no groupdef {def_id}", node.name));
855        }
856        g
857    }
858
859    /// `<hideobject>`, `<showobject>`, `<sendparams>`: applied where they stand in the XML, so
860    /// they reach the objects made before them.
861    fn apply_meta(&mut self, group: ObjId, meta: &Meta) {
862        for (m, before) in meta {
863            let Some(targets) = m.get("target") else {
864                continue;
865            };
866            let targets: Vec<String> = targets
867                .split(';')
868                .map(|t| t.trim().to_string())
869                .filter(|t| !t.is_empty())
870                .collect();
871            let existing: Vec<ObjId> = self.objects[group]
872                .children()
873                .iter()
874                .take(*before)
875                .copied()
876                .collect();
877            let scope = m
878                .get("group")
879                .and_then(|g| self.find_meta_target(&existing, g))
880                .filter(|o| self.objects[*o].group.is_some());
881            for t in targets {
882                let target = match scope {
883                    Some(s) => self.find_object(s, &t),
884                    None => self.find_meta_target(&existing, &t),
885                };
886                if let Some(target) = target {
887                    self.apply_meta_to(m, target);
888                }
889            }
890        }
891    }
892
893    /// The object `id` names among `objs`, by id or instance id, else anywhere inside one of their groups.
894    fn find_meta_target(&self, objs: &[ObjId], id: &str) -> Option<ObjId> {
895        let lower = id.to_lowercase();
896        if let Some(o) = objs.iter().copied().find(|o| {
897            let obj = &self.objects[*o];
898            obj.base.id == lower
899                || obj
900                    .group
901                    .as_ref()
902                    .is_some_and(|g| g.instance_id.as_deref() == Some(lower.as_str()))
903        }) {
904            return Some(o);
905        }
906        for o in objs {
907            if self.objects[*o].group.is_some() {
908                if let Some(f) = self.find_object(*o, &lower) {
909                    return Some(f);
910                }
911            }
912        }
913        None
914    }
915
916    fn apply_meta_to(&mut self, m: &Rc<XmlNode>, target: ObjId) {
917        match m.name.as_str() {
918            "hideobject" => self.hide_object(target),
919            "showobject" => self.show_object(target),
920            "sendparams" => {
921                for (k, v) in &m.attrs {
922                    if k != "target" && k != "group" {
923                        self.set_param(target, k, v);
924                    }
925                }
926            }
927            _ => {}
928        }
929    }
930
931    fn attach_script(&mut self, node: &Rc<XmlNode>, group: Option<ObjId>) {
932        let Some(file) = node.get("file") else { return };
933        if let Some(rest) = file.strip_prefix(BASE_PREFIX) {
934            self.base_usage.insert(format!("script:{rest}"));
935        }
936        let key = file.to_lowercase();
937        let program = if let Some(p) = self.programs.get(&key) {
938            p.clone()
939        } else {
940            let short = format!("scripts/{}", file.rsplit('/').next().unwrap_or(file));
941            let bytes = self.files.read(file).or_else(|| self.files.read(&short));
942            let program = match bytes {
943                None => {
944                    self.host.log(&format!("script not found: {file}"));
945                    None
946                }
947                // the parser reports any damaged file as an error
948                Some(bytes) => match crate::maki::parser::parse(&bytes, file) {
949                    Ok(p) => Some(Rc::new(p)),
950                    Err(e) => {
951                        self.host.log(&format!("script {file}: {e}"));
952                        None
953                    }
954                },
955            };
956            self.programs.insert(key, program.clone());
957            program
958        };
959        let Some(program) = program else { return };
960        let s = self.systems.len();
961        self.systems.push(SystemObject {
962            group,
963            param: node.get("param").unwrap_or("").to_string(),
964            script_id: file.to_string(),
965            started: false,
966        });
967        let script = crate::maki::Script::new(program, Handle::System(s), |guid| self.create(guid));
968        self.scripts.push(script);
969        if let Some(g) = group {
970            if let Some(gd) = self.objects[g].group.as_mut() {
971                gd.system_objects.push(s);
972            }
973        }
974        // a script in a group made later starts once that group has been laid out
975        if self.scripts_started {
976            self.pending_starts.push(s);
977            self.relayout();
978        }
979    }
980
981    /// `System.newGroup(id)`: a fresh instance of a groupdef, not yet in any parent.
982    pub(crate) fn instantiate_group(&mut self, id: &str) -> Option<ObjId> {
983        if !self.group_defs.contains_key(&id.to_lowercase()) {
984            return None;
985        }
986        let g = self.new_object("group", Kind::Group);
987        let spec = Rc::new(XmlNode {
988            name: "group".into(),
989            attrs: vec![("id".into(), id.to_string())],
990            children: Vec::new(),
991            text: String::new(),
992        });
993        self.fill_group(g, &spec, Some(id));
994        Some(g)
995    }
996
997    /// A status bar's field between its buttons: the skin's `wasabi.statusbar` group, else
998    /// what Winamp's own status bar group draws, the object frame; none with `bg="0"`.
999    fn status_field(&mut self, o: ObjId) {
1000        if matches!(&self.objects[o].kind, Kind::LayoutStatus(d) if !d.background) {
1001            return;
1002        }
1003        let field = self
1004            .instantiate_group("wasabi.statusbar")
1005            .or_else(|| self.instantiate_group("wasabi.objectframe.group"));
1006        if let Some(g) = field {
1007            self.add_child(o, g);
1008        }
1009    }
1010
1011    /// Scripts that have yet to start, started after a layout pass.
1012    pub(crate) fn take_pending_starts(&mut self) -> Vec<usize> {
1013        std::mem::take(&mut self.pending_starts)
1014    }
1015}
1016
1017/// What a groupdef asks for with `behavior="..."`.
1018fn behavior_of(def: &XmlNode) -> Option<Behavior> {
1019    match def.get("behavior").map(|b| b.to_lowercase()).as_deref() {
1020        Some("standardframe") => {
1021            let area: Vec<i32> = def
1022                .get("contentrect")
1023                .map(|r| {
1024                    r.split(',')
1025                        .map(|p| p.trim().parse().unwrap_or(0))
1026                        .collect()
1027                })
1028                .filter(|v: &Vec<i32>| v.len() == 4)
1029                .unwrap_or_else(|| vec![0, 0, 0, 0]);
1030            Some(Behavior::StandardFrame {
1031                area: [area[0], area[1], area[2], area[3]],
1032            })
1033        }
1034        Some("titlebar") => Some(Behavior::TitleBar {
1035            pad_left: 0,
1036            pad_right: 0,
1037        }),
1038        _ => None,
1039    }
1040}
1041
1042/// The same tree with every `file` attribute under `prefix`: the wasabi base's pictures live there.
1043fn prefix_files(node: &Rc<XmlNode>, prefix: &str) -> Rc<XmlNode> {
1044    let attrs = if FILE_NODES.contains(&node.name.as_str()) && node.has("file") {
1045        node.attrs
1046            .iter()
1047            .map(|(k, v)| {
1048                if k == "file" {
1049                    (
1050                        k.clone(),
1051                        format!("{prefix}{}", v.replace('\\', "/").trim_start_matches('/')),
1052                    )
1053                } else {
1054                    (k.clone(), v.clone())
1055                }
1056            })
1057            .collect()
1058    } else {
1059        node.attrs.clone()
1060    };
1061    Rc::new(XmlNode {
1062        name: node.name.clone(),
1063        attrs,
1064        children: node
1065            .children
1066            .iter()
1067            .map(|c| prefix_files(c, prefix))
1068            .collect(),
1069        text: node.text.clone(),
1070    })
1071}