diff --git a/module.json b/module.json index a32198d..45ab360 100644 --- a/module.json +++ b/module.json @@ -8,7 +8,7 @@ } ], "url": "https://gitea.palmenalzer.de/alzer/wfrp-4e-de", - "version": "8.7.13", + "version": "8.7.17", "esmodules": [ "modules/babele-register.js", "modules/addon-register.js", diff --git a/modules/addon-register.js b/modules/addon-register.js index 207427e..92eaecc 100644 --- a/modules/addon-register.js +++ b/modules/addon-register.js @@ -232,11 +232,18 @@ const __check_fix_wrong_modules = (chatFlag, patchFinished) => { }); } } else { - if (false && game.user.isGM && patchFinished) { - ChatMessage.create({ - content: "
Die WFRP4E-Module wurden erfolgreich übersetzt. Du kannst loslegen und möge Shallya dich behüten
", - user: game.user.id, - whisper: ChatMessage.getWhisperRecipients("GM") + if (game.user.isGM && patchFinished) { + // Wait for babele-register.js's dictionary caches (career/skill/trait/prayer/ + // spell/talent/vehicleRole/trapping - used by career_careergroup_fn and + // bestiary_traits) to actually finish loading before announcing completion, + // rather than relying on this function's fixed 20s setTimeout delay alone - + // that delay predates those caches and isn't guaranteed to outlast them. + Promise.resolve(game.wfrp4efr?.dictCachesReady).finally(() => { + ChatMessage.create({ + content: "
Die WFRP4E-Module wurden erfolgreich übersetzt. Du kannst loslegen und möge Shallya dich behüten
", + user: game.user.id, + whisper: ChatMessage.getWhisperRecipients("GM") + }); }); } } @@ -469,6 +476,41 @@ Hooks.on('ready', () => { }; } + // Patch OvercastItemModel.prototype.computeSpellDamage (shared by SpellModel and + // PrayerModel, both `extends OvercastItemModel`) to also recognize raw English + // characteristic-bonus phrases in the damage formula, not just the current locale's. + // The system's own implementation does + // `formula.replace(game.wfrp4e.config.characteristicsBonus[ch].toLowerCase(), ...)`, + // which only ever tries the CURRENT (German) localized text - e.g. "widerstandsbonus" + // for Toughness. If a spell/prayer's damage.value formula is still raw English (e.g. + // "Toughness Bonus+4"), because the document was loaded through a path where Babele's + // translation converters run too late to matter for this field (observed via a journal + // page's link-preview priming, which constructs the full Item/Actor - and immediately + // evaluates derived data - before our custom converters get a chance to rewrite the + // formula text), the replace never matches and the leftover text throws a SyntaxError + // when eval()'d. This tries the English phrase too, as a fallback, so the formula + // evaluates correctly regardless of translation timing. + const overcastProto = Object.getPrototypeOf(CONFIG.Item.dataModels.spell?.prototype ?? {}); + if (overcastProto?.computeSpellDamage) { + const originalComputeSpellDamage = overcastProto.computeSpellDamage; + const EN_CHARACTERISTICS_BONUS = { + "ws": "weapon skill bonus", "bs": "ballistic skill bonus", "s": "strength bonus", + "t": "toughness bonus", "i": "initiative bonus", "ag": "agility bonus", + "dex": "dexterity bonus", "int": "intelligence bonus", "wp": "willpower bonus", "fel": "fellowship bonus" + }; + overcastProto.computeSpellDamage = function (formula, options) { + if (typeof formula === "string") { + const lower = formula.toLowerCase(); + for (const [abbr, enPhrase] of Object.entries(EN_CHARACTERISTICS_BONUS)) { + if (!lower.includes(enPhrase)) continue; + const dePhrase = game.wfrp4e.config.characteristicsBonus?.[abbr]?.toLowerCase(); + if (dePhrase) formula = formula.replace(new RegExp(enPhrase, "ig"), dePhrase); + } + } + return originalComputeSpellDamage.call(this, formula, options); + }; + } + game.wfrp4e.warnDialog.render(true, { focus: true, left: 20, top: 20 }); //setTimeout( __check_fix_wrong_modules, 2000, true, false); setTimeout(__check_fix_wrong_modules, 20000, true, true); diff --git a/modules/babele-register.js b/modules/babele-register.js index 3e6127d..48c9e6a 100644 --- a/modules/babele-register.js +++ b/modules/babele-register.js @@ -142,6 +142,49 @@ Hooks.once('init', () => { // pack "loaded" (JSON parsed) but with no effective mapping applied - which is // exactly the "everything stays English except journals" symptom. // See: https://gitlab.com/riccisi/foundryvtt-babele/-/raw/master/DEVELOPER_MIGRATION_2_8_0.md +// Every converter below used to resolve an English item name (a career +// mentioned inline in another document's text, a skill in a career's skill +// list, a bestiary trait/prayer/spell/talent/trapping on an NPC, ...) to +// German by calling game.babele.translate(pack, {name, ...}, ...). That no +// longer works in the installed Babele version: matching is driven entirely +// by mapping.matchKeyCandidates(), which returns no candidates for a bare +// stub object, so the call silently falls through and returns the input +// unchanged for EVERY name, matched or not (verified live - even definite, +// unambiguous entries like the "Charm" skill or the "Spy" career come back +// unchanged). The old code detected "no match" by comparing the result +// against the input, which is doubly wrong here: it never once succeeds, and +// even if it had, it would mislabel any German name that happens to be +// spelled like its English source (e.g. "Agitator", "Slayer", "Duellist") as +// untranslated. +// Fix: read our own compendium/*.json dictionaries directly (same files +// Babele itself loads via dir:'compendium'), bypassing Babele's matcher. +// __dictCaches[tag] is a Map built once from +// every pack tagged with `tag`, in priority order (first pack with an entry +// for a given key wins), mirroring the old "break on first match" loops. +const __dictCaches = {}; +async function __buildDictCache(...validCompendiums) { + const cache = new Map(); + // Fetch every pack's dictionary in parallel (there can be a dozen+ packs per + // tag, e.g. "spell"), then merge sequentially in pack order so the "first + // pack wins" precedence from the old per-lookup loops is preserved. + const fetched = await Promise.all(validCompendiums.map(async (compData) => { + try { + const resp = await fetch(`modules/wh4-de-translation/compendium/${compData.metadata.id}.json`); + if (!resp.ok) return null; + return await resp.json(); + } catch (e) { + console.warn(`WFRP4E-DE | Konnte Wörterbuch für ${compData.metadata.id} nicht laden`, e); + return null; + } + })); + for (const data of fetched) { + for (let [enName, entry] of Object.entries(data?.entries ?? {})) { + if (!cache.has(enName) && entry?.name) cache.set(enName, entry); + } + } + return cache; +} + Hooks.once('babele.init', () => { if (typeof game.babele !== 'undefined') { @@ -155,65 +198,41 @@ Hooks.once('babele.init', () => { // Pre-define functions for cross-converter calls (Babele 2.8+ wraps converters // as objects, so game.babele.converters.X() no longer works as a plain call) const career_skills_fn = (skills_list) => { - let validCompendiums = game.wfrp4e.tags.getPacksWithTag("skill") - //DEBUG: console.log( "Thru here ...", compendium, skills_list); if (skills_list) { - let i; - let len = skills_list.length; let re = /(.*)\((.*)\)/i; - for (i = 0; i < len; i++) { + for (let i = 0; i < skills_list.length; i++) { skills_list[i] = skills_list[i].trim(); - for (let compData of validCompendiums) { - let translItem = game.babele.translate(compData.metadata.id, { name: skills_list[i], type: "skill" }, true) - let transl = translItem?.name || undefined - if (!transl) transl = skills_list[i] - if (transl == skills_list[i]) { - let res = re.exec(skills_list[i]); - if (res) { - let subword = game.i18n.localize(res[2].trim()); - let s1 = res[1].trim() + " ()"; - translItem = game.babele.translate(compData.metadata.id, { name: s1, type: "skill" }, true) - let translw = translItem?.name || undefined - if (translw && translw != s1) { - let res2 = re.exec(translw); - transl = res2[1].trim() + " (" + subword + ")"; - } else { - s1 = res[1].trim() + " ( )"; - translItem = game.babele.translate(compData.metadata.id, { name: s1, type: "skill" }, true) - translw = translItem?.name || undefined - if (translw) { - let res2 = re.exec(translw); - transl = res2[1].trim() + " (" + subword + ")"; - } else { - transl = res[1].trim() + " (" + subword + ")"; - } - } - } + let transl = __dictCaches.skill?.get(skills_list[i])?.name; + if (!transl) { + // Grouped skill with a specialization, e.g. "Art (Painting)": look up + // the group's own template entry ("Art ()"/"Art ( )") for the German + // group name, and localize the specialization word separately. + let res = re.exec(skills_list[i]); + if (res) { + let subword = game.i18n.localize(res[2].trim()); + let base = res[1].trim(); + let template = __dictCaches.skill?.get(base + " ()")?.name ?? __dictCaches.skill?.get(base + " ( )")?.name; + let res2 = template ? re.exec(template) : null; + transl = (res2 ? res2[1].trim() : base) + " (" + subword + ")"; } - skills_list[i] = transl; - if (translItem?.system) - break; } + skills_list[i] = transl || skills_list[i]; } } return skills_list }; const career_careergroup_fn = (value) => { - if (value == 'Slayer') return "Slayer"; + let entry = __dictCaches.career?.get(value); + if (entry?.name) return entry.name; + // Dictionary lookups that don't exist under their English career name at all + // (e.g. "Druidic Priest" isn't a literal key in any compendium/*.json) stay + // hardcoded here rather than forcing a fake dictionary entry for them. if (value == 'Druidic Priest') return "Druide"; - let validCompendiums = game.wfrp4e.tags.getPacksWithTag("career"); - // Try every career-tagged pack (core + supplements like Up in Arms, Archives, EIS, ...) - // before giving up - a career group's defining career may only exist in one of them, - // so returning after the first pack silently left it untranslated whenever that pack - // happened not to be the one with the match (e.g. "Spy" only exists in wfrp4e-core). - // IMPORTANT: game.babele.translate() returns the ORIGINAL stub object unchanged when a - // pack has no matching dictionary entry - it never returns null/undefined - so `newName` - // is truthy even on a miss (it's just `value` again). Must compare against `value` to - // detect an actual match, otherwise the very first pack always "wins" by default. - for (let compData of validCompendiums) { - let newName = game.babele.translate(compData.metadata.id, { name: value })?.name; - if (newName && newName !== value) return newName; + if (!__dictCaches.career) { + // Cache not built yet (called before babele.init's fetches resolved) - + // return the English name rather than a false "not translated" error. + return value; } ui.notifications.error("Das Übersetzen der Karriere " + value + " ist nicht möglich. Sie ist wahrscheinlich nicht übersetzt.", { permanent: true }); return value; @@ -312,41 +331,29 @@ Hooks.once('babele.init', () => { }, "career_talents": (talents_list) => { - let validCompendiums = game.wfrp4e.tags.getPacksWithTag("talent") - let i; if (talents_list) { - let len = talents_list.length; let re = /(.*)\((.*)\)/i; - for (i = 0; i < len; i++) { - for (let compData of validCompendiums) { - let translItem = game.babele.translate(compData.metadata.id, { name: talents_list[i] }, true); - // Specific case management - if (talents_list[i] === "Trapper") { - translItem = game.babele.translate(compData.metadata.id, { name: "a7v422EZcOUUC20X" }, true); - } - if (talents_list[i] === "Inspiring") { - translItem = game.babele.translate(compData.metadata.id, { name: "WCXnFSV4WOSmzzc4" }, true); - } - //console.log("Search talent name:", compData.metadata.id, talents_list[i], translItem); - let transl = translItem?.name || undefined - if (!transl) transl = talents_list[i] - if (transl == talents_list[i]) { - let res = re.exec(talents_list[i]); - if (res) { - let subword = game.i18n.localize(res[2].trim()); - let s1 = res[1].trim(); // No () in talents table - translItem = game.babele.translate(compData.metadata.id, { name: s1 }, true) - let translw = translItem?.name || undefined - //console.log("Search talent name:", compData.metadata.id, s1, translw); - if (translw && translw != s1) { - transl = translw.trim() + " (" + subword + ")"; - } + for (let i = 0; i < talents_list.length; i++) { + // Specific case management: "Trapper"/"Inspiring" collide with another + // document's name in the raw dictionary, so those two are looked up by + // their stable GUID key instead (see the identical special-case in the + // "talent" branch of bestiary_traits below). + let key = talents_list[i]; + if (key === "Trapper") key = "a7v422EZcOUUC20X"; + if (key === "Inspiring") key = "WCXnFSV4WOSmzzc4"; + let transl = __dictCaches.talent?.get(key)?.name; + if (!transl) { + let res = re.exec(talents_list[i]); + if (res) { + let subword = game.i18n.localize(res[2].trim()); + let s1 = res[1].trim(); // No () in talents table + let baseTransl = __dictCaches.talent?.get(s1)?.name; + if (baseTransl && baseTransl != s1) { + transl = baseTransl.trim() + " (" + subword + ")"; } } - talents_list[i] = transl; - if (translItem?.system) - break; } + talents_list[i] = transl || talents_list[i]; } } return talents_list; @@ -404,20 +411,15 @@ Hooks.once('babele.init', () => { special = " (" + game.i18n.localize(res[2].trim()) + ")"; // And the special keyword } } - let validCompendiums = game.wfrp4e.tags.getPacksWithTag("trait") - for (let compData of validCompendiums) { - let trait_fr = game.babele.translate(compData.metadata.id, { name: name_en, system: { description: { value: trait_en.system.description.value } } }, true) - if (trait_fr?.name && trait_fr?.name != name_en) { - trait_fr.name = trait_fr.name || trait_en.name - trait_en.name = nbt + trait_fr.name + special; - if (trait_en.system?.description?.value && trait_fr.system?.description?.value) { - trait_en.system.description.value = trait_fr.system.description.value; - } - if (trait_en?.system?.specification && isNaN(trait_en.system.specification?.value)) { // This is a string, so translate it - //console.log("Translating : ", trait_en.system.specification.value); - trait_en.system.specification.value = game.i18n.localize(trait_en.system.specification.value.trim()); - } - break // Translation has been found, skip other compendiums + let trait_fr = __dictCaches.trait?.get(name_en); + if (trait_fr?.name) { + trait_en.name = nbt + trait_fr.name + special; + if (trait_en.system?.description?.value && trait_fr.description) { + trait_en.system.description.value = trait_fr.description; + } + if (trait_en?.system?.specification && isNaN(trait_en.system.specification?.value)) { // This is a string, so translate it + //console.log("Translating : ", trait_en.system.specification.value); + trait_en.system.specification.value = game.i18n.localize(trait_en.system.specification.value.trim()); } } } else if (trait_en.type == "skill") { @@ -430,46 +432,30 @@ Hooks.once('babele.init', () => { special = " (" + game.i18n.localize(res[2].trim()) + ")"; // And the special keyword } } - let validCompendiums = game.wfrp4e.tags.getPacksWithTag("skill") - for (let compData of validCompendiums) { - let trait_fr = game.babele.translate(compData.metadata.id, { name: name_en, system: { description: { value: trait_en.system.description.value } } }, true) - //console.log(">>>>> Skill ?", name_en, special, trait_fr.name, trait_fr); - if (trait_fr?.name && trait_fr?.name != name_en) { - trait_fr.name = trait_fr.name || name_en - trait_en.name = trait_fr.name + special; - trait_en.system.description.value = trait_fr.system.description.value; - break; // Translation has been found, skip other compendiums - } + let trait_fr = __dictCaches.skill?.get(name_en); + if (trait_fr?.name) { + trait_en.name = trait_fr.name + special; + if (trait_fr.description) trait_en.system.description.value = trait_fr.description; } } else if (trait_en.type == "prayer") { - let validCompendiums = game.wfrp4e.tags.getPacksWithTag("prayer") - for (let compData of validCompendiums) { - let trait_fr = game.babele.translate(compData.metadata.id, { name: name_en, system: { description: { value: trait_en.system.description.value } } }, true) - if (trait_fr?.name && trait_fr?.name != name_en) { - //DEBUG : console.log(">>>>> Prayer ?", name_en, special, trait_fr.name ); - WFRP4FrTranslation.parseSpellContent(trait_en) - trait_fr.name = trait_fr.name || name_en - trait_en.name = trait_fr.name + special; - if (trait_fr.system?.description?.value) { - trait_en.system.description.value = trait_fr.system.description.value; - } - break; - } + // parseSpellContent must run regardless of whether this prayer's name has a + // dictionary entry: the wfrp4e system's own damage-formula evaluator matches + // characteristic-bonus text against the CURRENT locale's localized string + // (wfrp4e.js: formula.replace(config.characteristicsBonus[ch].toLowerCase(), ...)), + // so a raw English "Willpower Bonus" formula throws a SyntaxError under a German + // locale even when the prayer/spell itself isn't in our dictionary at all. + WFRP4FrTranslation.parseSpellContent(trait_en) + let trait_fr = __dictCaches.prayer?.get(name_en); + if (trait_fr?.name) { + trait_en.name = trait_fr.name + special; + if (trait_fr.description) trait_en.system.description.value = trait_fr.description; } } else if (trait_en.type == "spell") { - let validCompendiums = game.wfrp4e.tags.getPacksWithTag("spell") - for (let compData of validCompendiums) { - let trait_fr = game.babele.translate(compData.metadata.id, { name: name_en, system: { description: { value: trait_en.system.description.value } } }, true) - if (trait_fr?.name && trait_fr?.name != name_en) { - //DEBUG : console.log(">>>>> Spell ?", name_en, special, trait_fr); - WFRP4FrTranslation.parseSpellContent(trait_en) - trait_fr.name = trait_fr.name || name_en - trait_en.name = trait_fr.name + special; - if (trait_fr.system?.description?.value) { - trait_en.system.description.value = trait_fr.system.description.value; - } - break; - } + WFRP4FrTranslation.parseSpellContent(trait_en) + let trait_fr = __dictCaches.spell?.get(name_en); + if (trait_fr?.name) { + trait_en.name = trait_fr.name + special; + if (trait_fr.description) trait_en.system.description.value = trait_fr.description; } } else if (trait_en.type == "talent") { if (name_en.includes("(") && name_en.includes(")")) { // Then process specific skills name with (xxxx) inside @@ -481,65 +467,32 @@ Hooks.once('babele.init', () => { special = " (" + game.i18n.localize(res[2].trim()) + ")"; // And the special keyword } } - let validCompendiums = game.wfrp4e.tags.getPacksWithTag("talent") - for (let compData of validCompendiums) { - if (name_en === "Trapper") { - name_en = "a7v422EZcOUUC20X" - } - if (name_en === "Inspiring") { - name_en = "WCXnFSV4WOSmzzc4" - } - trait_en.name = name_en // Reset the name to the original one - let trait_fr = game.babele.translate(compData.metadata.id, trait_en, true) - if (trait_fr?.name && trait_fr?.name != name_en) { - trait_fr.name = trait_fr.name || name_en // Security since babele v10 - //console.log(">>>>> Talent ?", trait_fr, name_en, special, trait_fr.name); - if (trait_fr.name && (trait_fr.name == "Sprinter" || trait_fr.name != name_en)) { // Talent translated! - trait_en.name = trait_fr.name.trim() + special - if (trait_fr.system?.tests?.value) { // Why ??? - trait_en.system.tests.value = trait_fr.system.tests.value; - } - if (trait_fr.system?.description?.value) { // Why ??? - trait_en.system.description.value = trait_fr.system.description.value; - } - } - break; - } + let talentKey = name_en; + if (talentKey === "Trapper") talentKey = "a7v422EZcOUUC20X"; + if (talentKey === "Inspiring") talentKey = "WCXnFSV4WOSmzzc4"; + let trait_fr = __dictCaches.talent?.get(talentKey); + if (trait_fr?.name) { + trait_en.name = trait_fr.name.trim() + special + if (trait_fr.tests) trait_en.system.tests.value = trait_fr.tests; + if (trait_fr.description) trait_en.system.description.value = trait_fr.description; } } else if (trait_en.type == "career") { - let validCompendiums = game.wfrp4e.tags.getPacksWithTag("career") - for (let compData of validCompendiums) { - let career_fr = game.babele.translate(compData.metadata.id, trait_en, true); - if (career_fr?.name && career_fr?.name != name_en) { - trait_en.name = career_fr.name || trait_en.name - // DEBG: console.log(">>>>> Career ?", career_fr.name ); - trait_en.system = foundry.utils.duplicate(career_fr.system); - break; - } + let career_fr = __dictCaches.career?.get(name_en); + if (career_fr?.name) { + trait_en.name = career_fr.name + if (career_fr.description) trait_en.system.description.value = career_fr.description; } } else if (trait_en.type == "vehicleRole") { - let validCompendiums = game.wfrp4e.tags.getPacksWithTag("vehicleRole") - for (let compData of validCompendiums) { - let role_fr = game.babele.translate(compData.metadata.id, trait_en, true); - if (role_fr?.name && role_fr?.name != name_en) { - trait_en.name = role_fr.name || trait_en.name - // DEBG: console.log(">>>>> Role ?", role_fr.name ); - trait_en.system = foundry.utils.duplicate(role_fr.system); - break; - } + let role_fr = __dictCaches.vehicleRole?.get(name_en); + if (role_fr?.name) { + trait_en.name = role_fr.name + if (role_fr.description) trait_en.system.description.value = role_fr.description; } } else if (trait_en.type == "trapping" || trait_en.type == "weapon" || trait_en.type == "armour" || trait_en.type == "container" || trait_en.type == "money") { - let validCompendiums = game.wfrp4e.tags.getPacksWithTag(["trapping"], ["weapon", "armour", "container", "money"]) - for (let compData of validCompendiums) { - let trapping_fr = game.babele.translate(compData.metadata.id, { name: name_en, system: { description: { value: trait_en.system.description.value } } }, true); - if (trapping_fr?.name && trapping_fr?.name != name_en) { - //console.log(">>>>> Trapping ?", name_en, trapping_fr.name); - trait_en.name = trapping_fr.name || trait_en.name - if (trapping_fr.system?.description?.value) { - trait_en.system.description.value = trapping_fr.system.description.value - } - break; - } + let trapping_fr = __dictCaches.trapping?.get(name_en); + if (trapping_fr?.name) { + trait_en.name = trapping_fr.name + if (trapping_fr.description) trait_en.system.description.value = trapping_fr.description; } } } @@ -666,6 +619,20 @@ Hooks.once('babele.init', () => { /*---------------------------------------------------------------------*/ Hooks.once('ready', () => { + // game.wfrp4e isn't guaranteed to exist yet during 'babele.init' (that hook can + // fire before the wfrp4e system finishes its own setup), so the dictionary + // caches are built here instead, once 'ready' guarantees game.wfrp4e is live. + // Exposed as a promise so other modules (addon-register.js's completion chat + // message) can wait for these fetches to genuinely finish before announcing + // the translation as fully loaded, instead of relying on a fixed timeout. + const dictCacheBuilds = ["career", "skill", "trait", "prayer", "spell", "talent", "vehicleRole"] + .map(tag => __buildDictCache(...game.wfrp4e.tags.getPacksWithTag(tag)).then(cache => { __dictCaches[tag] = cache; })); + dictCacheBuilds.push( + __buildDictCache(...game.wfrp4e.tags.getPacksWithTag(["trapping"], ["weapon", "armour", "container", "money"])) + .then(cache => { __dictCaches.trapping = cache; }) + ); + game.wfrp4efr.dictCachesReady = Promise.all(dictCacheBuilds); + console.log("WFRP4E-DE | Modul ist übersetzt."); ui.notifications.info("WFRP4E-DE: Übersetzung ist fertig geladen.");