diff --git a/crates/benilla-app/src/capture/probe_mail.rs b/crates/benilla-app/src/capture/probe_mail.rs index 41de4a1f6..c14af9cbc 100644 --- a/crates/benilla-app/src/capture/probe_mail.rs +++ b/crates/benilla-app/src/capture/probe_mail.rs @@ -174,16 +174,17 @@ fn last_event(script: &UiScript) -> String { fn mail_probe( time: ProbeClock, mut probe: ResMut, - mail: Res, mut windows: Commands, - mut hosted_vm: crate::script_calls::HostedVm, + // The session is the call host's too ([`crate::ui_mail::MailVerbs`]): the probe's verbs apply + // as its turn ends. + mut vm: crate::script_calls::VmWith>, self_player: Query<(), With>, player: Res, objects: Query<(&Guid, &NetEntity, &ObjectStore, &Transform), Without>, net: Res, mut exit: MessageWriter, ) { - hosted_vm.run(|script| { + vm.turn(|script, mail| { if self_player.is_empty() { return; // not in-world yet } diff --git a/crates/benilla-app/src/entities.rs b/crates/benilla-app/src/entities.rs index 4e30e7475..0d88aa1b5 100644 --- a/crates/benilla-app/src/entities.rs +++ b/crates/benilla-app/src/entities.rs @@ -984,12 +984,16 @@ fn setup_entities( } match benilla_formats::load_stationery_catalog(&mut chain) { Ok(catalog) => commands.insert_resource(crate::ui_mail::Stationery(catalog)), - Err(e) => warn!("stationery catalog unavailable, mail uses the default backdrop: {e:#}"), + Err(e) => warn!("stationery catalog unavailable, mail has no paper or texture: {e:#}"), } match benilla_formats::load_packages(&mut chain) { Ok(rows) => commands.insert_resource(crate::ui_mail::Packages(rows)), Err(e) => warn!("mail packages unavailable, GetNumPackages answers 0: {e:#}"), } + match benilla_formats::load_mail_templates(&mut chain) { + Ok(rows) => commands.insert_resource(crate::ui_mail::MailTemplates(rows)), + Err(e) => warn!("mail templates unavailable, a template letter has no body: {e:#}"), + } match benilla_formats::load_page_text_material_catalog(&mut chain) { Ok(catalog) => commands.insert_resource(crate::ui_item_text::PageMaterials(catalog)), Err(e) => warn!("page text materials unavailable, books read on parchment: {e:#}"), diff --git a/crates/benilla-app/src/go_templates.rs b/crates/benilla-app/src/go_templates.rs index df10082b7..11547d491 100644 --- a/crates/benilla-app/src/go_templates.rs +++ b/crates/benilla-app/src/go_templates.rs @@ -183,6 +183,18 @@ impl GameObjectTemplates { self.templates.get(entry).map(|t| t.name.as_str()) } + /// A template's name by entry, read as `ask` says, a miss asked with no spawn's guid: the inbox + /// header's game object sender (`0x558560` with the callback `0x4af080`, `0x4aee94`). + pub(crate) fn resolve_name( + &self, + entry: u32, + ask: crate::query_cache::Ask<'_>, + ) -> Option<&str> { + self.templates + .read(entry, ask, |commands| Self::send(entry, 0, commands)) + .map(|t| t.name.as_str()) + } + /// The cached template for a GameObject, found through its own descriptor. pub(crate) fn of(&self, fields: &ObjectFields) -> Option<&GoTemplate> { Self::key(fields).and_then(|e| self.templates.get(e)) diff --git a/crates/benilla-app/src/net.rs b/crates/benilla-app/src/net.rs index a5aea64db..60ff541e1 100644 --- a/crates/benilla-app/src/net.rs +++ b/crates/benilla-app/src/net.rs @@ -1616,6 +1616,7 @@ pub(crate) enum ClientCommand { MailCreateTextItem { mailbox: u64, mail_id: u32, + template_id: u32, }, /// `CMSG_ITEM_TEXT_QUERY`, once per mail with a nonzero `item_text_id`. ItemTextQuery { diff --git a/crates/benilla-app/src/net/io.rs b/crates/benilla-app/src/net/io.rs index 14fa18315..5f3ddf93d 100644 --- a/crates/benilla-app/src/net/io.rs +++ b/crates/benilla-app/src/net/io.rs @@ -1640,9 +1640,11 @@ pub(super) fn writer_loop( ClientCommand::MailDelete { mailbox, mail_id } => { w.mail_delete(mailbox, mail_id) } - ClientCommand::MailCreateTextItem { mailbox, mail_id } => { - w.mail_create_text_item(mailbox, mail_id) - } + ClientCommand::MailCreateTextItem { + mailbox, + mail_id, + template_id, + } => w.mail_create_text_item(mailbox, mail_id, template_id), ClientCommand::ItemTextQuery { text_id, mail_id } => { w.item_text_query(text_id, mail_id) } diff --git a/crates/benilla-app/src/script_calls.rs b/crates/benilla-app/src/script_calls.rs index 0c820acf5..953676f4f 100644 --- a/crates/benilla-app/src/script_calls.rs +++ b/crates/benilla-app/src/script_calls.rs @@ -84,13 +84,14 @@ pub(crate) struct ScriptCallHost<'w, 's> { crate::ui_party::PartyCalls<'w, 's>, ), >, - // The bags' and the loot window's. + // The bags', the loot window's and the mailbox's. ParamSet< 'w, 's, ( crate::ui_items::ScriptItemUse<'w, 's>, crate::ui_loot::LootSteps<'w, 's>, + crate::ui_mail::MailVerbs<'w>, ), >, crate::ui_pet::PetPress<'w, 's>, @@ -194,6 +195,7 @@ impl CallHost for ScriptCallHost<'_, '_> { ScriptCall::Auction(call) => appliers.p4().p3().apply(script, call), ScriptCall::Social(call) => appliers.p4().p4().apply(script, call), ScriptCall::Party(request) => appliers.p4().p5().apply(script, request), + ScriptCall::Mail(call) => appliers.p5().p2().apply(script, call), } // A selection this call made with the targeting cursor up was handed to the cast // (`SelectTarget`, `0x4935d5`) and is bound now, before the next call reads either. diff --git a/crates/benilla-app/src/text_filter.rs b/crates/benilla-app/src/text_filter.rs index a7d2eb636..d5f3b7409 100644 --- a/crates/benilla-app/src/text_filter.rs +++ b/crates/benilla-app/src/text_filter.rs @@ -7,11 +7,11 @@ //! (`[0xb6e5f0]`) that is never reset, so the phase carries across matches and messages. Patterns //! apply in list order, not text order, every occurrence, and the length never changes. //! -//! Only the chat chokepoint is wired. The reference masks twelve more sites, not built here: the -//! mail subject, `GetInboxText`, `GetGuildInfo`, the two guild-record accessors, the roster MOTD -//! and info, `GetGuildRosterInfo`, `GuildControlGetRankName`, item text, `SendChatMessage` and the -//! guild-event MOTD; seven of them pass the `dl = 1` memo, which re-blits a cached string without -//! advancing the index. +//! The chat chokepoint, the mail list's subjects (`0x4ad5b2`) and `GetInboxText`'s letter +//! (`0x4af203`) are wired. The reference masks ten more sites, not built here: `GetGuildInfo`, the +//! two guild-record accessors, the roster MOTD and info, `GetGuildRosterInfo`, +//! `GuildControlGetRankName`, item text, `SendChatMessage` and the guild-event MOTD; seven of them +//! pass the `dl = 1` memo, which re-blits a cached string without advancing the index. //! //! The predicate has one call site, in the chat chokepoint; it never edits the text, and a hit //! drops the line silently. @@ -293,8 +293,10 @@ pub(crate) struct TextFilter { /// (`0xce893c`) is read by the masker and the name check alike. profanity: Arc, spam: PatternList, - /// `[0xb6e5f0]`: zero-initialized, advanced mod 8, never reset. - mask_index: usize, + /// `[0xb6e5f0]`: zero-initialized, advanced mod 8, never reset. Atomic, so every reader of the + /// filter (the chat chokepoint, the mail calls) shares the one index without excluding the + /// others. + mask_index: std::sync::atomic::AtomicUsize, } impl Default for TextFilter { @@ -303,7 +305,7 @@ impl Default for TextFilter { TextFilter { profanity: Arc::new(PatternList::empty()), spam: PatternList::empty(), - mask_index: 0, + mask_index: std::sync::atomic::AtomicUsize::new(0), } } } @@ -313,7 +315,7 @@ impl TextFilter { TextFilter { profanity: Arc::new(PatternList::compile(profanity, "chat profanity filter")), spam: PatternList::compile(spam, "chat spam filter"), - mask_index: 0, + mask_index: std::sync::atomic::AtomicUsize::new(0), } } @@ -351,16 +353,24 @@ impl TextFilter { /// `0x4a1a60` with `dl = 0`: mask in place, return whether anything matched. `enabled` is /// `profanityFilter`, tested here as the reference does. - pub(crate) fn mask(&mut self, enabled: bool, text: &mut String) -> bool { + pub(crate) fn mask(&self, enabled: bool, text: &mut String) -> bool { if !enabled || text.is_empty() || self.profanity.len() == 0 { return false; } self.mask_uncached(text) } + /// The index's current token, and the index advanced past it. + fn next_mask_index(&self) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let at = self.mask_index.load(Relaxed); + self.mask_index.store((at + 1) % MASK_TOKENS.len(), Relaxed); + at + } + /// The byte loop of `0x4a1b6a`-`0x4a1ba6`: one pass in list order over the mutating buffer, so /// an earlier pattern's mask can enable a later match but never the reverse. - fn mask_uncached(&mut self, text: &mut String) -> bool { + fn mask_uncached(&self, text: &mut String) -> bool { // The subject is ASCII-lowercased, byte-aligned with `text` and masked in step. let mut subject = ascii_lower(text); let mut candidates = self.profanity.candidates(&subject); @@ -380,11 +390,7 @@ impl TextFilter { // One token per byte of the span, as the reference's loop writes; a match is on // char boundaries, so both strings stay valid UTF-8 and aligned. let run: String = (start..end) - .map(|_| { - let token = MASK_TOKENS[self.mask_index] as char; - self.mask_index = (self.mask_index + 1) % MASK_TOKENS.len(); - token - }) + .map(|_| MASK_TOKENS[self.next_mask_index()] as char) .collect(); text.replace_range(start..end, &run); subject.replace_range(start..end, &run); @@ -433,7 +439,7 @@ mod tests { let f = TextFilter::new(&list(&[spelling]), &[]); let mut hit = "you twat here".to_string(); let mut miss = "atwatb".to_string(); - let mut copy = f; + let copy = f; assert!(copy.mask(true, &mut hit), "{spelling} must match [4,8)"); assert_eq!(hit, "you !@#$ here", "{spelling}"); assert!( @@ -458,7 +464,7 @@ mod tests { } fn masked(pattern: &str, text: &str) -> String { - let mut f = TextFilter::new(&list(&[pattern]), &[]); + let f = TextFilter::new(&list(&[pattern]), &[]); let mut line = text.to_string(); f.mask(true, &mut line); line @@ -572,7 +578,7 @@ mod tests { /// carrying across calls, and list order giving the later word the earlier mask characters. #[test] fn the_masker_reproduces_the_oracle_transcript() { - let mut f = TextFilter::new(&list(&[r"\", "shit"]), &[]); + let f = TextFilter::new(&list(&[r"\", "shit"]), &[]); let mut line = "you are a twat and a faggot".to_string(); assert!(f.mask(true, &mut line)); @@ -596,7 +602,8 @@ mod tests { assert_eq!(line, "hello friend, nice weather"); assert_eq!( - f.mask_index, 6, + f.mask_index.load(std::sync::atomic::Ordering::Relaxed), + 6, "the cycle carries forward, and is never reset" ); } @@ -604,17 +611,17 @@ mod tests { /// With `profanityFilter = 0` the text is untouched and the phase does not move. #[test] fn the_masker_self_gates_and_a_gated_call_does_not_move_the_phase() { - let mut f = TextFilter::new(&list(&[r"\"]), &[]); + let f = TextFilter::new(&list(&[r"\"]), &[]); let mut line = "you are a twat".to_string(); assert!(!f.mask(false, &mut line)); assert_eq!(line, "you are a twat"); - assert_eq!(f.mask_index, 0); + assert_eq!(f.mask_index.load(std::sync::atomic::Ordering::Relaxed), 0); } /// A multi-byte match is masked byte for byte. #[test] fn a_non_ascii_match_is_masked_byte_for_byte() { - let mut f = TextFilter::new(&list(&["傻B"]), &[]); + let f = TextFilter::new(&list(&["傻B"]), &[]); let mut line = "说 傻B 了".to_string(); let before = line.len(); assert!(f.mask(true, &mut line)); @@ -715,7 +722,7 @@ mod tests { let mut chain = benilla_formats::open_chain(&data).expect("open chain"); let profanity = benilla_formats::load_chat_profanity(&mut chain).expect("profanity"); let spam = benilla_formats::load_spam_messages(&mut chain).expect("spam"); - let mut f = TextFilter::new(&profanity, &spam); + let f = TextFilter::new(&profanity, &spam); let mut line = "you are a twat and a faggot".to_string(); assert!(f.mask(true, &mut line)); @@ -798,7 +805,7 @@ impl benilla_ui::script::NameLists for NameFilter { /// Bevy's sixteen-parameter limit. #[derive(bevy::ecs::system::SystemParam)] pub(crate) struct ChatTextFilter<'w> { - filter: ResMut<'w, TextFilter>, + filter: Res<'w, TextFilter>, switches: Res<'w, TextFilterSwitches>, } @@ -822,7 +829,7 @@ impl ChatTextFilter<'_> { /// Arm 2: mask the line if its type is in the reference's table (`0x49aa98`-`0x49aac2`); the /// CVar is the masker's own. - pub(crate) fn mask_chat(&mut self, chat_type: u8, text: &mut String) { + pub(crate) fn mask_chat(&self, chat_type: u8, text: &mut String) { if !PROFANITY_MASKED_CHAT_TYPES.contains(&chat_type) { return; } diff --git a/crates/benilla-app/src/ui_chat/feed.rs b/crates/benilla-app/src/ui_chat/feed.rs index 04ed19775..d840db9d2 100644 --- a/crates/benilla-app/src/ui_chat/feed.rs +++ b/crates/benilla-app/src/ui_chat/feed.rs @@ -1120,7 +1120,7 @@ pub(super) fn feed_chat( ), unit_names: crate::ui_unit::NameTables, // The spam and profanity filters, which run in the reference's display function `0x49a870`. - mut text_filter: crate::text_filter::ChatTextFilter, + text_filter: crate::text_filter::ChatTextFilter, ) { let (Some(script), set) = vm.parts() else { return; diff --git a/crates/benilla-app/src/ui_item_text.rs b/crates/benilla-app/src/ui_item_text.rs index 37e050ac5..483c3f3bf 100644 --- a/crates/benilla-app/src/ui_item_text.rs +++ b/crates/benilla-app/src/ui_item_text.rs @@ -410,8 +410,8 @@ fn readable( /// Drive the begun session to `ITEM_TEXT_READY`, which shows the window, once the body and any /// creator line are in. fn feed_item_text( - mut vm: crate::script_calls::VmWith>, - mail: Res, + // The mail session's body cache is the call host's too ([`crate::ui_mail::MailVerbs`]). + mut vm: crate::script_calls::VmWith<(ResMut<'static, ItemTextOpen>, Res<'static, MailOpen>)>, pages: Res, objects: Objects, items: Res, @@ -424,7 +424,7 @@ fn feed_item_text( states: Res, unit_names: crate::ui_unit::NameTables, ) { - vm.feed(|script, mut open, fires| { + vm.feed(|script, (mut open, mail), fires| { let Some(script) = script else { return; }; diff --git a/crates/benilla-app/src/ui_mail/invoice.rs b/crates/benilla-app/src/ui_mail/invoice.rs index 1bf28d550..ea08d26ec 100644 --- a/crates/benilla-app/src/ui_mail/invoice.rs +++ b/crates/benilla-app/src/ui_mail/invoice.rs @@ -20,9 +20,8 @@ pub(crate) mod auction_mail { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct AuctionSubject { pub(crate) entry: u32, - /// The random-property roll. Parsed, not applied: the reference names the item with it - /// (`[rec+0x250]`, `[rec+0x254]`), and the displayed subject here does not. - #[allow(dead_code)] + /// The random-property roll, which names the item's suffix in the subject and the invoice + /// (`[rec+0x254]`, `0x5d8b00`). pub(crate) random_property: i32, pub(crate) result: u32, } diff --git a/crates/benilla-app/src/ui_mail/mod.rs b/crates/benilla-app/src/ui_mail/mod.rs index 333dd47de..7f2e090c3 100644 --- a/crates/benilla-app/src/ui_mail/mod.rs +++ b/crates/benilla-app/src/ui_mail/mod.rs @@ -12,6 +12,7 @@ use benilla_protocol::messages::{mail_error, mail_message_type, MailListEntry}; use bevy::prelude::*; +use std::collections::HashMap; use benilla_ui::script::{MailInboxRow, MailState, ScriptValue, StationeryView, UiScript}; @@ -23,13 +24,18 @@ use crate::net::{ }; use crate::query_cache::Ask; use crate::query_cache::QueryCache; +use crate::script_calls::VmWith; use crate::ui_script::{SweepApp, SweepLeg, UiFeed}; use crate::ui_session::{CoreCloses, LatchApp, LatchedWindow, NpcWindow}; mod net; mod pending; +#[cfg(test)] +mod verb_tests; +mod verbs; pub(crate) use pending::MailPending; +pub(crate) use verbs::MailVerbs; /// `checked` mask bits (vmangos `Mail.h`): READ, RETURNED, COPIED. const CHECKED_READ: u32 = 0x1; @@ -43,19 +49,27 @@ const CHECKED_COD_PAYMENT: u32 = 0x8; /// carries a package (`MailFrame.lua:108`). const STATIONERY_GM: u32 = 61; -/// The letter-row icon: the stationery's item icon (`Stationery.dbc` 41 → item 9311, display -/// 7798; 61 → item 18154, display 30658). -const STATIONERY_ICON_NORMAL: &str = "Interface\\Icons\\INV_Misc_Note_01"; -const STATIONERY_ICON_GM: &str = "Interface\\Icons\\Mail_GMIcon"; - -/// The `Stationery.dbc` catalog; without it every mail gets the default backdrop. +/// The `Stationery.dbc` catalog; without it every mail's texture is nil and no paper is usable. #[derive(Resource)] pub(crate) struct Stationery(pub(crate) benilla_formats::StationeryCatalog); +/// `MailTemplate.dbc`'s bodies by id, in the client's locale; without them a template mail's body +/// is nil, as for an id the store lacks (`0x4af229`). +#[derive(Resource)] +pub(crate) struct MailTemplates(pub(crate) std::collections::HashMap); + /// `Package.dbc`'s rows, in file order; without them `GetNumPackages()` answers 0. #[derive(Resource)] pub(crate) struct Packages(pub(crate) Vec); +/// The stores a row's icons and a non-player sender's name are read from. +#[derive(Clone, Copy, Default)] +pub(super) struct RowCatalogs<'a> { + pub(super) packages: Option<&'a Packages>, + pub(super) houses: Option<&'a crate::ui_auction::AuctionHouses>, + pub(super) gameobjects: Option<&'a crate::go_templates::GameObjectTemplates>, +} + /// A package row as the engine answers it: the icon under `StringLookups.dbc` row 3's folder /// (`0x4ae4ab`, the `"%s%s"` of folder and `\`, then the basename appended). fn package_view(row: &benilla_formats::PackageRow) -> benilla_ui::script::PackageView { @@ -105,8 +119,19 @@ pub(crate) struct MailOpen { list_results: u32, /// The mail results since the last feed, in arrival order. pub(crate) results: Vec, - /// Refusals of a request the client made no packet for, as message keys. - pub(crate) errors: Vec<&'static str>, + /// Each auction notice's subject cell (`[rec+0x14]`) as the list parse left it, by mail id; the + /// row keeps the raw triplet, the copy (`[rec+0x150]`) every parse reads. + pub(crate) auction_subjects: HashMap, +} + +/// An auction notice's shown subject after the list parse (`0x4ad580`-`0x4ad5b2`): rewritten +/// and masked when the notice's item was held then, else empty (`0x4acf3d`). +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ListedSubject { + pub(crate) text: String, + /// The parse rewrote it. Else the cell stays empty until the item's template lands and its + /// callback rewrites it (`0x4ad010` → `0x4ace40`), with no mask. + pub(crate) rewritten: bool, } impl crate::query_cache::AskOnce for MailOpen { @@ -129,20 +154,15 @@ impl MailOpen { self.request_resolved = true; } - fn mail_id_at(&self, index_1based: u32) -> Option { - index_1based - .checked_sub(1) - .and_then(|i| self.mails.get(i as usize)) - .map(|e| e.message_id) - } - - /// Sets a row's READ bit locally: `CMSG_MAIL_MARK_AS_READ` gets no reply. - fn mark_read(&mut self, index_1based: u32) { - if let Some(e) = index_1based - .checked_sub(1) - .and_then(|i| self.mails.get_mut(i as usize)) - { + /// The read mark's record half (`0x4adcd0`), as `CMSG_MAIL_MARK_AS_READ` gets no reply: the + /// READ bit (`0x4add62`), and days left above 3 lowered to 3 on a mail with no COD + /// (`0x4add72`-`0x4add8e`). + fn mark_read(&mut self, mail_id: u32) { + if let Some(e) = self.mails.iter_mut().find(|e| e.message_id == mail_id) { e.checked |= CHECKED_READ; + if e.cod == 0 && e.expire_days > 3.0 { + e.expire_days = 3.0; + } } } @@ -152,7 +172,6 @@ impl MailOpen { pub(crate) fn clear(&mut self) { self.mailbox = None; self.show_requested = false; - self.errors.clear(); } /// The world-enter init (`0x4acb10`) and a disconnect: no mailbox and no rows. @@ -160,6 +179,7 @@ impl MailOpen { self.clear(); self.results.clear(); self.mails.clear(); + self.auction_subjects.clear(); self.bodies.clear(); self.request_resolved = false; self.list_results = 0; @@ -226,16 +246,13 @@ pub(crate) fn close_core(world: &mut World) { /// no `MAIL_CLOSED`, no interaction release and no refresh (`0x4acd5f`-`0x4acd6b`), the `cl` /// arm the close button's `0x4acd71` skips to. The latch still names the mailbox, which the /// sweep's interaction close then finds no window for. -pub(crate) fn close_mail_on_leave_world( - mut hosted_vm: crate::script_calls::HostedVm, - mut mail: ResMut, -) { - hosted_vm.run(|script| { +pub(crate) fn close_mail_on_leave_world(mut vm: VmWith>) { + vm.run(|script| { if let Some(script) = script { script.reset_compose_tab_silently(); } - mail.clear(); - }) + }); + vm.own().clear(); } pub(crate) struct UiMailPlugin; @@ -270,15 +287,13 @@ impl Plugin for UiMailPlugin { /// with a callback (`0x4acbba`), then it stamps "no mail" (`0x4acb87`) and sends /// `MSG_QUERY_NEXT_MAIL_TIME` (`0x4acbdc`), after the time query and before the battlefield status. pub(crate) fn send_query_next_mail_time_on_enter( - mut hosted_vm: crate::script_calls::HostedVm, + mut vm: VmWith, mut cascades: MessageReader, commands: Res, - mut mail: ResMut, - mut pending: ResMut, items: Option>, stationery: Option>, ) { - hosted_vm.run(|script| { + vm.turn(|script, (mut mail, mut pending)| { if cascades.read().next().is_some() { mail.clear_session(); if let Some(script) = script { @@ -320,6 +335,30 @@ mod invoice; use invoice::auction_mail; +/// An auction notice's subject as `0x4ace70` writes it once the notice's item is held +/// (`0x4acf04`): the outcome's `AUCTION_*_MAIL_SUBJECT` (`0x4acfec`) with the item's name and +/// its roll's suffix (`0x4acf5d` → `0x5d8b00`), `""` +/// when the string is missing or empty (`0x4acf99`-`0x4acfbd`). `None` for a subject that is not +/// the triplet, and for an item not held, which the lookup asks for (`0x4acf38`). +pub(super) fn auction_subject( + raw: &str, + items: &Items, + props: Option<&crate::items::RandomProperties>, + ask: Ask<'_>, + get_text: &dyn Fn(&str) -> Option, +) -> Option { + let notice = invoice::parse_subject(raw)?; + let template = items.template(notice.entry, 0, ask)?; + let name = &crate::items::item_display_name(&template.name, notice.random_property, props); + Some( + invoice::subject_key(notice.result) + .and_then(get_text) + .filter(|t| !t.is_empty()) + .map(|t| t.replace("%s", name)) + .unwrap_or_default(), + ) +} + /// One wire row as the Lua-facing row; anything still in flight stays `None` until it lands. The /// caches are read as `ask` says: the reference's `GetInboxHeaderInfo` (sender `0x4aedf6`, item /// `0x4aecc7`), its subject parse at the list (`0x4acf38`) and `GetInboxInvoiceInfo`'s name @@ -327,9 +366,13 @@ use invoice::auction_mail; fn resolve_row( entry: &MailListEntry, bodies: &QueryCache, + // What the list parse left in an auction notice's subject. + listed: Option<&ListedSubject>, items: &Items, icons: Option<&ItemDisplays>, stationery: Option<&Stationery>, + templates: Option<&MailTemplates>, + catalogs: RowCatalogs, names: &NameCache, ask: Ask<'_>, rolls: crate::items::RollCatalogs, @@ -337,14 +380,12 @@ fn resolve_row( // The VM's GlobalStrings, for the auction subject: the strings are the install's, never ours. get_text: &dyn Fn(&str) -> Option, ) -> MailInboxRow { + // The GM flag is the stationery alone (`0x4aeda1`); the reply flag is a player's mail off it, + // returned or not (`0x4aefa5`-`0x4aefbc`), which `MailFrame.lua:281` reads. let is_gm = entry.stationery == STATIONERY_GM; let returned = entry.checked & CHECKED_RETURNED != 0; - // Reply only to an unreturned mail from a player (`MailFrame.lua:281` reads it). - let can_reply = entry.sender_guid.is_some() && !returned; - // An unreturned player mail still carrying money or an item returns rather than deletes; the - // reference's `InboxItemCanDelete` predicate is untraced. - let can_delete = - returned || entry.sender_guid.is_none() || (entry.item.is_none() && entry.money == 0); + let player_mail = entry.message_type == mail_message_type::NORMAL; + let can_reply = player_mail && !is_gm; let (item_id, item_roll, item_count, item_name, item_texture, item_quality) = match &entry.item { @@ -372,13 +413,51 @@ fn resolve_row( (att.charges as i32, (att.durability, att.durability_max)) }); - let sender = entry - .sender_guid - .and_then(|g| names.resolve_player(g, ask).map(str::to_string)); + // A player's GM letter is from `GM_EMAIL_NAME`, `""` when the string is missing + // (`0x4aedbd`-`0x4aedcb`, `0x703bf0`); any other player's mail from its sender's name. + // A non-player sender is named from its store by the sender id (`[rec+0x10]`, jump table + // `0x4af068`): an auction house's name (`0x4aee11`), a creature's (`0x4aee48`) and a game + // object's (`0x4aee78`), the last two asked with no guid. + let sender_id = entry.sender_id.unwrap_or(0); + let sender = match entry.message_type { + mail_message_type::NORMAL if is_gm => Some(get_text("GM_EMAIL_NAME").unwrap_or_default()), + mail_message_type::NORMAL => entry + .sender_guid + .and_then(|g| names.resolve_player(g, ask).map(str::to_string)), + mail_message_type::AUCTION => catalogs + .houses + .and_then(|h| h.0.get(sender_id)) + .map(|h| h.name.clone()), + mail_message_type::CREATURE => names + .resolve_creature(sender_id, 0, ask) + .map(str::to_string), + mail_message_type::GAMEOBJECT => catalogs + .gameobjects + .and_then(|g| g.resolve_name(sender_id, ask)) + .map(str::to_string), + _ => None, + }; + // The package's icon when the row carries an id the store holds (`[rec+0x118]`, + // `0x4aec76`-`0x4aec9c`), else the item's (`[rec+0x120]`, `0x4aeca6`-`0x4aecd8`), GM letter + // or not. + let package_icon = catalogs + .packages + .filter(|_| (entry.package as i32) > 0) + .and_then(|p| p.0.iter().find(|r| r.id == entry.package)) + .map(|r| package_view(r).icon) + .or_else(|| item_texture.clone()); + // The paper's item's icon (`[rec+0x11c]` → the store row's item, `0x4aed25`-`0x4aed74`), nil + // for a paper the store lacks or an item not yet held. + let stationery_icon = stationery + .and_then(|s| s.0.rows().iter().find(|r| r.id == entry.stationery)) + .and_then(|r| items.template(r.item, 0, ask)) + .and_then(|t| crate::ui_items::item_icon(icons, t.display_info_id)); + + // The store's texture for the id, none for one it lacks (`0x4af27c`-`0x4af2a9`). let stationery_texture = stationery - .map(|s| s.0.texture(entry.stationery).to_string()) - .unwrap_or_else(|| benilla_formats::StationeryCatalog::DEFAULT_TEXTURE.to_string()); + .and_then(|s| s.0.texture_of(entry.stationery)) + .map(str::to_string); // The raw body: the invoice parses it before any `$`-macro expansion. let raw_body = (entry.item_text_id != 0) @@ -392,16 +471,20 @@ fn resolve_row( .then(|| invoice::parse_subject(&entry.subject)) .flatten(); // The notice's item comes from the subject: a sold notice names an item it does not carry. - let notice_item_name = auction - .and_then(|a| items.template(a.entry, 0, ask)) - .map(|t| t.name.clone()); - // Until the item template lands, the raw triplet stands. - let subject = match (auction, ¬ice_item_name) { - (Some(a), Some(name)) => invoice::subject_key(a.result) - .and_then(get_text) - .map(|t| t.replace("%s", name)) + // The invoice names it with the roll's suffix (`0x4af430` → `0x5d8b00`). + let notice_item_name = auction.and_then(|a| { + items + .template(a.entry, 0, ask) + .map(|t| crate::items::item_display_name(&t.name, a.random_property, rolls.props)) + }); + // The list parse's rewrite stands, masked; else the template's callback rewrites the raw + // triplet once the item lands, unmasked, and until then the list's masked triplet shows. + let subject = match listed { + Some(l) if l.rewritten => l.text.clone(), + _ => auction + .and_then(|_| auction_subject(&entry.subject, items, rolls.props, ask, get_text)) + .or_else(|| listed.map(|l| l.text.clone())) .unwrap_or_else(|| entry.subject.clone()), - _ => entry.subject.clone(), }; let auction_invoice = auction .filter(|a| matches!(a.result, auction_mail::WON | auction_mail::SOLD)) @@ -422,15 +505,11 @@ fn resolve_row( }); MailInboxRow { - package_icon: item_texture.clone(), - stationery_icon: Some( - if is_gm { - STATIONERY_ICON_GM - } else { - STATIONERY_ICON_NORMAL - } - .to_string(), - ), + mail_id: entry.message_id, + item_text_id: entry.item_text_id, + stationery: entry.stationery, + package_icon, + stationery_icon, sender, subject, money: entry.money, @@ -445,15 +524,13 @@ fn resolve_row( mail_template_id: entry.mail_template_id, can_reply, is_gm, - // The body runs the `$`-macro expander for the local player, as `GetInboxText` does. - body: raw_body.map(|b| crate::npc_text::substitute(b, macros)), + body: letter_body(entry, raw_body, templates, macros), stationery_texture, // Won and sold notices only, not every auction mail: the reference's `isInvoice` reads // what its subject parser persists for those two alone. is_invoice: auction .is_some_and(|a| matches!(a.result, auction_mail::WON | auction_mail::SOLD)), invoice: auction_invoice, - has_body: entry.item_text_id != 0, item_id, item_random_property_id: item_roll, item_charges, @@ -461,15 +538,39 @@ fn resolve_row( item_name, item_texture, item_quality, - can_delete, } } +/// `GetInboxText`'s body (`0x4af193`-`0x4af26e`): with a text id, its cached text, nil until it +/// lands (`0x4af1c9`) and for an auction mail (`0x4af1cf`); with none, the template's body in the +/// client's locale (`0x4af217`-`0x4af24e`), nil for an id the store lacks (`0x4af229`); with +/// neither, nil. Either is expanded for the local player (`0x4af1f6`, `0x4af261`). +fn letter_body( + entry: &MailListEntry, + raw_body: Option<&String>, + templates: Option<&MailTemplates>, + macros: &crate::npc_text::MacroContext, +) -> Option { + let text = if entry.item_text_id != 0 { + raw_body.filter(|_| entry.message_type != mail_message_type::AUCTION) + } else if entry.mail_template_id != 0 { + templates.and_then(|t| t.0.get(&entry.mail_template_id)) + } else { + None + }; + text.map(|b| crate::npc_text::substitute(b, macros)) +} + +/// The mail session and its arrival state, which the call host writes too ([`MailVerbs`]): a system +/// holding them runs its Lua as an engine turn ([`VmWith`]). +type MailSession = (ResMut<'static, MailOpen>, ResMut<'static, MailPending>); + /// The usable stationery list (`0x4ad970`): rows always available (`Flags & 1`) or whose item the -/// player carries in bags (`0x622270`), with a cached template, sorted by buy price (`0x4ada90`). -/// A carried paper has no `cost`. The templates are only read (`0x4ada51`): the mail init asks +/// player carries in bags (`0x622270`), with a cached template, in the comparator `0x4ada90`'s +/// order: carried first (`0x4adab5`-`0x4adae7`), then the lower buy price, signed (`0x4adb81`), then +/// the name, ASCII case folded (`SStrCmpI` at `0x4adba6`). A carried paper has no `cost`. The templates are only read (`0x4ada51`): the mail init asks /// for them ([`send_query_next_mail_time_on_enter`]). -fn stationeries( +pub(super) fn stationeries( catalog: &Stationery, self_q: &Query<(&ObjectStore, &crate::net::Guid), With>, objects: &Objects, @@ -477,7 +578,7 @@ fn stationeries( icons: Option<&ItemDisplays>, ) -> Vec { let store = self_q.iter().next().map(|(s, _)| s); - let mut out: Vec<(u32, StationeryView)> = Vec::new(); + let mut out: Vec<((bool, i32, String), StationeryView)> = Vec::new(); for row in catalog.0.rows() { let Some(t) = items.template(row.item, 0, Ask::Read).cloned() else { continue; @@ -494,7 +595,7 @@ fn stationeries( continue; } out.push(( - t.buy_price, + (!carried, t.buy_price as i32, t.name.to_ascii_lowercase()), StationeryView { id: row.id, name: t.name.clone(), @@ -504,7 +605,9 @@ fn stationeries( }, )); } - out.sort_by_key(|(price, v)| (*price, v.id)); + // The id breaks what the comparator leaves equal, which its sort (`0x73f727`) leaves in no + // order the reference fixes. + out.sort_by(|(a, v), (b, w)| a.cmp(b).then(v.id.cmp(&w.id))); out.into_iter().map(|(_, v)| v).collect() } @@ -513,6 +616,8 @@ fn snapshot( items: &Items, icons: Option<&ItemDisplays>, stationery: Option<&Stationery>, + templates: Option<&MailTemplates>, + catalogs: RowCatalogs, names: &NameCache, ask: Ask<'_>, rolls: crate::items::RollCatalogs, @@ -528,9 +633,12 @@ fn snapshot( resolve_row( e, &mail.bodies, + mail.auction_subjects.get(&e.message_id), items, icons, stationery, + templates, + catalogs, names, ask, rolls, @@ -554,6 +662,9 @@ struct MailFeedExtras<'w, 's> { packages_pushed: Local<'s, crate::ui_script::VmMemo>, closes: CoreCloses<'w, 's>, unit_names: crate::ui_unit::NameTables<'w>, + templates: Option>, + houses: Option>, + gameobjects: Option>, /// The diff fired `MAIL_INBOX_UPDATE` last frame, which the stock inbox answers with its /// getters, as it does the reference's cache callbacks' (`0x4af080`, `0x4af0a0` on status 1). inbox_updated: Local<'s, crate::ui_script::VmMemo>, @@ -605,15 +716,13 @@ fn announce_lists(script: &mut UiScript, results: u32) { } fn feed_mail( - mut hosted_vm: crate::script_calls::HostedVm, - mut mail: ResMut, + mut vm: VmWith, objects: Objects, items: Res, icons: Option>, stationery: Option>, names: Res, commands: Res, - mut pending: ResMut, time: Res