-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmod.js
1798 lines (1657 loc) · 56.5 KB
/
mod.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This whole mess deserves an explanation. When the game loads, the following
* normally happens:
*
* - Before the game's main() has a chance to run, we patch the ig.LANG_DETAILS
* (which contains the locale information) and sc.LANGUAGE, which
* contain a mapping from indexes to locales. These indexes are used in the
* settings dialogs. These are typically not available when the game's code
* is loaded, but only later during initialisation of main's dependencies.
*
* - main() runs, and tries to determine the final language to be used by the
* game. For that, it looks at localStorage and if not, it auto-detects it
* with LANG_DETAILS's useFor. if localStorage contains an unknown locale,
* this part of the code can recover from it by switch back to english
* and saving that in localStorage. It should be noted that localStorage
* represent a locale as text (e.g. en_US).
*
* - Once the "final" language is determined, it is stored in ig.currentLang.
* This is the language that will be used for the remaining of the game, and
* changing it requires a restart. We patch an unrelated part of the code
* just to have an event trigger when this happens, because other things in
* this mod absolutely want to know which language we should actually patch
* in.
*
* - The game continues to load, and starts to initialize its options in
* sc.OptionModel's constructor. This is where the mess begins.
* These is a game option named "language" that duplicate what's in
* localStorage, except it's an integer and not a string, because that's
* easier to handle in OptionModel. The game has a mapping from this
* integer to a string, in a local variable that we can't access.
* Duplicating it would be too fragile. The constructor first initializes
* "language" to it's default value, which is normally 0, but i think previous
* versions of the game could leave it unset.
*
* - Then, it uses the internal mapping to convert the final language into
* an integer. This code has the property that if the final language is
* unknown to the mapping, then "language" is left unmodified. So if this a
* locale added by us, "language" may be 0 or it may be undefined, in which
* case we better patch this quickly, before the game crashes.
*
* - Right after that, it calls code (let's call it setOption, which is much
* clearer than its actual name _checkSystemSettings), that... translate the
* "language" integer into a locale name using the internal mapping, before
* storing it in localStorage. This setOption() thing is tricky, because it
* is used in loads of places other than the constructor. But say that we
* cannot detect this case reliably, so we allow "language" values that do
* not match the final language at this point.
*
* - The game continue to load, and loads the file containing both savefiles
* and game options (or select default options). After that, it calls
* onStorageGlobalLoad(), which the options that were loaded.
* it will update the options from what was loaded and then it will call...
* setOption() on them. Yep. We patch onStorageGlobalLoad to patch the
* "language" mess there, because it is only called during initialization.
*
* - If the user goes into the options and select a language, then setOption()
* is also called in this case. The user basically clicked on an integer,
* and this function is responsible for storing it into localStorage as well
* as the options.
*
* - When the game wants to save options, it calls onStorageGlobalSave, which
* we also patch. We do not want to save our added locales's integer into
* the save file, because the game cannot recover from that if localize-me
* gets uninstalled. So we always save 0 and we make it that
* onStorageGlobalLoad ignores the saved option if the final locale is a
* custom one.
*/
class GameLocaleConfiguration {
constructor() {
// locale definitions here. the native ones are not present.
this.added_locales = {};
// native locales are mapped to null, because we don't know
// their indexes. It can also be used to distinguish between
// added locales and completely unknown indexes.
this.localedef_by_index = {};
// Total number of locales in the game, including the native
// ones.
this.locale_count = 0;
// Until the game determines the language to use for this run,
// this is a promise. After which, it is the language used
// by the game.
this.final_locale = new Promise((resolve) => {
this.set_final_locale = (locale) => {
console.log("final language set to ", locale);
this.final_locale = locale;
resolve(locale);
};
});
// When all locales have been loaded from mods, this resolves
// to an locale -> localedef mapping
this.all_locales = new Promise(resolve => {
this.set_all_locales_ready
= () => resolve(this.added_locales);
});
}
// Add a custom locale definition. Can be called any time before the
// patch_game_locale_definitions() is called, which happen after the
// game starts but before main().
add_locale_definition(name, localedef) {
if (name in this.added_locales) {
console.error("Language " + name + " added twice");
return;
}
if (this.locale_count) {
console.error("Language " + name
+ " is added too late !");
return;
}
this.added_locales[name] = localedef;
}
// Called during the initialisation of the game. The final locale
// is typically unknown at this point.
patch_game_locale_definitions () {
let count = 0;
for (const locale in window.ig.LANG_DETAILS) {
if (this.added_locales[locale]) {
console.warn("Language " + locale
+ " already there");
delete this.added_locales[locale];
}
count++;
}
for (const lang in window.sc.LANGUAGE) {
// lang is not a locale name... this would have made
// things much simpler if it was...
const locale_index = window.sc.LANGUAGE[lang];
this.localedef_by_index[locale_index] = null;
}
const added = Object.keys(this.added_locales);
added.sort();
for (const locale of added) {
const options = this.added_locales[locale];
const locale_index = count++;
options.localizeme_global_index = locale_index;
window.ig.LANG_DETAILS[locale] = options;
window.sc.LANGUAGE["LOCALIZEME"+locale] = locale_index;
this.localedef_by_index[locale_index] = locale;
}
this.locale_count = count;
this.set_all_locales_ready();
}
/**
* Get the language that the game will use for the remaining of this
* session.
*
* If unknown, a promise is returned, else, a locale name is returned.
* Note that, when the game is loaded, the same information is
* available at ig.currentLang. During loading, however,
* ig.currentLang might be incorrect.
*/
get_final_locale () {
return this.final_locale;
}
get_localedef_sync() {
return window.ig.LANG_DETAILS[this.final_locale];
}
async get_localedef() {
await this.final_locale;
return window.ig.LANG_DETAILS[this.final_locale];
}
/// Get all locales once they are loaded.
async get_all_locales() {
return this.all_locales;
}
/*
* patch lang/sc/gui.$locale.json/labels/options/language.group
*
* this is an array indexed by locale indexes, which is used in the
* option menu to display languages.
*/
patch_game_language_list(language_list) {
for (let patched = language_list.length;
patched < this.locale_count;
++patched) {
const locale = this.localedef_by_index[patched];
if (!locale) {
console.error("language array out of sync ?",
"patched ", patched, " out of ",
this.locale_count, " size is ",
language_list.length);
language_list.push("ERROR");
continue;
}
const lang_name = this.added_locales[locale].language;
language_list.push(lang_name[this.final_locale]
|| lang_name[locale]
|| "ERROR NO LANGUAGE");
}
}
// Will only work for added locales, we can't get to the others.
get_index_of_locale(locale) {
const localedef = this.added_locales[locale];
if (!localedef)
return null;
return localedef.localizeme_global_index;
}
hook_into_game() {
// ig.LANG_DETAILS defined in game.config
// sc.LANGUAGE_ICON_MAPPING may need an update if we want flags
// one day.
// sc.LANGUAGE defined in game.feature.model.options-model
ig.module("localize_put_locales").requires(
"game.config",
"game.feature.model.options-model"
).defines(this.patch_game_locale_definitions.bind(this));
const localedef_by_index = this.localedef_by_index;
const index_by_locale = this.get_index_of_locale.bind(this);
// We completely ignore the locale from the save file for
// added locales.
const patch_loaded_globals = function (globals) {
const id = index_by_locale(ig.currentLang);
if (id !== null) {
if (globals.options === undefined)
globals.options = {};
globals.options.language = id;
}
this.parent(globals);
};
// And we save a 0 if it is an added locale.
const patch_saved_globals = function (globals) {
this.parent(globals);
const locale_index = globals.options["language"];
if (localedef_by_index[locale_index])
globals.options["language"] = 0;
};
// Hack up the function called to check and set parameters,
// either initialized on startup, loaded from the save file or
// manually selected by the user. We can't really tell.
const patched_check_settings = function(setting) {
if (setting !== "language")
return this.parent(setting);
// This should not happen anymore, on the latest game
// versions.
if (!this.values.hasOwnProperty("language"))
this.values.language = 0;
let locale = localedef_by_index[this.values.language];
// Previous localize-me versions saved the locale index
// in the options. If the index does not match a known
// locale, then recover from it quickly before bad
// things happens.
if (locale === undefined) {
console.log("Recovered from missing locale");
this.values.language = 0;
locale = null;
}
if (locale === null)
// native locale, we don't have access to
// the mapping...
return this.parent(setting);
localStorage.setItem("IG_LANG", locale);
console.log("Locale set to " + locale
+ " in localStorage");
return undefined;
};
ig.module("localize_patch_up_option_model").requires(
"game.feature.model.options-model"
).defines(function() {
sc.OptionModel.inject({
_checkSystemSettings : patched_check_settings,
onStorageGlobalLoad : patch_loaded_globals,
onStorageGlobalSave : patch_saved_globals,
});
});
const set_final_locale = this.set_final_locale.bind(this);
const init_lang = function() {
this.parent();
set_final_locale(ig.currentLang);
};
// ig.Lang, to find out when the locale is finally known.
// This is known in ig.main, and this constructor is called
// afterward. (this object is responsible for loading the
// lang files).
ig.module("localize_language_finalized").requires(
"impact.base.lang"
).defines(function() {
ig.Lang.inject({ init: init_lang });
});
}
}
// This thing is turning into a god class...
class JSONPatcher {
constructor(game_locale_config) {
this.game_locale_config = game_locale_config;
this.map_file = undefined;
this.url_cache = {};
// Function returned by various methods when things are not
// found. This allows callers to either use it blindly or check
// if it not_found
this.not_found = () => null;
}
// Fetch the thing at url and return its xhr responseText.
fetch_stuff(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open("GET", url, true);
req.onerror = reject;
req.onreadystatechange = () => {
if (req.readyState !== req.DONE
|| req.status !== 200)
return; // reject ?
resolve(req.responseText);
};
req.send();
});
}
/*
* If thing is a string, treat it as an URL and fetch its JSON,
* else assume it is a function and call it without any argument.
* The function may return a promise.
*
* JSON objects refered by their URL are cached.
*/
async fetch_or_call(thing) {
if (thing.constructor !== String)
return await thing();
let ret = this.url_cache[thing];
if (!ret) {
ret = this.fetch_stuff(thing);
ret = ret.then(json => JSON.parse(json));
this.url_cache[thing] = ret;
ret.then(() => { delete this.url_cache[thing]; });
}
return ret;
}
async load_map_file() {
const localedef = await this.game_locale_config.get_localedef();
if (!localedef) {
console.error("trying to patch locales without locale");
return null;
} else if (!localedef.map_file || !localedef.from_locale)
// native, no need to patch
return null;
const result = await this.fetch_or_call(localedef.map_file);
if (typeof result === "function")
return result;
const prefix = localedef.url_prefix || "";
return (url_to_patch) => {
const ret = result[url_to_patch];
if (!ret)
return null;
return prefix + ret;
};
}
/*
* Get a map file for the given current locale.
*
* This returns a map_file function that maps assets path relative to
* assets/data/ into a translation pack url, or a function
* returning a json or function.
*
* If nothing needs to be patched, this returns null.
*
* the map_file function is cached for later use.
*/
async get_map_file() {
if (this.map_file === undefined)
this.map_file = this.load_map_file();
return this.map_file;
}
/*
* Get a translation pack for the given path and json and locale.
*
* The path must be relative to assets/data.
*
* This returns a function mapping a dict path to a translation result.
* a dict path is basically a cursor to a element of a json file.
* e.g. if file hello/world.json contains {"foo":["bar"]},
* then dict path "hello/world.json/foo/0" points to "bar".
*
* a translation result is either a translated string or an object with
* these optional fields:
*
* - orig: the original text from from_locale, if the loaded file
* does not match this string, then the translation is likely
* stale and should not be used
* - text: the translated text to use.
* - ciphertext: the translated text, encrypted with AES-CBC with
* the key equal to MD5(original text). This idiotic
* scheme is mainly here for copyright reasons.
* - mac: a HMAC-MD5 of the translated text with key MD5(original text)
* for detecting stale translations and not returning garbage.
*
* If a translation result is unknown, null or undefined is returned.
*/
async get_transpack(map_file, json_path, json) {
const url_or_func = map_file(json_path, json);
if (!url_or_func)
return this.not_found;
const result = await this.fetch_or_call(url_or_func);
if (typeof result !== "function")
return dict_path => result[dict_path];
return result;
}
/**
* If 'json' is an Object, call cb(value, key) for each key.
* If 'json' is an Array, call cb(value, index) for each element in it.
* Will ignore anything else.
*/
walk_json(json, cb) {
if (json === null)
return;
if (json.constructor === Array)
json.forEach(cb);
if (json.constructor === Object)
for (const index in json)
if (json.hasOwnProperty(index))
cb(json[index], index);
}
/**
* Iterate over all lang labels found in the object and call the
* callback with (lang_label, dict_path).
* It should be possible to modify the lang_label inside the callback.
*/
for_each_langlabels(json, dict_path_prefix, callback) {
const localedef = this.game_locale_config.get_localedef_sync();
if (json !== null && json[localedef.from_locale]) {
callback(json, dict_path_prefix);
return;
}
this.walk_json(json, (value, index) => {
const sub = dict_path_prefix + "/" + index;
this.for_each_langlabels(value, sub, callback);
});
}
/**
* Get the HMAC of the given string or CryptoJS.lib.WordArray.
*
* key must be a CryptoJS.lib.WordArray
*
* Returns a CryptoJS.lib.WordArray with the hmacmd5
*/
hmacmd5(message, key) {
/// The loaded CryptoJS has a CryptoJS.HmacMD5 symbol ... that
/// does not work. It tries to reference CryptoJS.HMAC, which
/// doesn't exist. Hopefully, HMAC isn't complicated to code.
const outer = key.clone();
const to_words = x => CryptoJS.lib.WordArray.create(x);
// pad 16 bytes to 64 -> 48 bytes, which is 12 u32
outer.concat(to_words(Array.from({length: 12}, () => 0)));
const ip
= outer.words
.map((v,i,a) => 0x6a6a6a6a ^ (a[i]^=0x5c5c5c5c));
outer.concat(CryptoJS.MD5(to_words(ip).concat(message)));
return CryptoJS.MD5(outer);
}
/**
* Decrapt the given string using the given original text.
*
* Return null if the decryption failed.
* May throw exceptions if CryptJS is buggy.
*/
decrapt_string(trans_result, orig) {
// the loaded CryptoJS only supports AES CBC with Pkcs7 and
// MD5... This should be more than enough for the "security"
// that we need: requiring the game files to get the
// translation.
const ciphertext
= CryptoJS.enc.Base64.parse(trans_result.ciphertext);
const key = CryptoJS.MD5(orig);
const param = CryptoJS.lib.CipherParams.create({ ciphertext,
iv:key});
const text = CryptoJS.AES.decrypt(param, key,
{ mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
iv: key}
);
// This happens if the padding is incorrect, and the last byte
// of the decryption is longer than the actual input...
if (text.sigBytes < 0)
return null;
if (trans_result.mac) {
// if i don't do this, then calculating the md5 of it
// fails.
text.clamp();
// wait, CryptoJS.HmacMD5 does not work ? Crap.
// var correct_mac = CryptoJS.HmacMD5(text, key);
const correct_mac = this.hmacmd5(text, key);
const mac = CryptoJS.enc.Base64.stringify(correct_mac);
if (trans_result.mac !== mac)
// stale translation
return null;
}
return CryptoJS.enc.Utf8.stringify(text);
}
/**
* Given a translation result, get the translation of the given
* string or lang label.
*
* This function does not support lang labels mappings to array or
* objects. Thanksfully, these appear to be currently unused.
*
* Returns a string, or null if the translation is unknown.
*/
get_translated_string(trans_result, lang_label_or_string) {
const localedef = this.game_locale_config.get_localedef_sync();
if (trans_result === null || trans_result === undefined)
return null;
if (trans_result.constructor === String)
return trans_result;
const orig = (lang_label_or_string[localedef.from_locale]
|| lang_label_or_string);
if (trans_result.orig && orig && trans_result.orig !== orig)
// original text has changed, translation is stale.
return null;
if (trans_result.text)
return trans_result.text;
if (!trans_result.ciphertext)
return null;
try {
return this.decrapt_string(trans_result, orig);
} catch (e) {
console.error(e);
console.error("decryption failed hard, is translation "
+ "stale ?");
return null;
}
}
/**
* Given a translation result, get the translation of the given
* string or lang label.
*
* Always returns a string, unlike get_translated_string().
*
* If the translation is unknown, then call the missing callback
* or return the original text prefixed by "--", unless skip_missing
* is true, in which case it will be returned unmodified.
*/
get_text_to_display(trans_result, lang_label_or_string, dict_path,
skip_missing) {
const localedef = this.game_locale_config.get_localedef_sync();
let ret = this.get_translated_string(trans_result,
lang_label_or_string);
if (ret !== null) {
if (!localedef.text_filter)
return ret;
return localedef.text_filter(ret, trans_result);
}
const missing = localedef.missing_cb;
if (missing)
ret = missing(lang_label_or_string, dict_path);
if (!ret) {
ret = (lang_label_or_string[localedef.from_locale]
|| lang_label_or_string);
if (!skip_missing)
ret = "--" + ret;
}
return ret;
}
/*
* Patch the lang labels in the json object loaded at path
* for the given current locale.
*
* Resolves to the json parameter, possibly modified.
*/
async patch_langlabels(path, json) {
const map_file = await this.get_map_file();
if (!map_file)
// native locale
return json;
const pack = await this.get_transpack(map_file, path, json)
.catch(() => this.not_found);
const patch_lang_label = (lang_label, dict_path) => {
const trans = pack(dict_path, lang_label);
lang_label[ig.currentLang]
= this.get_text_to_display(trans, lang_label,
dict_path);
};
this.for_each_langlabels(json, path, patch_lang_label);
return json;
}
/*
* Return a pack suitable for patching langfiles.
*
* This is like get_transpack(), except this also handles if the
* translation pack is a full langfile replacement. Support for that is
* deprecated.
*/
async get_langfile_pack(map_file, path, json) {
let pack;
try {
pack = await this.get_transpack(map_file, path, json);
} catch (error) {
console.warn("failed path", path, error);
return this.not_found;
}
if (pack("DOCTYPE") !== "STATIC-LANG-FILE")
return pack; // normal pack.
console.log("Using a langfile as a packfile is deprecated");
// it's not really a pack ... more like a json langfile that
// we parsed like a pack, but we can recover.
if (pack("feature") !== json["feature"]) {
console.error("mismatch between lang file feature :",
pack("feature"), "!=", json["feature"]);
return this.not_found;
}
const labels = pack("labels");
return ((prefix, dict_path) => {
if (!dict_path.startsWith(prefix)) {
console.error("invalid dict path for langfile",
dict_path);
return null;
}
let cursor = labels;
for (const component
of dict_path.substr(prefix.length).split("/"))
cursor = cursor && cursor[component];
if (!cursor && cursor !== "")
return null;
return cursor;
}).bind(null, path + "/labels/");
}
/*
* Assume the json object is a langfile residing at path
* and patch every value in it using the given pack.
*
* Resolves to the json parameter after modifying it.
*/
patch_langfile_from_pack(json, path, pack) {
const recurse = (json, dict_path_prefix) =>
this.walk_json(json, (value, index) => {
const dict_path
= dict_path_prefix + "/" + index;
if (value.constructor !== String) {
recurse(value, dict_path);
return;
}
let trans = pack(dict_path, value);
trans = this.get_text_to_display(trans, value,
dict_path);
json[index] = trans;
});
recurse(json.labels, path + "/labels");
}
/*
* Patch lang/sc/gui.*.json when used with ccloader v3
*
* This reimplements ccloader v3's localized fields
*/
patch_ccloader3_mods(json, path, pack) {
if (!window.modloader || !window.modloader.loadedMods)
return; // not ccloader v3
const { from_locale, text_filter }
= this.game_locale_config.get_localedef_sync();
const { options } = json.labels;
const true_filter = text_filter ? text_filter : (text => text);
const localize_field = (maybe_ll, field_name, prefix) => {
// technically not a lang label, but close enough
if (!maybe_ll)
return " ";
if (maybe_ll[ig.currentLang])
return true_filter(maybe_ll[ig.currentLang],
{});
if (maybe_ll.constructor !== String
&& maybe_ll[from_locale] === undefined)
return maybe_ll["en_US"] || " ";
const dict_path = `${prefix}/${field_name}`;
const trans = pack(dict_path, maybe_ll);
const text = this.get_text_to_display(trans, maybe_ll,
dict_path, true);
return text;
};
window.modloader.installedMods.forEach((mod, id) => {
const modEnabled_id = `modEnabled-${id}`;
if (!options[modEnabled_id])
return;
let { title, description } = mod.manifest;
const prefix
= `${path}/labels/options/${modEnabled_id}`;
title = localize_field(title || id, "name", prefix);
description = localize_field(description, "description",
prefix);
options[modEnabled_id].name = title;
options[modEnabled_id].description = description;
});
}
/*
* Patch the given langfile loaded in json.
*
* path should be relative to assets/data/.
*
* If path is not found, the alternate path is tried next.
*
* Resolves to a modified json object.
*/
async patch_langfile(path, json, alt_path) {
const map_file = await this.get_map_file();
if (map_file) {
const get_langfile_pack = p => (
this.get_langfile_pack(map_file, p, json)
);
let pack = await get_langfile_pack(path);
if (pack === this.not_found && alt_path) {
pack = await get_langfile_pack(alt_path);
if (pack !== this.not_found)
console.log("Falling back from", path,
"to", alt_path,
"is deprecated.");
path = alt_path;
}
this.patch_langfile_from_pack(json, path, pack);
if (path.startsWith("lang/sc/gui."))
this.patch_ccloader3_mods(json, path, pack);
}
// patch the language list after patching the langfile,
// otherwise, the added languages will be considered
// as missing text.
if (path.startsWith("lang/sc/gui.")) {
const langs = json.labels.options.language.group;
if (langs.constructor !== Array) {
console.error("Could not patch language array",
"game will likely crash !");
return json;
}
this.game_locale_config.patch_game_language_list(langs);
}
return json;
}
/*
* Change the given url so it resolves to a file that exists.
*
* This should be used for url that are constructed using the added
* locales, since these url points to files that do not exist.
*
* This function will change the url so it points to the locale's
* from_locale, so that we can patch it.
*
* Returns a possibly modified url.
*/
get_replacement_url(url) {
if (!ig.currentLang)
console.error("need to patch url without locale set");
const localedef = window.ig.LANG_DETAILS[ig.currentLang];
if (!localedef || !localedef.from_locale)
return url;
const new_url = url.replace(ig.currentLang,
localedef.from_locale);
if (new_url === url)
console.warn("Cannot find current locale in url", url);
return new_url;
}
determine_patch_opts(jquery_options, base_path_length) {
const relative_path
= jquery_options.url.slice(base_path_length);
const ret = {
relative_path,
patch_type: "lang_label"
};
if (jquery_options.context
&& jquery_options.context.constructor === ig.Lang) {
// langfile.
ret.url = this.get_replacement_url(jquery_options.url);
ret.patch_type = "lang_file";
ret.relative_path
= this.get_replacement_url(relative_path);
ret.alternate_relative_path = relative_path;
}
return ret;
}
async apply_patch_options(patch_opts, unpatched_json) {
if (patch_opts.patch_type === "lang_label")
return this.patch_langlabels(patch_opts.relative_path,
unpatched_json);
else {
const alt_rel_path = patch_opts.alternate_relative_path;
return this.patch_langfile(patch_opts.relative_path,
unpatched_json,
alt_rel_path);
}
}
hook_into_game() {
const base_path = ig.root + "data/";
const base_extension_path = ig.root + "extension/";
$.ajaxPrefilter("json", options => {
let prefix_length = 0;
if (options.url.startsWith(base_path))
prefix_length = base_path.length;
else if (options.url.startsWith(base_extension_path))
prefix_length = ig.root.length;
else
return options;
const patch_opts
= this.determine_patch_opts(options,
prefix_length);
options.url = patch_opts.url || options.url;
const apply_patch
= this.apply_patch_options
.bind(this, patch_opts);
const old_resolve = options.success;
const old_reject = options.error;
options.success = function(unpatched_json) {
const resolve = old_resolve.bind(this);
const reject = old_reject.bind(this);
apply_patch(unpatched_json).then(resolve,
reject);
};
return options;
});
}
}
class LocalizeMe {
constructor(game_locale_config) {
this.game_locale_config = game_locale_config;
}
/*
* Locale name must only contain the language and country,
* options can contains:
* - everything from LANG_DETAILS
* - "from_locale" indicate from which basic locale this was translated
* from. Used for 'orig' check, decryption or langfile
* patching.
* - "map_file" must be either an URL to a JSON object or a function
* returning a promise resolving to a JSON object or
* function. The function/JSON object must map an asset
* file path to a translation pack URL or function.
* these URL/function must return a JSON or function
* translations packs must map dict_paths of
* langLabels to their translation as string or
* as translation objects to use.
* It is also possible to return an entire JSON object
* for lang files.
* - "url_prefix" is an optional string, which is prepended to all
* URL found in a map file. Using something based
* on document.currentScript.src allows your mod
* to be relocatable. It should most of the time
* end with '/'.
* - "missing_cb" an optional function to call when a string has no
* translation. parameters are a lang label or string
* and the dict path.
* - "language" a langLabel indicating the name of the language to be
* used in the language options. If a language is missing
* then language[locale] will be used by default. langUid
* is ignored by this function.
* - "text_filter" an optional function called for each translated
* string that should return the string to use. Can be
* used to change the encoding of the text to match the
* font or apply similar transformations. Called with
* (text, translation object)
*
* - "patch_base_font" an optional function called for each loaded font.
* If this function isn't defined but patch_font is, then
* patch_font is used instead of this method (backward
* compatibility from when patch_base_font didn't exist)
*
* Can be used to change the encoding of displayed text,
* add missing characters or more. Called with
* (loaded_image (not scaled), context), where
* loadded_image is the base image of the font with
* white characters. context is unique per multifont
* and contains these fields and methods:
*
* char_height : the height of the font.
*
* size_index : the size index as used by the game.
*
* base_image : the white image loaded by the game.
*
* color : the color of the currently-patched image.
*
* get_char_pos(c) -> { x, y, width, height } to get
* the position of a char in loaded_image.
*
* set_char_pos(c, { x, y, width, height }) to change it.
*
* reserve_char(canvas, width) -> {x, y, width, height}
* to allocate free space in the font.
*
* import_from_font(canvas_dest,ig_font,start_char) to
* import all characters of an ig.Font into the canvas
* using reserve_char(), starting at start_char.
*
* recolor_from_base_image(canvas_dest) to take the white
* image and recolor it into canvas_dest
*
* This context is carried out to patch_font, so you
* may store stuff in there.
*
* This function can not block, use pre_patch_font to
* perform asynchronous operations (like, loading images)
*
* - "patch_font" an optional function called for each color of each
* font. It is called after "patch_base_font".
* Can be used to change the encoding of displayed text,
* add missing characters or more. Called with
* (loaded_image (not scaled), context), where context
* is unique per multifont and contains the same fields
* as "patch_base_font", minus `reserve_char` and
* `import_from_font`.
*
* This function can not block, use pre_patch_font to
* perform asynchronous operations (like, loading images)
*
* - "pre_patch_font" an optional function that is called before the
* first call to patch_font. Unlike patch_font,
* this one may return a promise and will be called
* once per font. Takes a context containing
* "char_height" (height of font),
* "size_index" (as used by the game) and
* "base_image" (the base image of a multifont).
* "set_base_image(img)" (replaces base_image before
* the games parses it)
* This context is carried out to patch_font, so you
* may store stuff in there.
*
* - "number_locale" If set, then number patching is enabled, and this
* locale string will be used as the first parameter
* of Number.prototype.toLocaleString. This should
* cover most number formatting needs. Note that it
* formats the '%' unit with the 'percent' style of
* toLocaleString() but only suffix the other units.
*
* - "format_number" If set, then number patching is enabled and this
* function will be called with 4 parameters, and
* should return a formatted number as a string.
* (number, precision, suffix, template)
* 'number' is the Number to format
* 'precision' indicates how much fractional digits
* must be displayed (as in toFixed())
* 'units' is either empty, or contains an unit.
* currently, only '%', 'm' and 'km' are used.
* it should be suffixed or to the number
* 'template' is passed only if 'number_locale' is
* defined: this is the number formatted
* by toLocaleString as if only
* 'number_locale' was defined. It is
* this possible to reuse this formatted
* number instead of recoding everything
* from scratch.
* - "misc_time_function" If set, then this function will be called
* when the game want the value \v[misc.time].
* This variable is used in the Golden Revolver
* description.
* (item-database.json/items/327/description)
*
* The game defines it as an hardcoded english