diff --git a/crates/benilla-app/src/cursor.rs b/crates/benilla-app/src/cursor.rs index ba4e9e0ce..e9e1b15d5 100644 --- a/crates/benilla-app/src/cursor.rs +++ b/crates/benilla-app/src/cursor.rs @@ -78,8 +78,8 @@ fn decode_payload_cursor_rgba( assets: &mut benilla_assets::WorldAssets, path: &str, ) -> Option> { - // The dragged picture opens with the loose flag, as the cursor code's `0x449610` opens it. - let (w, h, rgba) = assets.decode_rgba(path, benilla_assets::LooseOpen::Index)?; + // The dragged picture opens as the cursor code's `0x449610` opens it: its `.blp` alone. + let (w, h, rgba) = assets.cursor_rgba(path)?; let mut out = box_downsample_32(w, h, &rgba); for a in out.iter_mut().skip(3).step_by(4) { *a = 0xFF; @@ -172,12 +172,12 @@ pub(crate) fn pointer_visibility(hidden: bool, ours: &mut bool, visible: bool) - pub(crate) struct CustomCursorName(pub(crate) String); /// Decode the custom cursor `SetCursor` checked to be 32×32, as `0x523cdb` copies its texels -/// unfiltered with their alpha; opened with the loose flag, as `0x523c86` opens it. +/// unfiltered with their alpha; opened as `0x523c86` opens it, through `0x449610`. fn decode_custom_cursor_rgba( assets: &mut benilla_assets::WorldAssets, path: &str, ) -> Option> { - let (w, h, rgba) = assets.decode_rgba(path, benilla_assets::LooseOpen::Index)?; + let (w, h, rgba) = assets.cursor_rgba(path)?; (w == 32 && h == 32).then_some(rgba) } @@ -826,7 +826,7 @@ mod tests { fn a_custom_set_cursor_shows_mode_41_with_its_path() { let mut app = App::new(); let mut script = benilla_ui::script::UiScript::new().unwrap(); - script.set_texture_size_probe(Box::new(|p| (p == "Custom\\Arrow").then_some((32, 32)))); + script.set_cursor_size_probe(Box::new(|p| (p == "Custom\\Arrow").then_some((32, 32)))); script.run(r#"SetCursor("Custom\\Arrow")"#).unwrap(); app.insert_non_send_resource(script); app.insert_resource(crate::loading_screen::LoadingScreen::default()); diff --git a/crates/benilla-app/src/ui_script/lifecycle.rs b/crates/benilla-app/src/ui_script/lifecycle.rs index 4b2402960..0efd4b88e 100644 --- a/crates/benilla-app/src/ui_script/lifecycle.rs +++ b/crates/benilla-app/src/ui_script/lifecycle.rs @@ -210,6 +210,8 @@ fn install_addon_asset_resolvers(world: &mut World, script: &mut UiScript) { let chain = assets.chain.clone(); let size_chain = chain.clone(); let size_loose = loose.clone(); + let cursor_chain = chain.clone(); + let cursor_loose = loose.clone(); let font_chain = chain.clone(); let font_loose = loose.clone(); // `SetTexture` runs per frame in the addons that set an icon every `OnUpdate`: the probe @@ -228,6 +230,12 @@ fn install_addon_asset_resolvers(world: &mut World, script: &mut UiScript) { sizes.borrow_mut().insert(path.to_string(), measured); measured })); + // `SetCursor`'s 32×32 test reads the picture the cursor code opens (`0x449610`), its `.blp` + // alone, decoded each call as `0x523c98` waits on the load. + script.set_cursor_size_probe(Box::new(move |path| { + benilla_assets::file_texture_rgba(&cursor_chain, &cursor_loose, path) + .map(|(w, h, _)| (w, h)) + })); // Existence over the same stores, in the same order, as `ui_text::engine`'s face loader, // memoised because a path's answer cannot change and an addon may call `SetFont` every frame. let seen: std::cell::RefCell> = diff --git a/crates/benilla-assets/src/world_assets/mod.rs b/crates/benilla-assets/src/world_assets/mod.rs index d4455845b..9be4b0a1e 100644 --- a/crates/benilla-assets/src/world_assets/mod.rs +++ b/crates/benilla-assets/src/world_assets/mod.rs @@ -111,8 +111,8 @@ fn decode_sprite( decode_sprite_as(chain, loose, path, open, OnRefusal::Miss) } -/// [`decode_sprite`] for a load that `TextureCreate` (`0x449d90`) makes: a `.tga` whose header -/// opens is the texture, and a decode that refuses it leaves the opaque white default +/// [`decode_sprite`] for a load that `TextureCreate` (`0x449d90`) makes: the first candidate that +/// makes a texture is the texture, whether or not its pixels decode /// ([`OnRefusal::WhiteDefault`]). fn decode_texture( chain: &Mutex, @@ -133,8 +133,9 @@ enum OnRefusal { /// white at the header's size (`0x44a2eb` into `0x448920`) and logs the reference's line /// (`0x835538`), with no next candidate. A header that makes no texture (`0x448450`, see /// [`tga_texture_size`]) fails the candidate as a missing file does, whether the pixels would - /// decode or not. A BLP candidate takes another callback (`0x44a500`), whose failure is a - /// solid green 8 by 8 texture instead. + /// decode or not. The BLP loader `0x44a310` returns the texture once the file opens + /// (`0x44a399`), and a parse or decode its callback refuses (`0x44a560`) leaves the solid + /// green texture (`0x44a50e`), with no next candidate either. WhiteDefault, } @@ -158,7 +159,6 @@ fn decode_sprite_as( }; match bytes.map(|b| decode_candidate(candidate, &b, on_refusal)) { Some(Candidate::Pixels(width, height, rgba)) => return Some((width, height, rgba)), - Some(Candidate::Nothing) => return None, Some(Candidate::Next) | None => {} } } @@ -234,7 +234,7 @@ impl SpriteProbe { let hits: Vec> = candidates.iter().map(|c| loose.find(c, open)).collect(); candidates.iter().zip(hits).any(|(candidate, hit)| { let opens = hit.is_some() || chain.lock_recover().contains(candidate); - if !opens || !candidate.ends_with(".tga") { + if !opens || !is_tga_name(candidate) { return opens; } let key = match &hit { @@ -274,16 +274,15 @@ fn source_key(file: &LooseFile) -> String { /// Whether `TextureCreate` (`0x449d90`) makes a texture of a candidate's bytes: a TGA the loader /// `0x44a140` reads needs a header that `0x448450` makes a device texture at ([`tga_texture_size`]), -/// decoded or not. A `.blp` candidate, or bytes that are a BLP under a `.tga` name, are not gated -/// here. +/// decoded or not, whatever the bytes are. A `.blp` candidate makes one once it opens. fn makes_texture(candidate: &str, bytes: &[u8]) -> bool { - !is_tga_load(candidate, bytes) || tga_texture_size(bytes).is_some() + !is_tga_name(candidate) || tga_texture_size(bytes).is_some() } -/// Whether `candidate` is read by the TGA loader: its name is `.tga` and its bytes are no BLP, which -/// the content sniff ([`decode_sprite_bytes`]) sends to the BLP decoder. -fn is_tga_load(candidate: &str, bytes: &[u8]) -> bool { - candidate.ends_with(".tga") && !bytes.starts_with(b"BLP2") +/// Whether `candidate` is read by the TGA loader: `TextureCreate` picks the loader by the +/// candidate's extension (`0x449e16`-`0x449e3d`), never by its bytes. +fn is_tga_name(candidate: &str) -> bool { + candidate.ends_with(".tga") } /// What one candidate file yields for a load. @@ -291,18 +290,23 @@ fn is_tga_load(candidate: &str, bytes: &[u8]) -> bool { enum Candidate { /// Pixels to draw. Pixels(u32, u32, Vec), - /// A texture of no size, which draws nothing and ends the search: the size gate lets a zero - /// through (`0x44849d`, `test ebx, ebx-1`). - Nothing, /// No texture: the next candidate is tried. Next, } -/// One candidate's bytes through [`decode_sprite_bytes`]. By `on_refusal`, a TGA load gates its -/// header's size first ([`makes_texture`]), decoded or not, and a refused decode of one that -/// passes leaves that size of opaque white. +/// `TextureCreate`'s solid texture, the colour `0xff00ff00` (`0x447c00`) in an 8 by 8 texture +/// (`0x44a900`), as RGBA. +fn solid_green() -> (u32, u32, Vec) { + (8, 8, [0, 0xff, 0, 0xff].repeat(64)) +} + +/// One candidate's bytes through the decoder its name picks ([`decode_by_name`]). By +/// `on_refusal`, a TGA load gates its header's size first ([`makes_texture`]), decoded or not, and +/// a refused decode of one that passes leaves that size of opaque white; a refused BLP is the +/// solid green. fn decode_candidate(candidate: &str, bytes: &[u8], on_refusal: OnRefusal) -> Candidate { - let size = if on_refusal == OnRefusal::WhiteDefault && is_tga_load(candidate, bytes) { + let texture = on_refusal == OnRefusal::WhiteDefault; + let size = if texture && is_tga_name(candidate) { match tga_texture_size(bytes) { Some(size) => Some(size), None => return Candidate::Next, @@ -310,12 +314,10 @@ fn decode_candidate(candidate: &str, bytes: &[u8], on_refusal: OnRefusal) -> Can } else { None }; - if let Ok((width, height, rgba)) = decode_sprite_bytes(bytes) { + if let Ok((width, height, rgba)) = decode_by_name(candidate, bytes) { return Candidate::Pixels(width, height, rgba); } match size { - None => Candidate::Next, - Some((0, _) | (_, 0)) => Candidate::Nothing, Some((width, height)) => { warn!("Texture {candidate} not loaded -- replaced with default."); Candidate::Pixels( @@ -324,19 +326,101 @@ fn decode_candidate(candidate: &str, bytes: &[u8], on_refusal: OnRefusal) -> Can vec![0xff; width as usize * height as usize * 4], ) } + None if texture => { + warn!("Texture failure: \"{candidate}\" -- replaced with the solid texture."); + let (width, height, rgba) = solid_green(); + Candidate::Pixels(width, height, rgba) + } + None => Candidate::Next, } } -/// Decode by content, not extension, since addon folders mislabel both ways: a `BLP2` magic is a -/// BLP, anything else goes to the TGA decoder, whose header check is the gate. -fn decode_sprite_bytes(bytes: &[u8]) -> anyhow::Result<(u32, u32, Vec)> { - if bytes.starts_with(b"BLP2") { - blp_to_rgba(bytes) - } else { +/// Decode a candidate by its name: a `.tga` through the TGA decoder, anything else through the BLP +/// one, as `TextureCreate` picks its loader (`0x449e16`-`0x449e3d`). A file whose bytes are the +/// other format is refused by the decoder its name picks. +fn decode_by_name(candidate: &str, bytes: &[u8]) -> anyhow::Result<(u32, u32, Vec)> { + if is_tga_name(candidate) { tga_to_rgba(bytes) + } else { + blp_to_rgba(bytes) } } +/// The pixels of a minimap mask, read by `open`: a `TextureCreate` load (`Minimap:SetMaskTexture` +/// at `0x4ee5e4`, the world-entry load at `0x4ed862`), so a candidate that opens and will not +/// decode is the white or green default ([`decode_texture`]), and `None` only a name that does +/// not resolve. +fn mask_rgba( + chain: &Mutex, + loose: &LooseFiles, + path: &str, + open: LooseOpen, +) -> Option<(u32, u32, Vec)> { + decode_texture(chain, loose, path, open) +} + +/// One BLP file decoded, read with the loose flag ([`LooseOpen::Index`], or the archives for a +/// `path` written with `/`): the loads that open a `.blp` by name and nothing else. +fn decode_blp_file( + chain: &Mutex, + loose: &LooseFiles, + path: &str, + name: &str, +) -> Option<(u32, u32, Vec)> { + let bytes = read_loose_or_chain(chain, loose, name, loose_open_for(path, LooseOpen::Index)); + match bytes.map(|b| blp_to_rgba(&b)) { + Some(Ok(decoded)) => Some(decoded), + Some(Err(e)) => { + warn!("texture miss: '{name}' RESOLVES but will not decode as a BLP: {e:#}"); + None + } + None => { + warn!("texture miss: '{name}' does not resolve"); + None + } + } +} + +/// The files a tabard emblem cell reads: its name with `.BLP` appended (`0x50338a`, `0x83574c`), +/// whatever it ends in, and nothing else. +fn emblem_names(path: &str) -> Vec { + vec![format!("{}.blp", normalize_path(path))] +} + +/// The pixels of a tabard emblem cell, read from the archives alone (`0x5a7b40` with flag 0) and +/// decoded as a BLP ([`emblem_names`]). +fn emblem_rgba(chain: &Mutex, path: &str) -> Option<(u32, u32, Vec)> { + let chain = chain.lock_recover(); + emblem_names(path).into_iter().find_map(|name| { + let bytes = chain.read(&name).ok()?; + decode_by_name(&name, &bytes).ok() + }) +} + +/// The pixels of a portrait: the sink `0x525d30` formats `%s.blp` onto the name as written +/// (`0x525e0f`, whatever it ends in) and reads it with the BLP reader `0x5a7b40` and flag 1 +/// (`0x525e37`), so no `.tga` is read and `Foo.tga` opens `Foo.tga.blp`. +fn portrait_rgba( + chain: &Mutex, + loose: &LooseFiles, + path: &str, +) -> Option<(u32, u32, Vec)> { + decode_blp_file(chain, loose, path, &format!("{}.blp", normalize_path(path))) +} + +/// The pixels of a picture the cursor code opens through `0x449610`: `SetCursor`'s custom cursor +/// (`0x523c86`) and the dragged icon (`0x5239f7`, `0x523a3e`, `0x523af7`, `0x523bb1`), all with the +/// loose flag. It strips a three-letter extension (`0x449590` at `0x44963c`) and appends `.blp` +/// (`0x449641`), and the bytes decode as a BLP (`0x449840`): `Foo.tga` opens `Foo.blp`, and no +/// `.tga` is read. +pub fn file_texture_rgba( + chain: &Mutex, + loose: &LooseFiles, + path: &str, +) -> Option<(u32, u32, Vec)> { + decode_blp_file(chain, loose, path, &format!("{}.blp", sprite_key(path))) +} + /// The loose files an open that sets the loose flag reads before the archive chain, as the /// reference's resolver (`0x647e60`) answers from its index of the install (`0x647f89`) before the /// chain (`0x648116`): the install's index for any path, and benilla's AddOns folder for an @@ -741,19 +825,20 @@ impl WorldAssets { handle } - /// A unit-frame portrait, the circular mask baked in ([`portrait_image`]), opened with the loose - /// flag as `SetPortraitTexture` opens it (through `0x5a7b40`). + /// A portrait, the circular mask baked in ([`portrait_image`]): `.blp` as the sink + /// `0x525d30` opens it ([`portrait_rgba`]). Keyed by the whole name, since `Foo` and `Foo.blp` + /// open different files. pub fn portrait_texture( &mut self, path: &str, images: &mut Assets, ) -> Option> { self.sync_loose(); - let key = sprite_key(path); + let key = normalize_path(path); if let Some(cached) = self.cache.portraits.get(&key) { return cached; } - let loaded = decode_sprite(&self.chain, &self.loose, path, LooseOpen::Index) + let loaded = portrait_rgba(&self.chain, &self.loose, path) .map(|(w, h, rgba)| images.add(portrait_image(w, h, rgba))); let open = loose_open_for(path, LooseOpen::Index); self.cache.portraits.insert(key, open, loaded.clone()); @@ -774,7 +859,7 @@ impl WorldAssets { return cached; } let open = LooseOpen::Archives; - let loaded = decode_sprite(&self.chain, &self.loose, path, open).map(|(w, h, mut rgba)| { + let loaded = emblem_rgba(&self.chain, path).map(|(w, h, mut rgba)| { for px in rgba.as_chunks_mut::<4>().0 { px[0] = 0xFF; px[1] = 0xFF; @@ -799,23 +884,17 @@ impl WorldAssets { if let Some(cached) = self.cache.masks.get(&key) { return cached; } - let loaded = decode_sprite(&self.chain, &self.loose, path, open) + let loaded = mask_rgba(&self.chain, &self.loose, path, open) .map(|(w, h, rgba)| images.add(mask_image(w, h, rgba))); let open = loose_open_for(path, open); self.cache.masks.insert(key, open, loaded.clone()); loaded } - /// A cursor BLP's RGBA (`Interface\Cursor\Point.blp`), opened with the loose flag as the - /// cursor code's `0x449610` opens it. + /// A cursor picture's RGBA, a mode's (`Interface\Cursor\Point.blp`), the custom cursor's or a + /// dragged icon's, opened as the cursor code's `0x449610` opens it ([`file_texture_rgba`]). pub fn cursor_rgba(&self, path: &str) -> Option<(u32, u32, Vec)> { - let bytes = read_loose_or_chain( - &self.chain, - &self.loose, - &normalize_path(path), - LooseOpen::Index, - )?; - blp_to_rgba(&bytes).ok() + file_texture_rgba(&self.chain, &self.loose, path) } /// Decode a cursor BLP ([`Self::cursor_rgba`]) for winit's custom OS cursor; macOS drives @@ -1298,67 +1377,56 @@ mod tests { /// `0x44a140` returns the texture once the header opens, and the refused decode in `0x44a260` /// fills it opaque white (`0x44a2eb` into `0x448920`) at the size `0x448450` made it. A header /// that makes no texture fails the candidate as a missing file does, whether the pixels would - /// decode or not, and so does a candidate the TGA loader does not read, or any load that is not - /// `TextureCreate`'s. + /// decode or not, and so does any refused load that is not `TextureCreate`'s. #[test] fn a_refused_tga_texture_is_opaque_white_at_its_headers_size() { let tga = "interface\\addons\\foo\\icon.tga"; - let blp = "interface\\addons\\foo\\icon.blp"; let white = |candidate, bytes: &[u8]| decode_candidate(candidate, bytes, OnRefusal::WhiteDefault); - let bytes = refused_tga(4, 2, &[0; 32]); - assert!( - decode_sprite_bytes(&bytes).is_err(), - "the decoder refuses it" - ); + let bytes = refused_tga(16, 8, &[0; 512]); + assert!(tga_to_rgba(&bytes).is_err(), "the decoder refuses it"); assert_eq!( white(tga, &bytes), - Candidate::Pixels(4, 2, vec![0xff; 4 * 2 * 4]) + Candidate::Pixels(16, 8, vec![0xff; 16 * 8 * 4]) ); // The pixels need not be there at all. assert_eq!( - white(tga, &refused_tga(1, 512, &[])), - Candidate::Pixels(1, 512, vec![0xff; 512 * 4]) + white(tga, &refused_tga(8, 512, &[])), + Candidate::Pixels(8, 512, vec![0xff; 8 * 512 * 4]) ); - // Next candidate: not a size `0x448450` makes (decoded or not), a header that does not - // open, a BLP candidate (`0x44a500` substitutes a green texture instead), BLP bytes. - let mut wide = refused_tga(6, 1, &[9; 24]); + // Next candidate: not a size `0x448450` makes (decoded or not), a side below the 8 + // `GxTexCreate` takes (`0x58ab40`), a header that does not open. + let mut wide = refused_tga(24, 8, &[9; 24 * 8 * 4]); wide[17] = 0x28; assert!( - decode_sprite_bytes(&wide).is_ok(), + tga_to_rgba(&wide).is_ok(), "it decodes, and still fails the gate" ); - for (candidate, bytes) in [ - (tga, refused_tga(3, 2, &[0; 24])), - (tga, refused_tga(2048, 2, &[0; 24])), - (tga, wide), - (tga, vec![2, 0, 2]), - (blp, refused_tga(4, 2, &[0; 32])), - ( - tga, - [&b"BLP2"[..], &refused_tga(4, 2, &[0; 32])[4..]].concat(), - ), + for bytes in [ + refused_tga(24, 8, &[0; 24]), + refused_tga(2048, 8, &[0; 24]), + refused_tga(4, 8, &[0; 128]), + refused_tga(0, 8, &[]), + wide, + vec![2, 0, 2], ] { - assert_eq!(white(candidate, &bytes), Candidate::Next, "{candidate}"); + assert_eq!(white(tga, &bytes), Candidate::Next); } // A load that is no `TextureCreate`'s leaves them all to the next candidate. - for bytes in [&bytes, &refused_tga(3, 2, &[0; 24])] { + for bytes in [&bytes, &refused_tga(24, 8, &[0; 24])] { assert_eq!( decode_candidate(tga, bytes, OnRefusal::Miss), Candidate::Next ); } - // A zero size passes the gate (`0x44849d`) and draws nothing, trying no other candidate. - assert_eq!(white(tga, &refused_tga(0, 2, &[])), Candidate::Nothing); - // A TGA that decodes is its pixels, white or not. - let mut ok = refused_tga(2, 1, &[1, 2, 3, 77, 4, 5, 6, 88]); + let mut ok = refused_tga(8, 8, &[1, 2, 3, 77].repeat(64)); ok[17] = 0x28; assert_eq!( white(tga, &ok), - Candidate::Pixels(2, 1, vec![3, 2, 1, 77, 6, 5, 4, 88]) + Candidate::Pixels(8, 8, [3, 2, 1, 77].repeat(64)) ); } @@ -1389,7 +1457,7 @@ mod tests { /// Through the store: a refused `.tga` in the AddOns folder is a texture of its header's size /// for `SetTexture`'s loads. A header that makes no texture (`0x448450` takes powers of two - /// below 1024) is a miss, its pixels decoded or not, and a zero size passes. + /// below 1024, `GxTexCreate` no side below 8) is a miss, its pixels decoded or not. #[test] fn a_refused_tga_in_the_addons_folder_is_a_texture_of_its_size() { let data = benilla_formats::wow_data_or_skip!(); @@ -1397,38 +1465,245 @@ mod tests { let addons = Tree::new("white"); let dir = addons.0.join("Foo"); std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("Icon.tga"), refused_tga(8, 4, &[0; 128])).unwrap(); - std::fs::write(dir.join("Odd.tga"), refused_tga(6, 4, &[0; 96])).unwrap(); + std::fs::write(dir.join("Icon.tga"), refused_tga(16, 8, &[0; 512])).unwrap(); + std::fs::write(dir.join("Odd.tga"), refused_tga(6, 8, &[0; 192])).unwrap(); let loose = LooseFiles { addons: Some(addons.0.clone()), install: None, }; let icon = "Interface\\AddOns\\Foo\\Icon"; assert!(sprite_found(&chain, &loose, icon)); - assert_eq!(sprite_dimensions(&chain, &loose, icon), Some((8, 4))); + assert_eq!(sprite_dimensions(&chain, &loose, icon), Some((16, 8))); let (w, h, rgba) = decode_texture(&chain, &loose, icon, LooseOpen::Index).unwrap(); - assert_eq!((w, h, rgba.len()), (8, 4, 8 * 4 * 4)); + assert_eq!((w, h, rgba.len()), (16, 8, 16 * 8 * 4)); assert!(rgba.iter().all(|&b| b == 0xff)); // A load that is not `TextureCreate`'s still gets no pixels. assert!(decode_sprite(&chain, &loose, icon, LooseOpen::Index).is_none()); // Not a size `0x448450` makes (`0x4484ae`-`0x4484d0`): `TextureCreate` fails the candidate // whether its pixels decode or not, and `SetTexture` answers nil. - std::fs::write(dir.join("Wide.tga"), decodable_tga(6, 1)).unwrap(); - std::fs::write(dir.join("Fine.tga"), decodable_tga(2, 1)).unwrap(); + std::fs::write(dir.join("Wide.tga"), decodable_tga(24, 8)).unwrap(); + std::fs::write(dir.join("Small.tga"), decodable_tga(4, 8)).unwrap(); + std::fs::write(dir.join("Zero.tga"), refused_tga(0, 8, &[])).unwrap(); + std::fs::write(dir.join("Fine.tga"), decodable_tga(8, 16)).unwrap(); for (name, found, size) in [ ("Odd", false, None), ("Wide", false, None), - ("Fine", true, Some((2, 1))), + ("Small", false, None), + ("Zero", false, None), + ("Fine", true, Some((8, 16))), ] { let path = format!("Interface\\AddOns\\Foo\\{name}"); assert_eq!(sprite_found(&chain, &loose, &path), found, "{name}"); assert_eq!(sprite_dimensions(&chain, &loose, &path), size, "{name}"); } - // A zero size passes the gate (`0x44849d`, `test ebx, ebx-1`), and draws nothing. - std::fs::write(dir.join("Zero.tga"), refused_tga(0, 4, &[])).unwrap(); - let zero = "Interface\\AddOns\\Foo\\Zero"; - assert!(sprite_found(&chain, &loose, zero)); - assert_eq!(sprite_dimensions(&chain, &loose, zero), None); + } + + /// A palette BLP2 (compression 1, no alpha bits, no mips) of `w` by `h`, every texel palette + /// entry 0, red `r`. + fn tiny_blp(w: u32, h: u32, r: u8) -> Vec { + let mut b = vec![0u8; 148 + 1024]; + b[0..4].copy_from_slice(b"BLP2"); + b[4..8].copy_from_slice(&1u32.to_le_bytes()); + b[8] = 1; + b[12..16].copy_from_slice(&w.to_le_bytes()); + b[16..20].copy_from_slice(&h.to_le_bytes()); + b[20..24].copy_from_slice(&(148u32 + 1024).to_le_bytes()); + b[84..88].copy_from_slice(&(w * h).to_le_bytes()); + b[148 + 2] = r; + b.extend(vec![0u8; (w * h) as usize]); + b + } + + /// `TextureCreate`'s solid texture, `0xff00ff00` (`0x447c00`), 8 by 8 (`0x44a900`). + fn green() -> Candidate { + Candidate::Pixels(8, 8, [0, 0xff, 0, 0xff].repeat(64)) + } + + /// `TextureCreate` takes the loader by the candidate's extension (`0x449e16`-`0x449e3d`), never + /// by the bytes. BLP bytes under a `.tga` name reach the TGA loader `0x44a140`, whose header + /// is the BLP's: its height word is the BLP width's high half, 0, which `GxTexCreate` refuses + /// (`0x58ab4c`), so the next candidate is tried. Any bytes under a `.blp` name open as the BLP + /// loader's texture (`0x44a399`), and a refused parse (the magic, `0x5a83dc`) or decode leaves + /// the solid green (`0x44a50e`), with no next candidate. + #[test] + fn the_loader_is_the_candidates_extension_not_its_content() { + let tga = "interface\\addons\\foo\\icon.tga"; + let blp = "interface\\addons\\foo\\icon.blp"; + let white = + |candidate, bytes: &[u8]| decode_candidate(candidate, bytes, OnRefusal::WhiteDefault); + let good_blp = tiny_blp(16, 8, 7); + let good_tga = decodable_tga(8, 8); + assert!(matches!(white(blp, &good_blp), Candidate::Pixels(16, 8, _))); + assert!(matches!(white(tga, &good_tga), Candidate::Pixels(8, 8, _))); + + assert_eq!( + white(tga, &good_blp), + Candidate::Next, + "a BLP under a .tga name" + ); + assert_eq!(white(blp, &good_tga), green(), "a TGA under a .blp name"); + assert_eq!(white(blp, b"BLP2"), green(), "a BLP that will not parse"); + assert_eq!(white(blp, &[]), green(), "an empty .blp"); + + // A load that is not `TextureCreate`'s takes the same decoder, and a refusal is a miss. + assert_eq!( + decode_candidate(tga, &good_blp, OnRefusal::Miss), + Candidate::Next + ); + assert_eq!( + decode_candidate(blp, &good_tga, OnRefusal::Miss), + Candidate::Next + ); + } + + /// Through the store: a `.tga` name holding BLP bytes is passed over for its `.blp` + /// candidate (`0x449e4b`), and a `.blp` that will not decode is green, whatever `.tga` lies + /// beside it. + #[test] + fn a_mislabelled_addon_file_does_not_draw() { + let data = benilla_formats::wow_data_or_skip!(); + let chain = Mutex::new(Chain::open(&data).expect("open the chain")); + let addons = Tree::new("mislabel"); + let dir = addons.0.join("Foo"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Art.tga"), tiny_blp(16, 16, 1)).unwrap(); + std::fs::write(dir.join("Art.blp"), tiny_blp(8, 8, 2)).unwrap(); + std::fs::write(dir.join("Pic.blp"), decodable_tga(8, 8)).unwrap(); + std::fs::write(dir.join("Pic.tga"), decodable_tga(16, 16)).unwrap(); + std::fs::write(dir.join("Only.tga"), tiny_blp(16, 16, 1)).unwrap(); + let loose = LooseFiles { + addons: Some(addons.0.clone()), + install: None, + }; + let load = |name: &str| { + decode_texture( + &chain, + &loose, + &format!("Interface\\AddOns\\Foo\\{name}"), + LooseOpen::Index, + ) + }; + let (w, h, rgba) = load("Art.tga").unwrap(); + assert_eq!((w, h, rgba[0]), (8, 8, 2), "the .blp beside it draws"); + let (w, h, rgba) = load("Pic").unwrap(); + assert_eq!((w, h, &rgba[..4]), (8, 8, &[0, 0xff, 0, 0xff][..]), "green"); + assert!(load("Only.tga").is_none(), "no candidate makes a texture"); + assert!(!sprite_found( + &chain, + &loose, + "Interface\\AddOns\\Foo\\Only.tga" + )); + } + + /// The minimap's mask loads through `TextureCreate` (`Minimap:SetMaskTexture` at `0x4ee5e4`, + /// the world-entry load at `0x4ed862`): a `.tga` whose header opens and whose pixels the + /// decoder refuses is opaque white at its header's size (`0x44a2eb` into `0x448920`), not a + /// miss the minimap would paint green. + #[test] + fn a_refused_tga_mask_is_opaque_white() { + let data = benilla_formats::wow_data_or_skip!(); + let chain = Mutex::new(Chain::open(&data).expect("open the chain")); + let addons = Tree::new("mask"); + let dir = addons.0.join("Foo"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Mask.tga"), refused_tga(16, 8, &[0; 512])).unwrap(); + let loose = LooseFiles { + addons: Some(addons.0.clone()), + install: None, + }; + let (w, h, rgba) = mask_rgba( + &chain, + &loose, + "Interface\\AddOns\\Foo\\Mask", + LooseOpen::Index, + ) + .unwrap(); + assert_eq!((w, h), (16, 8)); + assert!(rgba.iter().all(|&b| b == 0xff)); + assert!( + mask_rgba( + &chain, + &loose, + "Interface\\AddOns\\Foo\\None", + LooseOpen::Index + ) + .is_none(), + "a name that resolves nowhere stays the minimap's green" + ); + } + + /// The portrait sink formats `%s.blp` onto the name as written (`0x525e0f`, format + /// `0x8540b4`) and reads that file with the BLP reader (`0x5a7b40` at `0x525e37`, flag 1): a + /// `.tga` is never read, and a name ending `.tga` opens `.tga.blp`. + #[test] + fn a_portrait_opens_its_name_with_blp_appended() { + let data = benilla_formats::wow_data_or_skip!(); + let chain = Mutex::new(Chain::open(&data).expect("open the chain")); + let addons = Tree::new("portrait"); + let dir = addons.0.join("Foo"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Icon.tga"), decodable_tga(64, 64)).unwrap(); + std::fs::write(dir.join("Bag.blp"), tiny_blp(64, 64, 3)).unwrap(); + std::fs::write(dir.join("Odd.tga.blp"), tiny_blp(64, 64, 4)).unwrap(); + std::fs::write(dir.join("Odd.blp"), tiny_blp(64, 64, 5)).unwrap(); + let loose = LooseFiles { + addons: Some(addons.0.clone()), + install: None, + }; + let red = |name: &str| { + portrait_rgba(&chain, &loose, &format!("Interface\\AddOns\\Foo\\{name}")) + .map(|(_, _, rgba)| rgba[0]) + }; + assert_eq!(red("Icon"), None, "no Icon.blp, and the .tga is not read"); + assert_eq!(red("Icon.tga"), None, "Icon.tga.blp"); + assert_eq!(red("Bag"), Some(3)); + assert_eq!(red("Bag.blp"), None, "Bag.blp.blp"); + assert_eq!(red("Odd.tga"), Some(4), "Odd.tga.blp, not Odd.blp"); + } + + /// The cursor code opens every picture through `0x449610`, `SetCursor`'s (`0x523c86`) and + /// the dragged icon's (`0x5239f7`, `0x523a3e`, `0x523af7`, `0x523bb1`) alike: it strips a + /// three-letter extension (`0x449590` at `0x44963c`), appends `.blp` (`0x449641`) and decodes + /// the bytes as a BLP (`0x449840`), so `Foo.tga` opens `Foo.blp` and no `.tga` is read. + #[test] + fn a_cursor_picture_opens_only_its_blp() { + let data = benilla_formats::wow_data_or_skip!(); + let chain = Mutex::new(Chain::open(&data).expect("open the chain")); + let addons = Tree::new("cursorpic"); + let dir = addons.0.join("Foo"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Arrow.tga"), decodable_tga(32, 32)).unwrap(); + std::fs::write(dir.join("Both.tga"), decodable_tga(16, 16)).unwrap(); + std::fs::write(dir.join("Both.blp"), tiny_blp(32, 32, 6)).unwrap(); + std::fs::write(dir.join("Fake.blp"), decodable_tga(32, 32)).unwrap(); + let loose = LooseFiles { + addons: Some(addons.0.clone()), + install: None, + }; + let pic = |name: &str| { + file_texture_rgba(&chain, &loose, &format!("Interface\\AddOns\\Foo\\{name}")) + .map(|(w, h, rgba)| (w, h, rgba[0])) + }; + assert_eq!(pic("Arrow"), None); + assert_eq!(pic("Arrow.tga"), None); + assert_eq!(pic("Both.tga"), Some((32, 32, 6)), "Both.blp, not Both.tga"); + assert_eq!(pic("Both"), Some((32, 32, 6))); + assert_eq!(pic("Fake"), None, "TGA bytes under a .blp name"); + } + + /// The emblem cell appends `.BLP` to its name (`0x50338a`, `0x83574c`) and reads that one file + /// with the BLP reader `0x5a7b40` and flag 0: no `.tga` of the same stem is read. + #[test] + fn an_emblem_cell_reads_only_its_blp() { + let stem = "Textures\\GuildEmblems\\Emblem_01_02_TU_U"; + assert_eq!( + emblem_names(stem), + vec![format!("{}.blp", normalize_path(stem))] + ); + let data = benilla_formats::wow_data_or_skip!(); + let chain = Mutex::new(Chain::open(&data).expect("open the chain")); + let (w, h, _) = emblem_rgba(&chain, stem).expect("the emblem BLP decodes"); + assert!(w > 0 && h > 0); } /// A 32-bit TGA with 8 alpha bits, `w` by `h`, that the decoder reads. @@ -1443,7 +1718,7 @@ mod tests { fn the_size_gate_reads_a_resolved_file_once() { let probe = SpriteProbe::default(); let tga = "interface\\addons\\foo\\icon.tga"; - let good = refused_tga(8, 4, &[]); + let good = refused_tga(16, 8, &[]); let reads = std::cell::Cell::new(0); let read = |bytes: Option<&Vec>| { reads.set(reads.get() + 1); @@ -1457,7 +1732,7 @@ mod tests { // Another resolved file under the same name is its own question: the chain's copy, once a // loose one shadows it, or the other way round. - assert!(!probe.gate("chain", tga, || read(Some(&refused_tga(3, 4, &[]))))); + assert!(!probe.gate("chain", tga, || read(Some(&refused_tga(3, 8, &[]))))); assert!(!probe.gate("chain", tga, || read(Some(&good)))); assert_eq!(reads.get(), 2); @@ -1475,8 +1750,8 @@ mod tests { let addons = Tree::new("probe"); let dir = addons.0.join("Foo"); std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("Icon.tga"), refused_tga(8, 4, &[0; 128])).unwrap(); - std::fs::write(dir.join("Odd.tga"), refused_tga(6, 4, &[0; 96])).unwrap(); + std::fs::write(dir.join("Icon.tga"), refused_tga(16, 8, &[0; 512])).unwrap(); + std::fs::write(dir.join("Odd.tga"), refused_tga(6, 8, &[0; 192])).unwrap(); let loose = LooseFiles { addons: Some(addons.0.clone()), install: None, diff --git a/crates/benilla-formats/src/tga.rs b/crates/benilla-formats/src/tga.rs index 283e5efca..ba4e91726 100644 --- a/crates/benilla-formats/src/tga.rs +++ b/crates/benilla-formats/src/tga.rs @@ -24,8 +24,8 @@ //! with 1 to 7 alpha bits, 33 to 39 with 9 to 15), then `0x5a41f0` returns 0 for a depth that is //! not 32, and the copy at `0x4492c4` reads through that null pointer: there is no result to match. //! -//! [`tga_to_rgba`] checks the header before the pixels, so it can serve as the fallback after a -//! failed `BLP2` sniff: TGA has no magic. +//! [`tga_to_rgba`] checks the header before the pixels: TGA has no magic, and the reference picks +//! this decoder by a file's `.tga` name alone (`0x449e16`-`0x449e3d`). use anyhow::{bail, Result}; @@ -43,10 +43,10 @@ pub const TGA_GATE_PREFIX: usize = 18 + 255 + 1; /// fails and the next candidate is tried. The loader returns the texture once the header opens /// (`0x5a3660`: the 18 bytes, then the id and the colour map the header declares, each read /// succeeding on any byte it gets, `0x64853b`-`0x64854a`) and `0x448450` makes the device texture -/// at the header's size, refusing a width or height that is not a power of two below 1024 -/// (`0x4484ae`-`0x4484d0`). The pixels decode later, in `0x44a260`: a file [`tga_to_rgba`] refuses -/// still has this texture, filled opaque white (`0x44a2eb`). A zero size passes the gate and draws -/// nothing. +/// at the header's size: a width or height that is not a power of two below 1024 makes none +/// (`0x4484ae`-`0x4484d0`), and a side of 16 or less goes to `GxTexCreate` (`0x58ab10`), which +/// refuses one below 8 (`0x58ab40`, `0x58ab4c`). The pixels decode later, in `0x44a260`: a file +/// [`tga_to_rgba`] refuses still has this texture, filled opaque white (`0x44a2eb`). pub fn tga_texture_size(bytes: &[u8]) -> Option<(u32, u32)> { let header = bytes.get(..18)?; let id_length = usize::from(header[0]); @@ -65,8 +65,7 @@ pub fn tga_texture_size(bytes: &[u8]) -> Option<(u32, u32)> { } let width = u32::from(u16::from_le_bytes([header[12], header[13]])); let height = u32::from(u16::from_le_bytes([header[14], header[15]])); - // `test ebx, ebx-1` lets 0 through (`0x44849d`), so a zero size passes. - let fits = |n: u32| n & n.wrapping_sub(1) == 0 && n < 1024; + let fits = |n: u32| n.is_power_of_two() && (8..1024).contains(&n); (fits(width) && fits(height)).then_some((width, height)) } @@ -563,21 +562,22 @@ mod tests { /// (`0x448450`): whether the pixels decode is `0x44a260`'s question, later. #[test] fn a_header_that_opens_makes_a_texture_at_its_size() { - // A 32-bit image with no alpha bits is refused by the decoder, and still a 4 by 2 texture. - let refused = tga(2, 4, 2, 32, 0x20, &[0; 32]); + // A 32-bit image with no alpha bits is refused by the decoder, and still a 16 by 8 + // texture. + let refused = tga(2, 16, 8, 32, 0x20, &[0; 512]); assert!(tga_to_rgba(&refused).is_err()); - assert_eq!(tga_texture_size(&refused), Some((4, 2))); - assert_eq!(tga_texture_size(&tga(2, 4, 2, 32, 0x20, &[])), Some((4, 2))); + assert_eq!(tga_texture_size(&refused), Some((16, 8))); assert_eq!( - tga_texture_size(&tga(99, 512, 1, 7, 0xff, &[])), - Some((512, 1)) + tga_texture_size(&tga(2, 16, 8, 32, 0x20, &[])), + Some((16, 8)) + ); + assert_eq!( + tga_texture_size(&tga(99, 512, 8, 7, 0xff, &[])), + Some((512, 8)) ); - // A zero size passes `0x44849d`'s test; a size that is not a power of two below 1024 - // makes no texture. - assert_eq!(tga_texture_size(&tga(2, 0, 4, 32, 0x28, &[])), Some((0, 4))); - assert_eq!(tga_texture_size(&tga(2, 4, 0, 32, 0x28, &[])), Some((4, 0))); - for (w, h) in [(3, 2), (4, 1024), (1024, 4), (65535, 2), (6, 6)] { + // A size that is not a power of two below 1024 makes no texture. + for (w, h) in [(24, 8), (8, 1024), (1024, 8), (65535, 8), (12, 12)] { assert_eq!( tga_texture_size(&tga(2, w, h, 32, 0x28, &[0; 8])), None, @@ -588,6 +588,27 @@ mod tests { assert_eq!(tga_texture_size(b"BLP2"), None); } + /// `0x448450` hands a side of 16 or less to `GxTexCreate` (`0x58ac40` into `0x58ab10`), which + /// refuses a width or height below 8 (`0x58ab40`, `0x58ab4c`), so the load returns no texture + /// (`0x44a20b`): 0, 1, 2 and 4 texels make none, 8 does. + #[test] + fn a_side_below_eight_makes_no_texture() { + for (w, h) in [(0, 8), (8, 0), (1, 8), (8, 2), (4, 4), (4, 512), (512, 4)] { + assert_eq!( + tga_texture_size(&tga(2, w, h, 32, 0x28, &[])), + None, + "{w}x{h}" + ); + } + for (w, h) in [(8, 8), (8, 512), (16, 8), (512, 512)] { + assert_eq!( + tga_texture_size(&tga(2, w, h, 32, 0x28, &[])), + Some((u32::from(w), u32::from(h))), + "{w}x{h}" + ); + } + } + /// The gate's prefix: nothing past `TGA_GATE_PREFIX` bytes changes the answer. #[test] fn the_gate_answers_the_same_for_its_prefix_as_for_the_file() { @@ -622,28 +643,31 @@ mod tests { /// the reference sizes it (`0x5a3b40`): 32-bit entries count 3 bytes. #[test] fn the_id_and_map_reads_fail_the_open_only_with_no_bytes() { - let mut with_id = tga(2, 4, 2, 24, 0x20, &[]); + let mut with_id = tga(2, 16, 8, 24, 0x20, &[]); with_id[0] = 5; assert_eq!(tga_texture_size(&with_id), None, "no id byte"); with_id.push(0); - assert_eq!(tga_texture_size(&with_id), Some((4, 2)), "a short id"); + assert_eq!(tga_texture_size(&with_id), Some((16, 8)), "a short id"); - let mut with_map = tga(1, 4, 2, 8, 0x20, &[]); + let mut with_map = tga(1, 16, 8, 8, 0x20, &[]); with_map[1] = 1; // colour-map type: present with_map[5..7].copy_from_slice(&4u16.to_le_bytes()); with_map[7] = 32; assert_eq!(tga_texture_size(&with_map), None, "no map byte"); with_map.push(0); - assert_eq!(tga_texture_size(&with_map), Some((4, 2)), "a short map"); + assert_eq!(tga_texture_size(&with_map), Some((16, 8)), "a short map"); // Past an id of 2, one byte reaches the map. with_map[0] = 2; assert_eq!(tga_texture_size(&with_map), None, "the id took the byte"); with_map.extend([0, 0]); - assert_eq!(tga_texture_size(&with_map), Some((4, 2))); + assert_eq!(tga_texture_size(&with_map), Some((16, 8))); // No map type, no read, whatever the length field says. with_map[1] = 0; - assert_eq!(tga_texture_size(&tga(2, 4, 2, 24, 0x20, &[])), Some((4, 2))); - assert_eq!(tga_texture_size(&with_map), Some((4, 2))); + assert_eq!( + tga_texture_size(&tga(2, 16, 8, 24, 0x20, &[])), + Some((16, 8)) + ); + assert_eq!(tga_texture_size(&with_map), Some((16, 8))); } #[test] diff --git a/crates/benilla-mlua/src/lib.rs b/crates/benilla-mlua/src/lib.rs index 725637f59..c2c1fa0e9 100644 --- a/crates/benilla-mlua/src/lib.rs +++ b/crates/benilla-mlua/src/lib.rs @@ -736,6 +736,56 @@ impl Lua { }) } + /// `f` behind a check of its receiver, as each method of a 1.12 widget class opens: argument 1 + /// read as a [`Receiver`] (`lua_type`, then `lua_rawgeti(1, 0)` and `lua_touserdata`, as + /// `Frame:Show` reads it at `0x775777`-`0x7757a6`), an `Err` from `check` raised as the + /// callback's own error is, and otherwise `f`'s own host closure run in the same call, with no + /// second call into the VM. `None` for a function that is no host closure. + pub fn guard_receiver(&self, f: &Function, check: C) -> Result> + where + C: Fn(&Lua, Receiver) -> Result<()> + 'static, + { + let (inner, name) = { + let vm = self.vm(); + let V::Func(r) = f.0.get().unpack() else { + return Ok(None); + }; + match vm.heap.func(r) { + benilla_lua::heap::FuncObj::Native { + host: Some(host), + name, + .. + } => (host.clone(), *name), + _ => return Ok(None), + } + }; + let host: HostFn = Rc::new(move |vm: &mut Vm, nargs: usize| { + let receiver = match vm.args(nargs).first().map(|v| v.unpack()) { + Some(V::Table(t)) => { + match vm.heap.table(t).get(benilla_lua::Value::Num(0.0)).unpack() { + V::Light(p) => Receiver::Object(p), + _ => Receiver::NoObject, + } + } + _ => Receiver::NotTable, + }; + let lua = Lua::of_vm(vm); + in_callback(&lua, vm, || { + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + check(&lua, receiver) + })); + match res { + Ok(Ok(())) => Ok(()), + Ok(Err(e)) => Err(raise(&lua, nargs, e)), + Err(payload) => Err(raise_panic(lua.vm(), payload)), + } + })?; + inner(vm, nargs) + }); + let g = self.vm().new_host(name, host); + Ok(Some(Function(self.make_ref(g)))) + } + /// Load a chunk. Unnamed, it is named after the Rust call site, as mlua names it. #[track_caller] pub fn load(&self, chunk: impl AsChunk) -> Chunk<'_> { @@ -1081,6 +1131,17 @@ pub struct Thread(()); #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct LightUserData(pub *mut c_void); +/// A method's argument 1 as the 1.12 member prologue reads it ([`Lua::guard_receiver`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Receiver { + /// No table, or no argument. + NotTable, + /// A table whose `[0]` holds no light userdata. + NoObject, + /// The light userdata at `[0]`, as its address. + Object(usize), +} + #[derive(Clone, Debug, Default)] pub enum Value { #[default] diff --git a/crates/benilla-mlua/tests/api.rs b/crates/benilla-mlua/tests/api.rs index c87892b51..adcc0bf18 100644 --- a/crates/benilla-mlua/tests/api.rs +++ b/crates/benilla-mlua/tests/api.rs @@ -181,3 +181,49 @@ fn an_objects_text_is_the_vms_tostring() { "{ts}" ); } + +/// A guarded host function reads its receiver as the 1.12 member prologue does, raises the +/// check's error before the function converts an argument, and otherwise runs the function itself +/// with the call's arguments. +#[test] +fn a_guarded_function_checks_its_receiver_then_runs() { + use benilla_mlua::{LightUserData, Receiver, Table, Value}; + let lua = Lua::new(); + let f = lua + .create_function(|_, (this, n): (Table, i64)| Ok(this.raw_get::("k")? + n)) + .unwrap(); + let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let log = seen.clone(); + let g = lua + .guard_receiver(&f, move |_, r| { + log.borrow_mut().push(r); + match r { + Receiver::Object(7) => Ok(()), + _ => Err(benilla_mlua::Error::runtime("bad receiver")), + } + }) + .unwrap() + .expect("a host function"); + lua.globals().set("g", g).unwrap(); + let t = lua.create_table().unwrap(); + t.raw_set(0, Value::LightUserData(LightUserData(7 as *mut _))) + .unwrap(); + t.raw_set("k", 40).unwrap(); + lua.globals().set("t", t).unwrap(); + assert_eq!(lua.load("return g(t, 2)").eval::().unwrap(), 42); + for (chunk, read) in [ + ("return g()", Receiver::NotTable), + ("return g(5, 2)", Receiver::NotTable), + ("return g({}, 'x')", Receiver::NoObject), + ] { + let err = lua.load(chunk).eval::().unwrap_err().to_string(); + assert!(err.contains("bad receiver"), "{chunk}: {err}"); + assert_eq!(seen.borrow().last(), Some(&read), "{chunk}"); + } + // A Lua function is no host closure. + let lua_fn: Function = lua.load("return function() end").eval().unwrap(); + assert!(lua + .guard_receiver(&lua_fn, |_, _| Ok(())) + .unwrap() + .is_none()); +} diff --git a/crates/benilla-ui/src/script/container.rs b/crates/benilla-ui/src/script/container.rs index 1abd8d279..e5bf2c999 100644 --- a/crates/benilla-ui/src/script/container.rs +++ b/crates/benilla-ui/src/script/container.rs @@ -3,7 +3,7 @@ //! (0 the backpack, 1-4 the worn bags, -1 the bank's own slots, 5-10 the bank bags, -2 the //! keyring); slots are 1-based. -use mlua::{Lua, MultiValue, Table, Value}; +use mlua::{Lua, MultiValue, Value}; use super::binding_abi::{self, flag, number_arg}; use super::cursor::{self, CursorItem, CursorPayload}; @@ -409,6 +409,13 @@ impl super::UiScript { self.model_ref().custom_cursor_name.clone() } + /// Install the host's size of a picture the cursor code opens (`0x449610`: the name's `.blp`, + /// decoded), which `SetCursor`'s custom cursor must have at 32 by 32; without one no custom + /// cursor loads. + pub fn set_cursor_size_probe(&mut self, probe: Box) { + self.model_mut().cursor_size_probe = Some(probe.into()); + } + /// Drain the pending cursor write: `Some(mode)` a set, `Some(None)` a reset, `None` no call, /// which must leave the cursor as it was, so an armed spell keeps its cast cursor over a /// spellbook button. @@ -474,7 +481,7 @@ fn custom_cursor(model: &mut super::Model, name: &str) -> bool { return true; } let size = model - .texture_size_probe + .cursor_size_probe .as_ref() .and_then(|probe| probe(name)); if size != Some((32, 32)) { @@ -854,9 +861,11 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { // up raise. lua.globals().set( "SetBagPortaitTexture", - lua.create_function(|lua, (region, container): (Table, Value)| { - // `is-number` else `Usage: SetBagPortaitTexture(texture, slot)` (`0x84d9c4`, - // `0x4fa58e`). + lua.create_function(|lua, (region, container): (Value, Value)| { + // The texture first, the member prologue against the Texture id (`0x4fa4f9`- + // `0x4fa56e`); then `is-number` else `Usage: SetBagPortaitTexture(texture, slot)` + // (`0x84d9c4`, `0x4fa58e`). + let rh = crate::script::region::this_texture(lua, ®ion)?; let container = i64::from(binding_abi::number_arg( lua, container, @@ -885,7 +894,6 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { .and_then(|slot| model.inv_slot("player", slot)) .and_then(|v| v.icon.clone()) }; - let rh = crate::script::region::region_handle_of(lua, ®ion)?; let mut model = lua.app_data_mut::().expect("model app_data"); // An empty slot's `None` is the answer: the reference clears first, then sets. let set = path.map_or(super::texel::TexSet::None, super::texel::TexSet::Portrait); @@ -1302,7 +1310,7 @@ mod tests { #[test] fn set_cursor_loads_any_other_name_as_a_32_by_32_texture() { let mut s = UiScript::new().unwrap(); - s.set_texture_size_probe(Box::new(|path| match path { + s.set_cursor_size_probe(Box::new(|path| match path { "Interface\\AddOns\\Mine\\Sword" | "5" => Some((32, 32)), "Interface\\Icons\\Big" => Some((64, 64)), _ => None, @@ -1332,6 +1340,28 @@ mod tests { assert_eq!(s.custom_cursor_name(), "5"); } + /// `SetCursor`'s load is the cursor code's (`0x523c86` into `0x449610`), not + /// `TextureCreate`'s: its 32 by 32 test reads the cursor picture's probe, which opens only the + /// `.blp`, never the interface texture's, which would read a `.tga`. + #[test] + fn set_cursor_sizes_the_cursor_picture_not_the_interface_texture() { + let mut s = UiScript::new().unwrap(); + s.set_texture_size_probe(Box::new(|_| Some((32, 32)))); + s.set_cursor_size_probe(Box::new(|path| (path == "Mine\\Sword").then_some((32, 32)))); + assert_eq!( + s.eval::>(r#"return SetCursor("Mine\\Arrow")"#) + .unwrap(), + None, + "only a .tga: no cursor picture" + ); + assert_eq!(s.ui_cursor(), None); + assert_eq!( + s.eval::>(r#"return SetCursor("Mine\\Sword")"#) + .unwrap(), + Some(1) + ); + } + fn backpack() -> ContainerState { let mut slots = std::collections::HashMap::new(); slots.insert( diff --git a/crates/benilla-ui/src/script/font.rs b/crates/benilla-ui/src/script/font.rs index 379c840cb..1334b4815 100644 --- a/crates/benilla-ui/src/script/font.rs +++ b/crates/benilla-ui/src/script/font.rs @@ -35,7 +35,7 @@ use super::{FontMask, FontObject, FontShadow, Model, RegionData}; /// The shared metatable of every font-object handle. const REG_FONT_META: &str = "__benilla_font_meta"; /// The font-object method table, which is the metatable's `__index`. -const REG_FONT_METHODS: &str = "__benilla_font_methods"; +pub(super) const REG_FONT_METHODS: &str = "__benilla_font_methods"; /// font id → handle, so `GameFontNormal == GameFontNormal` and a re-declared `` keeps identity. const REG_FONT_WRAPPERS: &str = "__benilla_font_wrappers"; @@ -206,11 +206,15 @@ pub(super) fn id_of_table(model: &Model, t: &Table) -> Option { } } -/// The font `this` is, for a Font method's receiver. +/// The font `this` is, for a Font method's receiver, with the member prologue's raises: no object +/// at `[0]`, or one that is no Font (`0x79fda0`..`0x7a0e70`). fn id_of(lua: &Lua, this: &Table) -> mlua::Result { + let id = super::object::decode_id(this)?; let model = lua.app_data_ref::().expect("model"); - id_of_table(&model, this) - .ok_or_else(|| mlua::Error::runtime("not a font object (missing T[0] font identity)")) + model + .fonts + .of_handle(id) + .ok_or_else(|| mlua::Error::runtime(super::object::ERR_WRONG_TYPE)) } /// Which font verb an argument error names. diff --git a/crates/benilla-ui/src/script/loot.rs b/crates/benilla-ui/src/script/loot.rs index 9c3233487..746cdcb37 100644 --- a/crates/benilla-ui/src/script/loot.rs +++ b/crates/benilla-ui/src/script/loot.rs @@ -993,6 +993,7 @@ mod tests { s.run(r#"b = CreateFrame("Button", "PlainB", UIParent)"#) .unwrap(); let e = s.run("LB1.SetSlot(b, 1)").unwrap_err().to_string(); - assert!(e.contains("not a LootButton"), "{e}"); + // A Button fails the LootButton type test (`0x4c18ee`, `0x495ab0`). + assert!(e.contains("Wrong object type for member function"), "{e}"); } } diff --git a/crates/benilla-ui/src/script/mod.rs b/crates/benilla-ui/src/script/mod.rs index 61c89ae97..c24765981 100644 --- a/crates/benilla-ui/src/script/mod.rs +++ b/crates/benilla-ui/src/script/mod.rs @@ -793,6 +793,7 @@ impl UiScript { pub fn new() -> mlua::Result { let lua = install_framescript(VmKind::InGame)?; install_in_game(&lua)?; + object::guard_receivers(&lua)?; Ok(Self::host(lua)) } @@ -804,6 +805,7 @@ impl UiScript { pub fn new_glue() -> mlua::Result { let lua = install_framescript(VmKind::Glue)?; glue::install(&lua)?; + object::guard_receivers(&lua)?; Ok(Self::host(lua)) } diff --git a/crates/benilla-ui/src/script/model.rs b/crates/benilla-ui/src/script/model.rs index 3e5f51827..02b49ddd1 100644 --- a/crates/benilla-ui/src/script/model.rs +++ b/crates/benilla-ui/src/script/model.rs @@ -148,6 +148,9 @@ pub(crate) struct Model { /// A path's texel size, which an axis authored as 0 takes, one texel per unit, as the client's /// `GetWidth` (`0x770720`) and `GetHeight` (`0x770790`) do; `None` leaves it as authored. pub(crate) texture_size_probe: Option, + /// The size of a picture the cursor code opens (`0x449610`), which `SetCursor`'s custom + /// cursor must have at 32 by 32 (`0x523cb9`); `None` loads none. + pub(crate) cursor_size_probe: Option, /// Whether a font path loads: `SetFont`'s 1 or nil, nil meaning a load failure (`0x79f345`, /// `0x79f361`, from `0x5c1ae0` in the `0x44d040` cache). Unlike `texture_probe`, `None` answers /// 1 for a non-empty path: without a font backend nothing failed, and addons revert their font @@ -1400,6 +1403,7 @@ impl Model { texture_probe: None, world_loc_projector: None, texture_size_probe: None, + cursor_size_probe: None, font_probe: None, addons_saved_account: None, addons_saved_character: None, diff --git a/crates/benilla-ui/src/script/object.rs b/crates/benilla-ui/src/script/object.rs index 1cb91bdfc..4648c14e5 100644 --- a/crates/benilla-ui/src/script/object.rs +++ b/crates/benilla-ui/src/script/object.rs @@ -36,17 +36,25 @@ pub(super) fn id_to_lud(id: u32) -> LightUserData { LightUserData(id as usize as *mut c_void) } -/// Read the id out of a wrapper table's `T[0]` lightuserdata (`0x701bd0` writes it). +/// The member prologue's three lines for a bad receiver (`Frame:Show` `0x775750`, +/// `Texture:IsShown` `0x79b9b0`, the Font methods from `0x79fda0`): no table (`0x847ef8`), a table +/// with no object at `[0]` (`0x847ec0`), an object that fails the class's type test (`0x847e98`). +pub(crate) const ERR_NON_TABLE: &str = + "Attempt to find 'this' in non-table object (used '.' instead of ':' ?)"; +pub(crate) const ERR_NO_OBJECT: &str = "Attempt to find 'this' in non-framescript object"; +pub(crate) const ERR_WRONG_TYPE: &str = "Wrong object type for member function"; + +/// Read the id out of a wrapper table's `T[0]` lightuserdata (`0x701bd0` writes it); a table with +/// none raises the member prologue's line for it ([`ERR_NO_OBJECT`]). pub(crate) fn decode_id(this: &Table) -> mlua::Result { match this.raw_get::(0)? { Value::LightUserData(l) => Ok(l.0 as usize as u32), - _ => Err(mlua::Error::runtime( - "not a benilla frame/region object (missing T[0] identity)", - )), + _ => Err(mlua::Error::runtime(ERR_NO_OBJECT)), } } -/// Resolve `self` (a frame wrapper) to its live [`FrameHandle`]. +/// Resolve `self` (a frame wrapper) to its live [`FrameHandle`]; an object that is no frame fails +/// the Frame type test ([`ERR_WRONG_TYPE`]). pub(super) fn frame_handle_of(lua: &Lua, this: &Table) -> mlua::Result { let id = decode_id(this)?; let model = lua.app_data_ref::().expect("model app_data"); @@ -54,7 +62,209 @@ pub(super) fn frame_handle_of(lua: &Lua, this: &Table) -> mlua::Result bool { + match self { + Class::Frame => model.id_to_frame.contains_key(&id), + Class::FrameKind(table) => model + .id_to_frame + .get(&id) + .and_then(|&h| model.arena.frame(h)) + .is_some_and(|f| kind_method_registries(Some(f.kind)).contains(&table)), + Class::Region(kind) => model + .id_to_region + .get(&id) + .and_then(|&rh| model.arena.region(rh)) + .is_some_and(|r| r.kind == kind), + Class::Widget => { + model.id_to_frame.contains_key(&id) || model.id_to_region.contains_key(&id) + } + Class::Font => model.fonts.of_handle(id).is_some(), + } + } +} + +/// The methods whose reference opens with no member prologue, so they keep their own order: +/// `(table, name)`. Every other method of the tables [`guard_receivers`] reaches opens with it, +/// read at each function the reference's pair tables name (`0x878ec0` and the rest). +const NO_PROLOGUE: &[(&str, &str)] = &[ + // No receiver read at all. + (super::minimap::REG_MINIMAP_METHODS, "GetZoomLevels"), // 0x4eebe0 + (super::minimap::REG_MINIMAP_METHODS, "GetZoom"), // 0x4eec20 + (super::minimap::REG_MINIMAP_METHODS, "SetZoom"), // 0x4eec60 + (super::minimap::REG_MINIMAP_METHODS, "GetPingPosition"), // 0x4eefd0 + (super::tabard::REG_TABARDMODEL_METHODS, "CanSaveTabardNow"), // 0x503910 + // An argument is read first, and the prologue runs only after it passes. + (super::minimap::REG_MINIMAP_METHODS, "PingLocation"), // 0x4eeca0: 0x4eed0b, 0x4eed1f + (super::tooltip::REG_TOOLTIP_METHODS, "SetBuybackItem"), // 0x536300: 0x536322 + ( + super::messageframe::REG_SCROLLINGMESSAGEFRAME_METHODS, + "SetScrollFromBottom", + ), // 0x793070: 0x793078 +]; + +/// Put the member prologue in front of every host method of every widget method table: a +/// receiver that is no table (`0x847ef8`), holds no object (`0x847ec0`) or fails the table's +/// [`Class`] (`0x847e98`) raises its line before the method converts an argument. Left as they +/// are: the [`NO_PROLOGUE`] methods, and each of the Region table's names +/// ([`super::REGION_MAP_METHODS`]), one function every widget table shares, which checks its own +/// receiver ([`super::region_map::install`]). Runs once, after the last table is built. +pub(super) fn guard_receivers(lua: &Lua) -> mlua::Result<()> { + use crate::widget::RegionKind; + let mut tables: Vec<(&'static str, Class)> = vec![ + (REG_FRAME_METHODS, Class::Frame), + (super::REG_REGION_METHODS, Class::Widget), + ( + super::REG_TEXTURE_METHODS, + Class::Region(RegionKind::Texture), + ), + ( + super::REG_FONTSTRING_METHODS, + Class::Region(RegionKind::FontString), + ), + (super::REG_TITLE_METHODS, Class::Region(RegionKind::Title)), + (super::font::REG_FONT_METHODS, Class::Font), + ]; + for kind in every_frame_kind() { + for &table in kind_method_registries(Some(kind)) { + if !tables.iter().any(|(t, _)| *t == table) { + tables.push((table, Class::FrameKind(table))); + } + } + } + let region: Table = lua.named_registry_value(super::REG_REGION_METHODS)?; + let shared: Vec = super::REGION_MAP_METHODS + .iter() + .map(|name| region.raw_get::(*name)) + .collect::>()?; + for (key, class) in tables { + let Value::Table(methods) = lua.named_registry_value::(key)? else { + continue; + }; + let entries: Vec<(Value, Value)> = methods + .pairs::() + .collect::>()?; + for (name, method) in entries { + if shared.contains(&method) { + continue; + } + if let Value::String(n) = &name { + let n = n.to_string_lossy(); + if NO_PROLOGUE.iter().any(|&(t, m)| t == key && m == n) { + continue; + } + } + let Value::Function(method) = method else { + continue; + }; + let guarded = lua.guard_receiver(&method, move |lua, receiver| match receiver { + mlua::Receiver::NotTable => Err(mlua::Error::runtime(ERR_NON_TABLE)), + mlua::Receiver::NoObject => Err(mlua::Error::runtime(ERR_NO_OBJECT)), + mlua::Receiver::Object(p) => { + let model = lua.app_data_ref::().expect("model app_data"); + if class.admits(&model, p as u32) { + Ok(()) + } else { + Err(mlua::Error::runtime(ERR_WRONG_TYPE)) + } + } + })?; + if let Some(guarded) = guarded { + methods.raw_set(name, guarded)?; + } + } + } + Ok(()) +} + +/// The member prologue for a [`NO_PROLOGUE`] method that runs it late, after its own argument +/// checks: `this` must be a table holding a frame of a kind whose method chain reaches `table`. +pub(crate) fn receiver_in(lua: &Lua, this: &Value, table: &'static str) -> mlua::Result { + let Value::Table(t) = this else { + return Err(mlua::Error::runtime(ERR_NON_TABLE)); + }; + let id = decode_id(t)?; + let model = lua.app_data_ref::().expect("model app_data"); + if Class::FrameKind(table).admits(&model, id) { + Ok(t.clone()) + } else { + Err(mlua::Error::runtime(ERR_WRONG_TYPE)) + } +} + +/// Every frame kind, so [`guard_receivers`] reaches every kind's method tables. The match makes +/// a new kind a compile error until it is listed here. +fn every_frame_kind() -> [FrameKind; 20] { + let kinds = [ + FrameKind::Frame, + FrameKind::WorldFrame, + FrameKind::Button, + FrameKind::LootButton, + FrameKind::CheckButton, + FrameKind::EditBox, + FrameKind::StatusBar, + FrameKind::Slider, + FrameKind::ScrollFrame, + FrameKind::Model, + FrameKind::PlayerModel, + FrameKind::DressUpModel, + FrameKind::TabardModel, + FrameKind::MessageFrame, + FrameKind::ScrollingMessageFrame, + FrameKind::ColorSelect, + FrameKind::SimpleHtml, + FrameKind::MovieFrame, + FrameKind::GameTooltip, + FrameKind::Minimap, + ]; + for kind in kinds { + match kind { + FrameKind::Frame + | FrameKind::WorldFrame + | FrameKind::Button + | FrameKind::LootButton + | FrameKind::CheckButton + | FrameKind::EditBox + | FrameKind::StatusBar + | FrameKind::Slider + | FrameKind::ScrollFrame + | FrameKind::Model + | FrameKind::PlayerModel + | FrameKind::DressUpModel + | FrameKind::TabardModel + | FrameKind::MessageFrame + | FrameKind::ScrollingMessageFrame + | FrameKind::ColorSelect + | FrameKind::SimpleHtml + | FrameKind::MovieFrame + | FrameKind::GameTooltip + | FrameKind::Minimap => {} + } + } + kinds } // ───────────────────────────────────────────────────────────────────────────────────────────── @@ -816,3 +1026,94 @@ mod fullscreen_scale_tests { } } } + +#[cfg(test)] +mod receiver_tests { + use crate::script::UiScript; + use mlua::{MultiValue, Table, Value}; + + /// The registry table that holds a reference method table's methods, by its address. + fn registry_key(table: &str) -> &'static str { + use crate::script as s; + match table { + "0x878ec0" => s::REG_FRAME_METHODS, + "0x87c9b8" => s::REG_REGION_METHODS, + "0x87c128" => s::REG_TEXTURE_METHODS, + "0x87c1d8" => s::REG_FONTSTRING_METHODS, + "0x87c7c8" => s::font::REG_FONT_METHODS, + "0x879d00" => s::button::REG_BUTTON_METHODS, + "0x87bf74" => s::button::REG_CHECKBUTTON_METHODS, + "0x847ce4" => s::loot::REG_LOOTBUTTON_METHODS, + "0x87bb68" => s::editbox::REG_EDITBOX_METHODS, + "0x87b010" => s::statusbar::REG_STATUSBAR_METHODS, + "0x87b260" => s::slider::REG_SLIDER_METHODS, + "0x87b3c0" => s::scrollframe::REG_SCROLLFRAME_METHODS, + "0x87b5c0" => s::messageframe::REG_SCROLLINGMESSAGEFRAME_METHODS, + "0x87b960" => s::messageframe::REG_MESSAGEFRAME_METHODS, + "0x87ba80" => s::simplehtml::REG_SIMPLEHTML_METHODS, + "0x87abb0" => s::colorselect::REG_COLORSELECT_METHODS, + "0x87ab4c" => s::movieframe::REG_MOVIEFRAME_METHODS, + "0x878948" => s::modelframe::REG_MODEL_METHODS, + "0x84f1fc" => s::modelframe::REG_PLAYERMODEL_METHODS, + "0x84f190" => s::dressup::REG_DRESSUPMODEL_METHODS, + "0x84ee40" => s::tabard::REG_TABARDMODEL_METHODS, + "0x854198" => s::tooltip::REG_TOOLTIP_METHODS, + "0x84c538" => s::minimap::REG_MINIMAP_METHODS, + other => panic!("no registry table for the reference's method table {other}"), + } + } + + /// The eight methods whose reference opens with no member prologue, by table and name: the + /// Minimap's four getters and setter (`0x4eebe0`, `0x4eec20`, `0x4eec60`, `0x4eefd0`), + /// `CanSaveTabardNow` (`0x503910`), and three that read an argument first, `PingLocation` + /// (`0x4eeca0`), `SetBuybackItem` (`0x536300`) and `SetScrollFromBottom` (`0x793070`). + const NO_PROLOGUE: [(&str, &str); 8] = [ + ("0x84c538", "GetZoomLevels"), + ("0x84c538", "GetZoom"), + ("0x84c538", "SetZoom"), + ("0x84c538", "GetPingPosition"), + ("0x84c538", "PingLocation"), + ("0x84ee40", "CanSaveTabardNow"), + ("0x854198", "SetBuybackItem"), + ("0x87b5c0", "SetScrollFromBottom"), + ]; + + /// Every widget method of `reference/bindings.tsv` is in its table and, called with no + /// receiver, raises the member prologue's first line (`0x847ef8`) before anything else; the + /// eight without a prologue raise something else or nothing. A method that is missing, or one + /// the receiver check passed over, fails by name. + #[test] + fn every_reference_widget_method_opens_with_the_prologue() { + let s = UiScript::new().unwrap(); + let lua = s.lua(); + let tsv = concat!(env!("CARGO_MANIFEST_DIR"), "/../../reference/bindings.tsv"); + let text = std::fs::read_to_string(tsv).expect("reference/bindings.tsv"); + let mut failures = Vec::new(); + let mut checked = 0; + for line in text.lines().skip(1) { + let f: Vec<&str> = line.split('\t').collect(); + if f.get(4) != Some(&"widget") { + continue; + } + let (name, table) = (f[0], f[3]); + let methods: Table = lua.named_registry_value(registry_key(table)).unwrap(); + let Ok(Value::Function(method)) = methods.raw_get::(name) else { + failures.push(format!("{table} {name}: not in its table")); + continue; + }; + checked += 1; + let raised = method + .call::(()) + .err() + .map(|e| e.to_string()) + .unwrap_or_default(); + let prologue = raised.contains(super::ERR_NON_TABLE); + let excepted = NO_PROLOGUE.contains(&(table, name)); + if prologue == excepted { + failures.push(format!("{table} {name}: raised {raised:?}")); + } + } + assert!(checked > 450, "only {checked} methods checked"); + assert!(failures.is_empty(), "{failures:#?}"); + } +} diff --git a/crates/benilla-ui/src/script/region.rs b/crates/benilla-ui/src/script/region.rs index 0bbb9e7a6..b858ee51f 100644 --- a/crates/benilla-ui/src/script/region.rs +++ b/crates/benilla-ui/src/script/region.rs @@ -13,7 +13,8 @@ use super::{ use crate::layout::{Anchor, Anchors, Len}; use crate::widget::{RegionHandle, RegionKind}; -/// Resolve `self` (a region wrapper) to its live [`RegionHandle`]. +/// Resolve `self` (a region wrapper) to its live [`RegionHandle`]; an object that is no region +/// fails the type test ([`super::object::ERR_WRONG_TYPE`]). pub(crate) fn region_handle_of(lua: &Lua, this: &Table) -> mlua::Result { let id = decode_id(this)?; let model = lua.app_data_ref::().expect("model app_data"); @@ -21,7 +22,7 @@ pub(crate) fn region_handle_of(lua: &Lua, this: &Table) -> mlua::Result bool { } /// Argument 1 of a global that takes a Texture as its `this` (`SetLootPortrait` `0x4c2b40`, -/// `SetInventoryPortaitTexture` `0x4c9150`), with the member prologue's three raises: a non-table +/// `SetInventoryPortaitTexture` `0x4c9150`, `SetBagPortaitTexture` `0x4fa4f0`, +/// `SetPortraitTexture` `0x519ef0`, `SetTaxiMap` `0x4dca50`), with the member prologue's three raises: a non-table /// (`0x847ef8`), a table with no object at `[0]` (`0x847ec0`), and any object but a Texture, the /// `IsA` test against the Texture class token `[0xcf4cdc]` (`0x847e98`). pub(super) fn this_texture(lua: &Lua, this: &Value) -> mlua::Result { + use super::object::{ERR_NON_TABLE, ERR_NO_OBJECT, ERR_WRONG_TYPE}; let Value::Table(t) = this else { - return Err(mlua::Error::runtime( - "Attempt to find 'this' in non-table object (used '.' instead of ':' ?)", - )); + return Err(mlua::Error::runtime(ERR_NON_TABLE)); }; if decode_id(t).is_err() { - return Err(mlua::Error::runtime( - "Attempt to find 'this' in non-framescript object", - )); + return Err(mlua::Error::runtime(ERR_NO_OBJECT)); } - let wrong = || mlua::Error::runtime("Wrong object type for member function"); + let wrong = || mlua::Error::runtime(ERR_WRONG_TYPE); let rh = region_handle_of(lua, t).map_err(|_| wrong())?; let model = lua.app_data_ref::().expect("model app_data"); if model.arena.region(rh).map(|r| r.kind) != Some(RegionKind::Texture) { @@ -390,6 +389,42 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { Ok(()) } +/// `SetPortraitToTexture`'s target (`0x48d780`): a name looked up as a global, which must hold a +/// Texture (`0x76c760`), else `0x842c98`'s line; or a table, whose `[0]` must hold an object +/// (`0x842c58`) that is a Texture (`0x842c1c`). +fn portrait_target(lua: &Lua, target: &Value) -> mlua::Result { + let is_texture = |model: &Model, id: u32| { + model + .id_to_region + .get(&id) + .copied() + .filter(|&rh| model.arena.region(rh).map(|r| r.kind) == Some(RegionKind::Texture)) + }; + if let Some(name) = super::binding_abi::optional_string(lua, target) { + let found = super::object::prefetch_named_target(lua, &name, None); + let model = lua.app_data_ref::().expect("model"); + return super::object::resolve_named_target(&model, &found) + .and_then(|id| is_texture(&model, id)) + .ok_or_else(|| { + mlua::Error::runtime(format!( + "SetPortraitToTexture(): Couldn't find texture named '{name}'" + )) + }); + } + let Value::Table(t) = target else { + return Err(mlua::Error::runtime( + "SetPortraitToTexture(): Couldn't find texture named '(null)'", + )); + }; + let id = decode_id(t).map_err(|_| { + mlua::Error::runtime("SetPortraitToTexture(): Couldn't find 'this' in texture object") + })?; + let model = lua.app_data_ref::().expect("model"); + is_texture(&model, id).ok_or_else(|| { + mlua::Error::runtime("SetPortraitToTexture(): Wrong object type, expected texture") + }) +} + /// The two portrait globals, which only the in-game state registers (`SetPortraitTexture` in /// table `0x850438`, `SetPortraitToTexture` in `0x83de68`). pub(super) fn install_in_game(lua: &Lua) -> mlua::Result<()> { @@ -398,16 +433,17 @@ pub(super) fn install_in_game(lua: &Lua) -> mlua::Result<()> { // or `SetPortraitToTexture` clears it. lua.globals().set( "SetPortraitTexture", - lua.create_function(|lua, (region, unit): (Table, Value)| { - // A non-string unit raises this exact error (`0x519fb4`, `0x8513b8`), which stock - // `Blizzard_InspectUI.lua:49` hits on a re-open; a token that resolves to nothing only - // blanks the portrait. + lua.create_function(|lua, (region, unit): (Value, Value)| { + // The texture first, the member prologue against the Texture id (`0x519f06`- + // `0x519faa`); then a non-string unit raises this exact error (`0x519fb4`, + // `0x8513b8`), which stock `Blizzard_InspectUI.lua:49` hits on a re-open. A token that + // resolves to nothing only blanks the portrait. + let rh = this_texture(lua, ®ion)?; let unit = crate::script::binding_abi::string_arg( lua, unit, r#"Usage: SetPortraitTexture(texture, "unit")"#, )?; - let rh = region_handle_of(lua, ®ion)?; let mut model = lua.app_data_mut::().expect("model"); model.set_texel(rh, super::texel::TexSet::Own(None)); let data = model.region_data.entry(rh).or_default(); @@ -421,20 +457,23 @@ pub(super) fn install_in_game(lua: &Lua) -> mlua::Result<()> { })?, )?; - // SetPortraitToTexture(textureName, path), an engine global: sets the texture, drawn masked - // to its inscribed circle, and drops any unit binding. It takes the name, as both stock - // callers pass (`ContainerFrame.lua:419`, `MailFrame.lua:174`); whether the reference also - // takes a region object is untraced. + // SetPortraitToTexture(target, path) (`0x48d780`), an engine global: sets the texture, drawn + // masked to its inscribed circle, and drops any unit binding. The target is a name, a string or + // a number (`lua_isstring`, `0x48d789`), read as a global that must hold a Texture (`0x76c760` + // at `0x48d7bf`), or a table (`lua_type` 5, `0x48d7fa`) holding one; anything else raises the + // name line with `lua_tostring`'s null (`0x48d7ce`). A path that is no string or number returns + // with the texture left alone (`0x48d886`). lua.globals().set( "SetPortraitToTexture", - lua.create_function(|lua, (name, path): (String, String)| { + lua.create_function(|lua, args: MultiValue| { + let mut args = args.into_iter(); + let target = args.next().unwrap_or(Value::Nil); + let path = args.next().unwrap_or(Value::Nil); + let rh = portrait_target(lua, &target)?; + let Some(path) = super::binding_abi::optional_string(lua, &path) else { + return Ok(()); + }; let mut model = lua.app_data_mut::().expect("model"); - let Some(id) = model.region_by_name.get(&name).copied() else { - return Ok(()); - }; - let Some(rh) = model.id_to_region.get(&id).copied() else { - return Ok(()); - }; model.set_texel(rh, super::texel::TexSet::Portrait(path)); let data = model.region_data.entry(rh).or_default(); data.circular = true; diff --git a/crates/benilla-ui/src/script/region_map.rs b/crates/benilla-ui/src/script/region_map.rs index 2fce44ce1..8956f3a89 100644 --- a/crates/benilla-ui/src/script/region_map.rs +++ b/crates/benilla-ui/src/script/region_map.rs @@ -38,7 +38,7 @@ pub(super) enum Side { Region, } -/// `Err` for a table that is no widget wrapper; `Ok(None)` for a wrapper whose widget is gone. +/// `Err` for a table that holds no object; `Ok(None)` for an object that is no widget. fn side_of(lua: &Lua, this: &Table) -> mlua::Result> { let id = decode_id(this)?; let model = lua.app_data_ref::().expect("model app_data"); @@ -127,19 +127,18 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { let shared = lua.create_function(move |lua, args: MultiValue| { // The receiver is argument 1, borrowed: a `Value::Table` clone would register a second // ref-thread reference on the hottest verbs. + // The member prologue (`0x7a2030`'s, as every method's): no table, no object at + // `[0]`, an object that is no widget, each its own line. let side = { let Some(Value::Table(this)) = args.iter().next() else { - return Err(mlua::Error::runtime( - "expected a frame or region as the first argument", - )); + return Err(mlua::Error::runtime(super::object::ERR_NON_TABLE)); }; side_of(lua, this)? }; match side { Some(Side::Frame) => on_frame(lua, args), Some(Side::Region) => on_region(lua, args), - // A wrapper whose widget is gone: one message, since its kind is unknown. - None => Err(mlua::Error::runtime("stale or invalid widget handle")), + None => Err(mlua::Error::runtime(super::object::ERR_WRONG_TYPE)), } })?; frame.set(name, shared.clone())?; diff --git a/crates/benilla-ui/src/script/tests/button.rs b/crates/benilla-ui/src/script/tests/button.rs index bfe1843b7..a42a4bd6f 100644 --- a/crates/benilla-ui/src/script/tests/button.rs +++ b/crates/benilla-ui/src/script/tests/button.rs @@ -855,7 +855,7 @@ fn set_font_string_adopts_the_label_and_raises_on_anything_else() { assert!(s.eval::("return b:GetFontString() == fs2").unwrap()); let err = s.run("fs:GetText()").unwrap_err().to_string(); assert!( - err.contains("stale") || err.contains("invalid"), + err.contains("Wrong object type for member function"), "the replaced label must be destroyed, not left live: {err}" ); diff --git a/crates/benilla-ui/src/script/tests/region_map.rs b/crates/benilla-ui/src/script/tests/region_map.rs index 0f308e3cd..9c34ee29e 100644 --- a/crates/benilla-ui/src/script/tests/region_map.rs +++ b/crates/benilla-ui/src/script/tests/region_map.rs @@ -132,7 +132,8 @@ fn the_six_look_alikes_are_not_shared() { } } -/// The bridge resolves the receiver before either arm runs, and its error names the reason. +/// The bridge resolves the receiver before either arm runs, with the member prologue's line for a +/// table holding no object (`0x847ec0`, read at `0x7a2098` in `GetHeight`). #[test] fn a_non_widget_receiver_raises_and_names_the_reason() { let s = vm(); @@ -140,5 +141,8 @@ fn a_non_widget_receiver_raises_and_names_the_reason() { .eval::("return Host.GetHeight({})") .unwrap_err() .to_string(); - assert!(err.contains("T[0] identity"), "unexpected error: {err}"); + assert!( + err.contains("Attempt to find 'this' in non-framescript object"), + "unexpected error: {err}" + ); } diff --git a/crates/benilla-ui/src/script/tests/regions.rs b/crates/benilla-ui/src/script/tests/regions.rs index 55699d803..fe69d986f 100644 --- a/crates/benilla-ui/src/script/tests/regions.rs +++ b/crates/benilla-ui/src/script/tests/regions.rs @@ -1026,11 +1026,157 @@ fn set_portrait_to_texture_is_a_global_taking_a_name() { "nil", "1.12 has no Texture:SetPortraitToTexture — it is a global" ); - // An unknown name does not raise here; the reference raises "Couldn't find texture named" - // (`0x48d7db`). - s.run(r#"SetPortraitToTexture("NoSuchPortrait", "Interface\\X")"#) + // An unknown name raises (`0x48d7db`). + assert!(s + .run(r#"SetPortraitToTexture("NoSuchPortrait", "Interface\\X")"#) + .is_err()); +} + +/// `SetPortraitToTexture(target, path)` (`0x48d780`) takes a name, a string or a number looked up +/// as a global holding a Texture (`0x76c760` at `0x48d7bf`), or a Texture object (`lua_type` 5 at +/// `0x48d7fa`). Each failure raises its own line (`0x842c98`, `0x842c58`, `0x842c1c`), a target +/// that is neither naming `(null)`; a path that is no string or number returns with the texture +/// left alone (`0x48d886`). +#[test] +fn set_portrait_to_texture_takes_a_texture_object_and_ignores_a_bad_path() { + let s = crate::script::UiScript::new().unwrap(); + s.run( + r#" + PortHost = CreateFrame("Frame", "PortHost") + Port = PortHost:CreateTexture("PortHostPortrait", "ARTWORK") + PortStr = PortHost:CreateFontString("PortHostText") + PortAlias = Port + "#, + ) + .unwrap(); + let texture = |s: &UiScript| { + s.eval::>("return Port:GetTexture()") + .unwrap() + }; + s.run(r#"SetPortraitToTexture(Port, "Interface\\Icons\\A")"#) .unwrap(); - assert!(s.errors().is_empty()); + assert_eq!(texture(&s).as_deref(), Some("Interface\\Icons\\A")); + for keep in [ + "SetPortraitToTexture(Port, nil)", + "SetPortraitToTexture(Port)", + r#"SetPortraitToTexture("PortHostPortrait", {})"#, + r#"SetPortraitToTexture("PortHostPortrait", true)"#, + ] { + s.run(keep).unwrap(); + assert_eq!( + texture(&s).as_deref(), + Some("Interface\\Icons\\A"), + "{keep}" + ); + } + s.run("SetPortraitToTexture(Port, 5)").unwrap(); + assert_eq!(texture(&s).as_deref(), Some("5"), "a number is its text"); + // Any global that holds the texture, not only its published name. + s.run(r#"SetPortraitToTexture("PortAlias", "Interface\\Icons\\B")"#) + .unwrap(); + assert_eq!(texture(&s).as_deref(), Some("Interface\\Icons\\B")); + + for (call, line) in [ + ( + r#"SetPortraitToTexture("NoSuchPortrait", "X")"#, + "SetPortraitToTexture(): Couldn't find texture named 'NoSuchPortrait'", + ), + ( + r#"SetPortraitToTexture("PortHost", "X")"#, + "SetPortraitToTexture(): Couldn't find texture named 'PortHost'", + ), + ( + r#"SetPortraitToTexture(nil, "X")"#, + "SetPortraitToTexture(): Couldn't find texture named '(null)'", + ), + ( + r#"SetPortraitToTexture(true, "X")"#, + "SetPortraitToTexture(): Couldn't find texture named '(null)'", + ), + ( + r#"SetPortraitToTexture({}, "X")"#, + "SetPortraitToTexture(): Couldn't find 'this' in texture object", + ), + ( + r#"SetPortraitToTexture(PortHost, "X")"#, + "SetPortraitToTexture(): Wrong object type, expected texture", + ), + ( + r#"SetPortraitToTexture(PortStr, "X")"#, + "SetPortraitToTexture(): Wrong object type, expected texture", + ), + ] { + let err = s.run(call).unwrap_err().to_string(); + assert!(err.contains(line), "{call}: {err}"); + } + assert_eq!(texture(&s).as_deref(), Some("Interface\\Icons\\B")); +} + +/// A method's receiver resolves through the member prologue's checks (`Frame:Show` `0x775750`, +/// `Texture:IsShown` `0x79b9b0`, `Button:SetFontString` `0x780ad9`, the Font methods from +/// `0x79fda0`, the Region methods' `0x7a2030`): a receiver that is no table raises `0x847ef8`'s +/// line, a table holding no object at `[0]` `0x847ec0`'s, and an object of another class +/// `0x847e98`'s. +#[test] +fn a_bad_method_receiver_raises_the_member_prologues_lines() { + let s = crate::script::UiScript::new().unwrap(); + s.run( + r#" + RecvFrame = CreateFrame("Frame", "RecvFrame") + RecvButton = CreateFrame("Button", "RecvButton") + RecvTex = RecvFrame:CreateTexture("RecvTex") + RecvStr = RecvFrame:CreateFontString("RecvStr") + RecvFont = CreateFont("RecvFont") + "#, + ) + .unwrap(); + const NON_TABLE: &str = + "Attempt to find 'this' in non-table object (used '.' instead of ':' ?)"; + const NO_OBJECT: &str = "Attempt to find 'this' in non-framescript object"; + const WRONG: &str = "Wrong object type for member function"; + for (call, line) in [ + ("RecvFrame.GetName(nil)", NON_TABLE), + ("RecvTex.GetHeight(5)", NON_TABLE), + ("RecvFrame.Show()", NON_TABLE), + ("RecvFrame.Show(5)", NON_TABLE), + ("RecvFrame.Show('RecvFrame')", NON_TABLE), + ("RecvTex.IsShown(nil)", NON_TABLE), + ("RecvButton.GetText(nil)", NON_TABLE), + ("RecvFont.GetName(nil)", NON_TABLE), + ("RecvButton.GetText({})", NO_OBJECT), + ("RecvTex.IsShown(RecvStr)", WRONG), + ("RecvTex.SetTexture(RecvStr, 'X')", WRONG), + ("RecvStr.IsShown(RecvTex)", WRONG), + ("RecvStr.SetText(RecvTex, 'x')", WRONG), + ("RecvButton.GetText(RecvFrame)", WRONG), + ("RecvFrame.Show({})", NO_OBJECT), + ("RecvTex.IsShown({})", NO_OBJECT), + ("RecvFont.GetName({})", NO_OBJECT), + ("RecvFrame.GetName({})", NO_OBJECT), + ("RecvFrame.Show(RecvTex)", WRONG), + ("RecvFrame.Show(RecvFont)", WRONG), + ("RecvTex.IsShown(RecvFrame)", WRONG), + ("RecvFont.GetName(RecvFrame)", WRONG), + ("RecvFont.GetName(RecvStr)", WRONG), + ("RecvFrame.GetName(RecvFont)", WRONG), + ] { + let err = s.run(call).unwrap_err().to_string(); + assert!(err.contains(line), "{call}: {err}"); + } + // The right receivers still answer, a method taken off one class's table included where the + // class admits it: a Button is a Frame, and the Region methods take any widget. + assert!(s + .eval::("RecvFrame.Show(RecvButton) return RecvButton:IsShown() == 1") + .unwrap()); + assert_eq!( + s.eval::("return RecvFrame.GetName(RecvTex)") + .unwrap(), + "RecvTex" + ); + assert_eq!( + s.eval::("return RecvFont:GetName()").unwrap(), + "RecvFont" + ); } /// `Region:GetWidth`/`GetHeight` (`0x7a1e00`/`0x7a2030`) call the virtual size getters the rect @@ -1740,3 +1886,142 @@ fn an_engine_vertex_colour_collapses_a_gradient() { "{color:?}" ); } + +/// Four globals resolve argument 1 with the member prologue against the Texture id `[0xcf4cdc]` +/// before reading another argument: `SetPortraitTexture` (`0x519f06`-`0x519faa`, the unit after +/// at `0x519fb4`), `SetBagPortaitTexture` (`0x4fa4f9`, the slot after at `0x4fa585`), +/// `SetInventoryPortaitTexture` (`0x4c9159`) and `SetTaxiMap` (`0x4dca67`, once its map has +/// loaded). A FontString fails the test (its `IsA`, `0x773550`, answers the FontString and Region +/// ids alone). +#[test] +fn the_texture_globals_refuse_a_non_texture_first() { + let mut s = crate::script::UiScript::new().unwrap(); + s.run( + r#" + GlobHost = CreateFrame("Frame", "GlobHost") + GlobTex = GlobHost:CreateTexture("GlobTex") + GlobStr = GlobHost:CreateFontString("GlobStr") + "#, + ) + .unwrap(); + s.set_taxi(Some(TaxiUiState { + art: "Interface\\TaxiFrame\\TAXIMAP1".into(), + nodes: vec![], + })); + const NON_TABLE: &str = + "Attempt to find 'this' in non-table object (used '.' instead of ':' ?)"; + const NO_OBJECT: &str = "Attempt to find 'this' in non-framescript object"; + const WRONG: &str = "Wrong object type for member function"; + for (call, line) in [ + ("SetPortraitTexture(GlobStr, 'player')", WRONG), + ("SetPortraitTexture(GlobStr, nil)", WRONG), + ("SetPortraitTexture(GlobHost, 'player')", WRONG), + ("SetPortraitTexture({}, nil)", NO_OBJECT), + ("SetPortraitTexture(5, nil)", NON_TABLE), + ( + "SetPortraitTexture(GlobTex, nil)", + "Usage: SetPortraitTexture(texture, \"unit\")", + ), + ("SetBagPortaitTexture(GlobStr, 1)", WRONG), + ("SetBagPortaitTexture(GlobStr, 'x')", WRONG), + ("SetBagPortaitTexture({}, 'x')", NO_OBJECT), + ("SetBagPortaitTexture(nil, 'x')", NON_TABLE), + ( + "SetBagPortaitTexture(GlobTex, 'x')", + "Usage: SetBagPortaitTexture(texture, slot)", + ), + ("SetInventoryPortaitTexture(GlobStr, 'player', 1)", WRONG), + ("SetInventoryPortaitTexture(GlobStr, nil, 1)", WRONG), + ("SetTaxiMap(GlobStr)", WRONG), + ] { + let err = s.run(call).unwrap_err().to_string(); + assert!(err.contains(line), "{call}: {err}"); + } + s.run("SetPortraitTexture(GlobTex, 'player') SetBagPortaitTexture(GlobTex, 0)") + .unwrap(); +} + +/// `GameTooltip:AddFontStrings(left, right)` (`0x530c40`) reads arguments 2 and 3 in turn: a +/// non-table raises the usage line (`0x85506c`), a table with no object `0x855034`'s, and an +/// object that fails the FontString test `[0xcf2ccc]` (`0x530d2f`-`0x530d4d`) `0x854ff8`'s, each +/// with the tooltip's name or ``. +#[test] +fn add_font_strings_takes_only_font_strings() { + let s = script(); + s.run( + r#" + FsTip = CreateFrame("GameTooltip", "FsTip") + FsAnon = CreateFrame("GameTooltip") + FsLeft = FsTip:CreateFontString("FsLeft") + FsRight = FsTip:CreateFontString("FsRight") + FsTex = FsTip:CreateTexture("FsTex") + "#, + ) + .unwrap(); + for (call, line) in [ + ( + "FsTip:AddFontStrings(FsTex, FsRight)", + "FsTip:AddFontStrings(): Wrong object type, expected fontstring", + ), + ( + "FsTip:AddFontStrings(FsLeft, FsTip)", + "FsTip:AddFontStrings(): Wrong object type, expected fontstring", + ), + ( + "FsTip:AddFontStrings({}, FsRight)", + "FsTip:AddFontStrings(): Couldn't find 'this' in fontstring", + ), + ( + "FsTip:AddFontStrings(FsLeft, 5)", + "Usage: FsTip:AddFontStrings(leftstring, rightstring)", + ), + ( + "FsAnon:AddFontStrings(FsTex, FsRight)", + ":AddFontStrings(): Wrong object type, expected fontstring", + ), + ] { + let err = s.run(call).unwrap_err().to_string(); + assert!(err.contains(line), "{call}: {err}"); + } + s.run("FsTip:AddFontStrings(FsLeft, FsRight)").unwrap(); +} + +/// `GameTooltip:SetBuybackItem(slot)` (`0x536300`) tests its slot with `lua_isnumber` first +/// (`0x536322`), raising `Usage: SetBuybackItem(slot)` (`0x855634`), and only then resolves its +/// receiver with the member prologue (`0x536367`). +#[test] +fn set_buyback_item_reads_its_slot_before_its_receiver() { + let s = script(); + s.run( + r#" + BbTip = CreateFrame("GameTooltip", "BbTip") + BbTex = BbTip:CreateTexture("BbTex") + "#, + ) + .unwrap(); + for (call, line) in [ + ("BbTip:SetBuybackItem('x')", "Usage: SetBuybackItem(slot)"), + ( + "BbTip.SetBuybackItem(nil, 'x')", + "Usage: SetBuybackItem(slot)", + ), + ("BbTip.SetBuybackItem()", "Usage: SetBuybackItem(slot)"), + ( + "BbTip.SetBuybackItem(nil, 1)", + "Attempt to find 'this' in non-table object (used '.' instead of ':' ?)", + ), + ( + "BbTip.SetBuybackItem({}, 1)", + "Attempt to find 'this' in non-framescript object", + ), + ( + "BbTip.SetBuybackItem(BbTex, 1)", + "Wrong object type for member function", + ), + ] { + let err = s.run(call).unwrap_err().to_string(); + assert!(err.contains(line), "{call}: {err}"); + } + s.run("BbTip:SetBuybackItem('2') BbTip:SetBuybackItem(1)") + .unwrap(); +} diff --git a/crates/benilla-ui/src/script/tooltip/verbs.rs b/crates/benilla-ui/src/script/tooltip/verbs.rs index 90242ac69..bbe8b134e 100644 --- a/crates/benilla-ui/src/script/tooltip/verbs.rs +++ b/crates/benilla-ui/src/script/tooltip/verbs.rs @@ -4,7 +4,6 @@ use mlua::{Lua, Table, Value, Variadic}; use crate::script::binding_abi::{self, optional_string, string_arg}; use crate::script::object::frame_handle_of; -use crate::script::region::region_handle_of; use crate::script::Model; use crate::widget::{KindState, TooltipAnchor}; @@ -206,9 +205,9 @@ pub(in crate::script) fn install(lua: &Lua) -> mlua::Result<()> { // pair and raise the line limit by one (`0x529940`), keeping the caller's fonts. m.set( "AddFontStrings", - lua.create_function(|lua, (this, left, right): (Table, Table, Table)| { - let lh = region_handle_of(lua, &left)?; - let rh = region_handle_of(lua, &right)?; + lua.create_function(|lua, (this, left, right): (Table, Value, Value)| { + let lh = font_string_arg(lua, &this, &left)?; + let rh = font_string_arg(lua, &this, &right)?; super::add_font_strings(lua, &this, lh, rh) })?, )?; @@ -259,3 +258,37 @@ pub(in crate::script) fn install(lua: &Lua) -> mlua::Result<()> { lua.set_named_registry_value(REG_TOOLTIP_METHODS, m)?; Ok(()) } + +/// One of `AddFontStrings`' two strings (`0x530cf6`-`0x530d4d`, arguments 2 then 3): a non-table +/// raises the usage line (`0x85506c`), a table with no object `0x855034`'s, and an object that +/// fails the FontString test `[0xcf2ccc]` `0x854ff8`'s, each naming the tooltip or ``. +fn font_string_arg( + lua: &Lua, + this: &Table, + arg: &Value, +) -> mlua::Result { + let who = binding_abi::name_of(lua, this); + let Value::Table(t) = arg else { + return Err(mlua::Error::runtime(format!( + "Usage: {who}:AddFontStrings(leftstring, rightstring)" + ))); + }; + let Ok(id) = crate::script::object::decode_id(t) else { + return Err(mlua::Error::runtime(format!( + "{who}:AddFontStrings(): Couldn't find 'this' in fontstring" + ))); + }; + let model = lua.app_data_ref::().expect("model app_data"); + model + .id_to_region + .get(&id) + .copied() + .filter(|&rh| { + model.arena.region(rh).map(|r| r.kind) == Some(crate::widget::RegionKind::FontString) + }) + .ok_or_else(|| { + mlua::Error::runtime(format!( + "{who}:AddFontStrings(): Wrong object type, expected fontstring" + )) + }) +} diff --git a/crates/benilla-ui/src/script/tooltip_item/mod.rs b/crates/benilla-ui/src/script/tooltip_item/mod.rs index 14c4dda50..e544f086c 100644 --- a/crates/benilla-ui/src/script/tooltip_item/mod.rs +++ b/crates/benilla-ui/src/script/tooltip_item/mod.rs @@ -844,11 +844,32 @@ pub(super) fn install_methods(lua: &Lua, m: &Table) -> mlua::Result<()> { compare::install_methods(lua, m)?; // GameTooltip:SetMerchantItem(index) / SetBuybackItem(index): template sources, as the - // reference's `SetMerchantItem` (`0x534080`) is. + // reference's `SetMerchantItem` (`0x534080`) is. `SetBuybackItem` (`0x536300`) tests its slot + // with `lua_isnumber` before its receiver (`0x536322`, usage `0x855634`), then takes row + // `ftol(slot) - 1` when it is below the count, compared unsigned (`0x536401`-`0x53640f`). for (method, buyback) in [("SetMerchantItem", false), ("SetBuybackItem", true)] { m.set( method, - lua.create_function(move |lua, (this, index): (Table, usize)| { + lua.create_function(move |lua, (this, index): (Value, Value)| { + let (this, index) = if buyback { + let Some(slot) = lua.coerce_number(index)? else { + return Err(mlua::Error::runtime("Usage: SetBuybackItem(slot)")); + }; + let this = crate::script::object::receiver_in( + lua, + &this, + crate::script::tooltip::REG_TOOLTIP_METHODS, + )?; + let Ok(index) = usize::try_from(slot as i64) else { + return Ok(()); + }; + (this, index) + } else { + <(Table, usize) as mlua::FromLuaMulti>::from_lua_args( + mlua::MultiValue::from_vec(vec![this, index]), + lua, + )? + }; let h = frame_handle_of(lua, &this)?; let row = { let model = lua.app_data_mut::().expect("model app_data"); @@ -860,7 +881,12 @@ pub(super) fn install_methods(lua: &Lua, m: &Table) -> mlua::Result<()> { } else { &merchant.items }; - list.get(index.saturating_sub(1)).cloned() + let row = if buyback { + index.checked_sub(1) + } else { + Some(index.saturating_sub(1)) + }; + row.and_then(|i| list.get(i)).cloned() }; let Some(row) = row else { return Ok(()) }; // Nothing to arm: the vendor tab's row seats `ShoppingTooltip1/2` itself diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index d4d8f421c..aa914dc3e 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -724,7 +724,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - The reference's `set` registers an unknown name as a new category-5 record (`0x63d569`-`0x63d582`); benilla refuses it, because nothing would read the row and `config.toml` keeps an unknown key anyway. ([`src/script/console_exec.rs:120`](../crates/benilla-ui/src/script/console_exec.rs#L120)) - A row the session owns (an env lever) is passed, because the env chose its value for this run and the file never holds it, so a reset would undo the lever and save nothing. ([`src/script/console_exec.rs:199`](../crates/benilla-ui/src/script/console_exec.rs#L199)) - The backpack is bounded by its own 16 slots, where `0x4f990f` bounds bag 0 by the player list's count (0x71), a reference bug that lets the backpack index read other containers. ([`src/script/container.rs:312`](../crates/benilla-ui/src/script/container.rs#L312)) -- A row index the list no longer holds buys nothing and drops, where this path reads through a null row (`0x4f9f35`). ([`src/script/container.rs:761`](../crates/benilla-ui/src/script/container.rs#L761)) +- A row index the list no longer holds buys nothing and drops, where this path reads through a null row (`0x4f9f35`). ([`src/script/container.rs:768`](../crates/benilla-ui/src/script/container.rs#L768)) - A last `spell_id` key breaks the remaining ties (Charge's six ranks all have `spellLevel` 0), because the reference leaves them to its qsort over an array benilla does not reproduce; ascending id is ascending rank in every 1.12 pet-ability family. ([`src/script/craft.rs:104`](../crates/benilla-ui/src/script/craft.rs#L104)) - The reference reads past the table unbounded (`0x4f6c90`), so type 5 would answer "CloseCraft"; no shipped opener carries a type past 3, and benilla answers nil rather than read past it. ([`src/script/craft.rs:430`](../crates/benilla-ui/src/script/craft.rs#L430)) - On `Terrain` the reference keeps a spell, action, macro or pet action on the left button; we clear them, because otherwise a spell has no left-click way off the cursor. ([`src/script/cursor.rs:642`](../crates/benilla-ui/src/script/cursor.rs#L642)) @@ -761,8 +761,8 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - A listing that finds no icon stays empty, to be listed again on the next ask, where the reference's dedup then reads below its null list (`0x4f0134`-`0x4f0145`) and faults. ([`src/script/macros.rs:534`](../crates/benilla-ui/src/script/macros.rs#L534)) - Each line is trimmed, because the reference sends an indented `" /say hi"` as plain chat, never as the command meant. ([`src/script/macros/bind.rs:30`](../crates/benilla-ui/src/script/macros/bind.rs#L30)) - The `/cast` argument is trimmed, because the reference binds `/cast Fireball` (two spaces) to a name that never resolves. ([`src/script/macros/bind.rs:50`](../crates/benilla-ui/src/script/macros/bind.rs#L50)) -- The client's Lua has no such bound, as nothing sets a hook (`lua_sethook`, `0x6fba40`, has no caller and no pointer to it), so a load that never ends hangs it. ([`src/script/mod.rs:882`](../crates/benilla-ui/src/script/mod.rs#L882)) -- The reference sets the cells only when glue or the interface is built, `0x41ad10` from `0x46a828` (`0x46a7b0`) and `0x48fe2b` (`0x48fbf0`), and a resize reaches them only through the rebuild it asks for. ([`src/script/mod.rs:933`](../crates/benilla-ui/src/script/mod.rs#L933)) +- The client's Lua has no such bound, as nothing sets a hook (`lua_sethook`, `0x6fba40`, has no caller and no pointer to it), so a load that never ends hangs it. ([`src/script/mod.rs:884`](../crates/benilla-ui/src/script/mod.rs#L884)) +- The reference sets the cells only when glue or the interface is built, `0x41ad10` from `0x46a828` (`0x46a7b0`) and `0x48fe2b` (`0x48fbf0`), and a resize reaches them only through the rebuild it asks for. ([`src/script/mod.rs:935`](../crates/benilla-ui/src/script/mod.rs#L935)) - A path that does not resolve is stored, where the reference raises `Invalid model file: %s` (`0x878b44`), because the file loads asynchronously here and the call cannot know yet. ([`src/script/modelframe.rs:339`](../crates/benilla-ui/src/script/modelframe.rs#L339)) - Benilla plays no pre-rendered movie (#968), so `StartMovie` answers nil, the reference's "could not start" (`0x78d861`), which the stock `MovieFrame_PlayMovie` answers by hiding the frame and so by returning to the login screen. ([`src/script/movieframe.rs:4`](../crates/benilla-ui/src/script/movieframe.rs#L4)) - The reference's free list is FIFO; either keeps every index stable, all an addon can observe. ([`src/script/nameplate.rs:432`](../crates/benilla-ui/src/script/nameplate.rs#L432))