-
Notifications
You must be signed in to change notification settings - Fork 0
/
localizer.inc
2029 lines (1839 loc) · 60.4 KB
/
localizer.inc
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
/**
* Localizer.inc | API | Using instrinsic in-game translation #phrases
*
* Copyright (C) 2022 Stanislav "Dragokas" Polshyn
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
//{ #region Declares
#if defined _localizer_included
#endinput
#endif
#define _localizer_included
#define LOCALIZER_VERSION "0.93"
#include <sourcemod>
#include <sdktools>
#include <profiler>
#include <regex>
#define LC_USE_SQLITE 1
enum LC_INSTALL_MODE {
LC_INSTALL_MODE_NONE = 0,
LC_INSTALL_MODE_DATABASE = 1,
LC_INSTALL_MODE_FULLCACHE = 2,
LC_INSTALL_MODE_TRANSLATIONFILE = 4,
LC_INSTALL_MODE_CUSTOM = 8
}
enum LC_OP_STATE
{
LC_OP_STATE_WAIT,
LC_OP_STATE_SIGNAL
}
enum LC_OP_TYPE
{
LC_OP_TYPE_DECODE,
LC_OP_TYPE_CACHE
}
enum LC_OP_FLAG
{
LC_OP_FLAG_NONE = 0,
LC_OP_FLAG_RESET = 1,
LC_OP_FLAG_DELAY = 2
}
enum LC_CACHE
{
LC_CACHE_DATABASE = 1, // L1
LC_CACHE_RAM = 2 // L2 - StringMap
}
//#define LC_PROFILER // uncomment to measure the performance
char LC_LANGUAGE_KEY[] = "Language";
char LC_RESOURCE_ENCODED_DIR[] = "resource";
char LC_RESOURCE_ENCODED_PL_DIR[] = "../platform/resource";
char LC_RESOURCE_DECODED_DIR[] = "resource/utf8";
char LC_RESOURCE_INDEX_FILE[] = "resource/utf8/_index.txt";
char LC_TRANSLATION_FILE[] = "localizer.phrases.txt";
#define LC_DATABASE_NAME "localizer"
#define LC_DATABASE_KEY "localizer_key"
#define LC_DATABASE_TABLE "localizer_phrases"
#define LC_CONVAR_NAME "sm_localizer_inc"
#define LC_MAX_LANG_COUNT 64
#define LC_MAX_LANG_FILE_LENGTH 64
#define LC_MAX_PHRASE_LENGTH 128
#define LC_MAX_TRANSLATION_LENGTH 3072
#define LC_THREAD_EXECUTION_TIME 0.3
#define LC_THREAD_WAIT_TIME 0.1
#define LC_MAX_SIGNAL_WAIT_TIME 60.0
#define LC_MAX_PATH_LANG_ENCODED LC_MAX_LANG_FILE_LENGTH+sizeof(LC_RESOURCE_ENCODED_DIR)+1
#define LC_MAX_PATH_LANG_DECODED LC_MAX_LANG_FILE_LENGTH+sizeof(LC_RESOURCE_DECODED_DIR)+1
Database g_hLcDB;
StringMap g_hMapLcPhrase[LC_MAX_LANG_COUNT], // weird, can't declare dynamic array statically
g_hMapLcStamp,
g_hMapLcEnglishFile; // for english ghosts (in CSGO)
ArrayStack g_hLcStackEncoded,
g_hLcStackCache;
PrivateForward g_fwdLcOnPhrasesProcessingCompleted;
Profiler g_hLcProf;
Regex g_rLcCaptures;
ConVar g_hCvarLcState;
Handle g_hTimerLcState;
bool g_bLcDecodeInProgress,
g_bLcIndexChanged,
g_bLcReady;
int g_iLcServerLanguage,
g_iLcQueueTx;
LC_INSTALL_MODE g_iLcInstallMode;
EngineVersion g_iLcEngine;
typedef g_typLcNotifier = function void();
// #endregion Declares }
//{ #region Stocks
/* ==============================================================================
Stocks
================================================================================*/
methodmap Localizer < Handle
{
/**
* Called whenever new instance of Localizer methodmap is created.
* This will make an installation of Localizer.
*
* @param install_mode Optional method of installation:
*
* LC_INSTALL_MODE_DATABASE (default)
* - saves phrases to a database.
* LC_INSTALL_MODE_FULLCACHE (experimental)
* - pre-caches all phrases making the fastest query, but consuming a lot of memory.
* LC_INSTALL_MODE_TRANSLATIONFILE (experimental, not fully implemented)
* - save phrases to translation file.
* - phrases are available via %T %t specifiers only.
* - do not use own's Localizer Print* methods within this installation mode.
* LC_INSTALL_MODE_CUSTOM
* - no installation is performed, no objects are initialized at startup.
* - it is intended to use with Localizer.Uninstall() method only.
*
* @return New instance of this methodmap.
*
* @note For LC_INSTALL_MODE_DATABASE and LC_INSTALL_MODE_TRANSLATIONFILE, installation is shared between plugins.
* To access the translation functionality as soon as possible, register a hook via Localizer.Delegate_InitCompleted() method.
* To free the resources use Localizer.Close() method.
* To uninstall Localizer completely, use Localizer.Uninstall() method.
*/
public Localizer(LC_INSTALL_MODE install_mode = LC_INSTALL_MODE_DATABASE)
{
Loc_Init(install_mode);
return view_as<Localizer>(g_hLcProf);
}
/**
* Returns the installation mode used
*/
property LC_INSTALL_MODE InstallMode
{
public get() { return g_iLcInstallMode; }
}
/**
* Creates a single use hook, notifying that Localizer is fully initialized
*
* @note Translation can only be retrieved after this hook is raised
*
* @param func Callback name having the following prototype: public void Foo()
*/
public void Delegate_InitCompleted(g_typLcNotifier func)
{
g_fwdLcOnPhrasesProcessingCompleted.AddFunction(GetMyHandle(), func);
}
/**
* Informs if Localizer is fully initialized.
*
* @return True if Localizer is ready to translate phrases, false if initialization has still proceeded.
*/
public bool IsReady()
{
return g_bLcReady;
}
/**
* Sends a message to the server console.
*
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
*/
public void PrintToServer(char[] format, any ...)
{
char translation[LC_MAX_TRANSLATION_LENGTH];
SetGlobalTransTarget(LANG_SERVER);
VFormat(translation, sizeof(translation), format, 2 +1);
Loc_ReplacePhrases(translation, sizeof(translation), g_iLcServerLanguage);
PrintToServer("%s", translation);
}
/**
* Replies to a message in a command.
*
* A client index of 0 will use PrintToServer().
* If the command was from the console, PrintToConsole() is used.
* If the command was from chat, PrintToChat() is used.
*
* @param client Client index, or 0 for server.
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
* @error If the client is not connected or invalid.
*/
public void ReplyToCommand(int client, const char[] format, any ...)
{
char translation[LC_MAX_TRANSLATION_LENGTH];
SetGlobalTransTarget(client);
VFormat(translation, sizeof(translation), format, 3 +1);
Loc_ReplacePhrases(translation, sizeof(translation), client == 0 ? g_iLcServerLanguage : GetClientLanguage(client));
ReplyToCommand(client, "%s", translation);
}
/**
* Prints a message to a specific client in the chat area.
*
* @param client Client index.
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
* @error Invalid client index, or client not in game.
*/
public void PrintToChat(int client, const char[] format, any ...)
{
char translation[LC_MAX_TRANSLATION_LENGTH];
SetGlobalTransTarget(client);
VFormat(translation, sizeof(translation), format, 3 +1);
Loc_ReplacePhrases(translation, sizeof(translation), GetClientLanguage(client));
PrintToChat(client, "%s", translation);
}
/**
* Prints a message to all clients in the chat area.
*
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
*/
public void PrintToChatAll(char[] format, any ...)
{
char translation[LC_MAX_TRANSLATION_LENGTH];
for( int i = 1; i <= MaxClients; i++ )
{
if( IsClientInGame(i) && !IsFakeClient(i) )
{
SetGlobalTransTarget(i);
VFormat(translation, sizeof(translation), format, 2 +1);
Loc_ReplacePhrases(translation, sizeof(translation), GetClientLanguage(i));
PrintToChat(i, "%s", translation);
}
}
}
/**
* Prints a message to a specific client with a hint box.
*
* @param client Client index.
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
* @error Invalid client index, or client not in game.
*/
public void PrintHintText(int client, const char[] format, any ...)
{
char translation[LC_MAX_TRANSLATION_LENGTH];
SetGlobalTransTarget(client);
VFormat(translation, sizeof(translation), format, 3 +1);
Loc_ReplacePhrases(translation, sizeof(translation), GetClientLanguage(client));
PrintHintText(client, "%s", translation);
}
/**
* Prints a message to all clients with a hint box.
*
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
*/
public void PrintHintTextToAll(char[] format, any ...)
{
char translation[LC_MAX_TRANSLATION_LENGTH];
for( int i = 1; i <= MaxClients; i++ )
{
if( IsClientInGame(i) && !IsFakeClient(i) )
{
SetGlobalTransTarget(i);
VFormat(translation, sizeof(translation), format, 2 +1);
Loc_ReplacePhrases(translation, sizeof(translation), GetClientLanguage(i));
PrintHintText(i, "%s", translation);
}
}
}
/**
* Prints a message to a specific client in the center of the screen.
*
* @param client Client index.
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
* @error Invalid client index, or client not in game.
*/
public void PrintCenterText(int client, const char[] format, any ...)
{
char translation[LC_MAX_TRANSLATION_LENGTH];
SetGlobalTransTarget(client);
VFormat(translation, sizeof(translation), format, 3 +1);
Loc_ReplacePhrases(translation, sizeof(translation), GetClientLanguage(client));
PrintCenterText(client, "%s", translation);
}
/**
* Prints a message to all clients in the center of the screen.
*
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
*/
public void PrintCenterTextAll(char[] format, any ...)
{
char translation[LC_MAX_TRANSLATION_LENGTH];
for( int i = 1; i <= MaxClients; i++ )
{
if( IsClientInGame(i) && !IsFakeClient(i) )
{
SetGlobalTransTarget(i);
VFormat(translation, sizeof(translation), format, 2 +1);
Loc_ReplacePhrases(translation, sizeof(translation), GetClientLanguage(i));
PrintCenterText(i, "%s", translation);
}
}
}
/**
* Sends a message to a client's console.
*
* @param client Client index.
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
* @error If the client is not connected an error will be thrown.
*/
public void PrintToConsole(int client, const char[] format, any ...)
{
char translation[LC_MAX_TRANSLATION_LENGTH];
SetGlobalTransTarget(client);
VFormat(translation, sizeof(translation), format, 3 +1);
Loc_ReplacePhrases(translation, sizeof(translation), GetClientLanguage(client));
PrintToConsole(client, "%s", translation);
}
/**
* Sends a message to every client's console.
*
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
*/
public void PrintToConsoleAll(char[] format, any ...)
{
char translation[LC_MAX_TRANSLATION_LENGTH];
for( int i = 1; i <= MaxClients; i++ )
{
if( IsClientInGame(i) && !IsFakeClient(i) )
{
SetGlobalTransTarget(i);
VFormat(translation, sizeof(translation), format, 2 +1);
Loc_ReplacePhrases(translation, sizeof(translation), GetClientLanguage(i));
PrintToConsole(i, "%s", translation);
}
}
}
/**
* Formats a string according to the SourceMod format rules (see documentation).
*
* @param buffer Destination string buffer.
* @param maxlength Maximum length of output string buffer.
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @return Number of cells written.
*
* @note If phrase translation doesn't exist, it defaults to server language translation.
*/
public int Format(char[] buffer, int maxlength, const char[] format, any...)
{
VFormat(buffer, maxlength, format, 4 +1);
Loc_ReplacePhrases(buffer, maxlength, g_iLcServerLanguage);
return strlen(buffer);
}
/**
* Translates a single #phrase according to client's or spicified language.
*
* @param phrase A single #phrase to be translated.
* @param buffer Destination string buffer. Input and output buffers cannot be the same!
* @param maxlength Maximum length of output string buffer.
* @param client Optional client index which language to translate to (default: LANG_SERVER).
* @param lang_name Optional full language name to translate to (default: empty).
* @param lang_code Optional alphabetic language code to translate to (default: empty).
* @param default_text Optional default string to use if phrase doesn't exist (default: empty).
*
* @return True if phrase is translated, false otherwise.
*
* @note If phrase doesn't found, the empty string is returned in buffer.
* @error If #phrase length is <= 1.
*/
public bool PhraseTranslateToLang(char[] phrase, char[] buffer, int maxlength, int client = LANG_SERVER, char[] lang_name = NULL_STRING, char[] lang_code = NULL_STRING, char[] default_text = NULL_STRING )
{
int lang_num = Loc_GetLanguageNum(client, lang_name, lang_code);
if( Loc_GetPhrase(lang_num, phrase[1], buffer, maxlength, false, false) )
{
return true;
}
else {
strcopy(buffer, maxlength, default_text);
return false;
}
}
/**
* Translates a single #phrase to client's or spicified language.
*
* @param phrase A single #phrase.
* @param buffer Destination string buffer.
* @param maxlength Maximum length of output string buffer.
* @param client Optional client index which language to translate to (default: LANG_SERVER).
* @param lang_name Optional full language name to translate to (default: empty).
* @param lang_code Optional alphabetic language code to translate to (default: empty).
*
* @return True if phrase is translated, false otherwise.
*
* @note If phrase doesn't found, the empty string is returned in buffer.
* @error If #phrase length is <= 1.
*/
public bool PhraseExists(char[] phrase, int client = LANG_SERVER, char[] lang_name = "", char[] lang_code = "")
{
int lang_num = Loc_GetLanguageNum(client, lang_name, lang_code);
char translation[LC_MAX_TRANSLATION_LENGTH];
return Loc_GetPhrase(lang_num, phrase[1], translation, sizeof(translation), false, false);
}
/**
* Checks if a #phrase had precache in RAM (Cache L2).
*
* @param phrase A single #phrase.
* @param client Optional client index of phrase language (default: LANG_SERVER).
* @param lang_name Optional full language name of phrase (default: empty).
* @param lang_code Optional alphabetic language code of phrase (default: empty).
*
* @return True if phrase is precached, false otherwise.
*
* @error If #phrase length is <= 1.
*/
public bool PhrasePrecached(char[] phrase, int client = LANG_SERVER, char[] lang_name = "", char[] lang_code = "")
{
int lang_num = Loc_GetLanguageNum(client, lang_name, lang_code);
char translation[LC_MAX_TRANSLATION_LENGTH];
return g_hMapLcPhrase[lang_num].GetString(phrase[1], translation, sizeof(translation));
}
/**
* Precaches a #phrase to RAM (Cache L2) for faster access later.
*
* @param phrase A single #phrase.
*
* @return True if phrase is precached, false if phrase doesn't found.
*
* @note This precache is only actual for installation mode 'LC_INSTALL_MODE_DATABASE' (default).
* @error If #phrase length is <= 1.
*/
public bool PrecachePhrase(char[] phrase)
{
int lang_num = Loc_GetLanguageNum(LANG_SERVER, "", "");
char translation[LC_MAX_TRANSLATION_LENGTH];
return Loc_GetPhrase(lang_num, phrase[1], translation, sizeof(translation), true, true);
}
//TODO
/**
* Precaches an arbitrary translation file to use it the same way if it were intrinsic translation phrases.
*
* @param phrase A single #phrase.
*
* @return True if phrase is precached, false if phrase doesn't found.
*
* @note This precache is only actual for installation mode 'LC_INSTALL_MODE_DATABASE' (default).
* @error If #phrase length is <= 1.
*/
public bool PrecacheTranslationFile(char[] file, LC_CACHE cache = LC_CACHE_RAM)
{
return true;
}
/**
* Adds a new #phrase and translation.
*
* @param phrase A single #phrase.
* @param translation Translation of phrase.
* @param client Optional client index which language is used in provided translation (default: LANG_SERVER).
* @param lang_name Optional full language name of provided translation (default: empty).
* @param lang_code Optional alphabetic language code of provided translation (default: empty).
* @param bOverwrite Optional, specify if you want to overwrite phrase that is already exists (default: yes).
* @param bAsync Optional, spefify if you want this operation to be asynchronous (default: no).
*
* @note This #phrase will not survive the server reboot if installation mode == LC_INSTALL_MODE_FULLCACHE.
* @error If #phrase length is <= 1.
*/
public void PhraseAdd(char[] phrase, char[] translation, int client = LANG_SERVER, char[] lang_name = "", char[] lang_code = "",
bool bOverwrite = true, bool bAsync = false)
{
int lang_num = Loc_GetLanguageNum(client, lang_name, lang_code);
Loc_AddPhrase(lang_num, phrase[1], translation, bOverwrite, bAsync);
}
/**
* Adds a new #phrase and translation to a temporarily cache L2 (StringMap).
*
* @param phrase A single #phrase.
* @param translation Translation of phrase.
* @param client Optional client index which language is used in provided translation (default: LANG_SERVER).
* @param lang_name Optional full language name of provided translation (default: empty).
* @param lang_code Optional alphabetic language code of provided translation (default: empty).
* @param bOverwrite Optional, specify if you want to overwrite phrase that is already exists (default: yes).
*
* @note This #phrase will not survive the server reboot.
* @error If #phrase length is <= 1.
*/
public void PhraseAddTemp(char[] phrase, char[] translation, int client = LANG_SERVER, char[] lang_name = "", char[] lang_code = "",
bool bOverwrite = true)
{
int lang_num = Loc_GetLanguageNum(client, lang_name, lang_code);
g_hMapLcPhrase[lang_num].SetString(phrase, translation, bOverwrite);
}
/**
* Removes a #phrase and all its translations.
*
* @param phrase A single #phrase.
*
* @note This will not survive the server reboot if installation mode == LC_INSTALL_MODE_FULLCACHE.
* For other modes, if you removes a pre-built (resource) phrase, it can only be restored on resource update,
* or via Localizer.Uninstall() method with a full re-installation.
* @error If #phrase length is <= 1.
*/
public void PhraseRemove(char[] phrase)
{
SQL_Loc_RemovePhrase(phrase[1]);
for( int i = 0; i < GetLanguageCount(); i++ )
{
if( g_hMapLcPhrase[i] )
{
g_hMapLcPhrase[i].Remove(phrase[1]);
}
}
}
/**
* Generates SM compatible translation file from all L2 (StringMap) pre-cached phrases.
* Note: for convenience, translation files are also mirrored to folder: "translations/localizer/"
*
* @return True if at least default server language file is successfully generated, false otherwise.
*
* @note To dump all resource phrases, you have to initialize Localizer with installation mode == LC_INSTALL_MODE_FULLCACHE.
* File is stored in location: ./translations/localizer.phrases.txt
* You can use it to observe and study desired phrases for further using via default installation mode.
* Or you can load this file with Localizer.LoadTranslations() method and use translations via %T %t specifiers.
*/
public bool DumpAll()
{
bool result;
int count;
g_hLcProf.Start();
result = Loc_Dump(LANG_SERVER, count);
for( int i = 0; i < GetLanguageCount(); i++ )
{
if( i != LANG_SERVER )
{
Loc_Dump(i, count);
}
}
g_hLcProf.Stop();
#if defined LC_PROFILER
PrintToServer(">> Profiler report for: %s (%i phrases): %.2f sec.", "Dumping" , count, g_hLcProf.Time);
#endif
return result;
}
/**
* Loads previously dumped localizer.phrases.txt file via SM LoadTranslations() method.
*
* @return True if translations are loaded, false if translation file doesn't found.
*
* @note You can use translations via %T %t specifiers in any SM Print* and similar methods passing "#phrase" as an argument.
*/
public bool LoadTranslations()
{
return Loc_LoadTranslations();
}
/**
* Uninstall Localizer from the server completely.
*
* @note Database table, translation files and decoded resource files ('utf8' dir) will be removed.
* You should call Localizer.Close() method manually to free the remaining resources.
*/
public void Uninstall()
{
if( g_hCvarLcState && g_hCvarLcState.IntValue == view_as<int>(LC_OP_STATE_WAIT) )
{
return;
}
Loc_DeleteDirectory(LC_RESOURCE_DECODED_DIR);
SQL_Loc_RemoveTable();
Loc_RemoveTranslationFiles();
g_iLcInstallMode = LC_INSTALL_MODE_NONE;
}
/**
* Frees resources allocated by Localizer instance.
*/
public void Close()
{
for( int i = 0; i < sizeof(g_hMapLcPhrase); i++ ) {
if( g_hMapLcPhrase[i] != null)
delete g_hMapLcPhrase[i];
}
delete g_hMapLcStamp;
delete g_hMapLcEnglishFile;
delete g_hLcStackEncoded;
delete g_hLcStackCache;
delete g_hTimerLcState;
delete g_hLcProf;
g_fwdLcOnPhrasesProcessingCompleted.RemoveAllFunctions(GetMyHandle());
//delete g_fwdLcOnPhrasesProcessingCompleted; // disabled: potential crash, if executed in mid-call
delete g_rLcCaptures;
//delete g_hLcDB; // disabled: for safe, because database can still execute threaded operations
g_iLcInstallMode = LC_INSTALL_MODE_NONE;
}
}
/**
* In-line formats a string according to the SourceMod format rules (see documentation).
*
* @param client Client index.
* @param format Formatting rules (allows to accept #phrase).
* @param ... Variable number of format parameters.
*
* @return Char array with resulting string.
*
* @note If a phrase doesn't found, original #phrase is stay untouched.
* @error Invalid client index, or client not in game.
*/
stock char[] Loc_Translate(int client, const char[] format, any ...) // weird, can't declare it within methodmap due to array-based return type
{
char translation[LC_MAX_TRANSLATION_LENGTH];
SetGlobalTransTarget(client);
VFormat(translation, sizeof(translation), format, 3);
Loc_ReplacePhrases(translation, sizeof(translation), client == 0 ? g_iLcServerLanguage : GetClientLanguage(client));
return translation;
}
/**
* In-line translates a single #phrase according to client's or spicified language.
*
* @param phrase A single #phrase to be translated.
* @param client Optional client index which language to translate to (default: LANG_SERVER).
* @param lang_name Optional full language name to translate to (default: empty).
* @param lang_code Optional alphabetic language code to translate to (default: empty).
*
* @return Char array with a translation.
*
* @note If phrase doesn't found, the empty string is returned.
* @error If #phrase length is <= 1.
*/
stock char[] Loc_TranslateToLang(char[] phrase, int client = LANG_SERVER, char[] lang_name = "", char[] lang_code = "" )
{
char translation[LC_MAX_TRANSLATION_LENGTH];
int lang_num = Loc_GetLanguageNum(client, lang_name, lang_code);
Loc_GetPhrase(lang_num, phrase[1], translation, sizeof(translation), false, false);
return translation;
}
// #endregion Stocks }
/* ==============================================================================
Private functions
================================================================================*/
//{ #region Initialize
void Loc_Init(LC_INSTALL_MODE install_mode)
{
/*
// TODO
g_hLcGlobalProf = new Profiler();
#if defined LC_PROFILER
if( !(install_mode & LC_INSTALL_MODE_CUSTOM) )
{
g_hLcGlobalProf.Start();
}
#endif
*/
g_iLcInstallMode = install_mode;
g_iLcEngine = GetEngineVersion();
g_hCvarLcState = FindConVar(LC_CONVAR_NAME); // inter-plugin sync. mechanism
Loc_RegisterCommands();
// TODO: remove it
if( g_hCvarLcState )
{
g_hCvarLcState.SetInt(1);
}
if( !(install_mode & LC_INSTALL_MODE_CUSTOM) )
{
Loc_InitObjects();
if( g_hCvarLcState && g_hCvarLcState.IntValue == view_as<int>(LC_OP_STATE_WAIT) )
{
#if defined LC_PROFILER
PrintToServer("[Localizer] [h:%i] Pausing execution", GetMyHandle());
#endif
g_hCvarLcState.AddChangeHook(Loc_StateChanged);
Loc_SetStateWatchDog();
}
else {
if( !g_hCvarLcState )
{
char value[4];
IntToString(view_as<int>(LC_OP_STATE_WAIT), value, sizeof(value));
g_hCvarLcState = CreateConVar(LC_CONVAR_NAME, value, "Signal for other plugins to continue initialization", FCVAR_SPONLY | FCVAR_DONTRECORD );
}
Loc_StartProcessing();
}
}
}
bool Loc_InitObjects()
{
int count = GetLanguageCount();
for( int i = 0; i < count; i++ ) {
delete g_hMapLcPhrase[i];
g_hMapLcPhrase[i] = new StringMap();
}
delete g_hMapLcStamp;
delete g_hLcStackEncoded;
delete g_hLcStackCache;
g_hMapLcStamp = new StringMap();
g_hMapLcEnglishFile = new StringMap();
g_hLcStackEncoded = new ArrayStack(ByteCountToCells(LC_MAX_LANG_FILE_LENGTH));
g_hLcStackCache = new ArrayStack(ByteCountToCells(LC_MAX_LANG_FILE_LENGTH));
if( !g_hLcProf )
{
g_hLcProf = new Profiler();
}
if( !g_fwdLcOnPhrasesProcessingCompleted )
{
g_fwdLcOnPhrasesProcessingCompleted = new PrivateForward(ET_Ignore);
}
//example: "#hulkzombie.start-ledge\\climb", but not greedy for "#hulkzombie.start-ledge\\climb."
//
if( !g_rLcCaptures )
{
g_rLcCaptures = new Regex("#\\w+([\\.\\-\\\\]\\w+)*");
}
g_iLcServerLanguage = GetServerLanguage();
return true;
}
void Loc_RegisterCommands()
{
static bool IsListen;
if( !IsListen )
{
if( CommandExists("sm_localizer_list") )
{
AddCommandListener(CmdListener_Loc_List, "sm_localizer_list");
}
else {
RegAdminCmd("sm_localizer_list", Cmd_Loc_List, ADMFLAG_ROOT, "Lists plugin names that using Localizer API, show API version and installation mode");
}
IsListen = true;
}
}
public Action CmdListener_Loc_List(int client, const char[] command, int argc)
{
Loc_ShowConsumer(client);
return Plugin_Continue;
}
public Action Cmd_Loc_List(int client, int argc)
{
Loc_ShowConsumer(client);
return Plugin_Handled;
}
void Loc_ShowConsumer(int client)
{
char name[64];
GetPluginFilename(INVALID_HANDLE, name, sizeof(name));
ReplyToCommand(client, "%s | Install mode: %s | API Version: %s", name, Loc_InstallMode_ToString(), LOCALIZER_VERSION);
}
public void Loc_StateChanged(ConVar convar, const char[] oldValue, const char[] newValue)
{
if( view_as<LC_OP_STATE>(convar.IntValue) == LC_OP_STATE_SIGNAL )
{
#if defined LC_PROFILER
PrintToServer("[Localizer] [h:%i] Received signal => continue execution", GetMyHandle());
#endif
delete g_hTimerLcState;
g_hCvarLcState.RemoveChangeHook(Loc_StateChanged);
convar.SetInt(view_as<int>(LC_OP_STATE_WAIT)); // pause the next plugin in chain
Loc_StartProcessing();
}
else {
#if defined LC_PROFILER
PrintToServer("[Localizer] [h:%i] Restarting Dog", GetMyHandle());
#endif
Loc_SetStateWatchDog();
}
}
void Loc_SetStateWatchDog()
{
delete g_hTimerLcState;
g_hTimerLcState = CreateTimer(LC_MAX_SIGNAL_WAIT_TIME, Timer_Loc_SignalWatchDog);
}
public Action Timer_Loc_SignalWatchDog(Handle timer)
{
PrintToServer("[Localizer] [h:%i] WatchDog raised !!!", GetMyHandle());
g_hTimerLcState = null;
g_hCvarLcState.SetInt(view_as<int>(LC_OP_STATE_SIGNAL));
return Plugin_Continue;
}
void Loc_StartProcessing()
{
CreateDirectory(LC_RESOURCE_DECODED_DIR, 0o755);
Loc_ReadIndexFile();
switch( g_iLcInstallMode )
{
case LC_INSTALL_MODE_DATABASE:
{
SQL_Loc_DB_Connect();
}
case LC_INSTALL_MODE_FULLCACHE:
{
Loc_GetPhraseFiles("");
}
case LC_INSTALL_MODE_TRANSLATIONFILE:
{
Loc_LoadTranslations();
Loc_GetPhraseFiles("");
}
}
}
// #endregion Initialize }
//{ #region Forwards
/* ==============================================================================
Forwards
================================================================================*/
void OnPhrasesProcessingCompleted_CallDelayed() // wait for DB to finish last threaded operation
{
CreateTimer(LC_THREAD_WAIT_TIME, Timer_Loc_OnPhrasesProcessingCompleted);
}
public Action Timer_Loc_OnPhrasesProcessingCompleted(Handle timer)
{
Forward_OnPhrasesProcessingCompleted();
return Plugin_Continue;
}
void Forward_OnPhrasesProcessingCompleted()
{
if( g_bLcIndexChanged )
{
Loc_WriteIndexFile();
}
if( g_iLcInstallMode == LC_INSTALL_MODE_DATABASE )
{
SQL_Loc_SetIndex("", 0, .bFinishPending = true);
}
else if( g_iLcInstallMode == LC_INSTALL_MODE_TRANSLATIONFILE )
{
// TODO
}
g_hCvarLcState.SetInt(view_as<int>(LC_OP_STATE_SIGNAL));
g_bLcReady = true;
#if defined LC_PROFILER
if( g_iLcInstallMode == LC_INSTALL_MODE_DATABASE )
{
g_hLcProf.Stop();
PrintToServer(">> Profiler report for: %s: %.2f sec.", "Pending database" , g_hLcProf.Time);
}
PrintToServer(">>> Phrases processing is completed.");
#endif
RequestFrame(Forward_OnPhrasesProcessingCompleted_Frame);
}
void Forward_OnPhrasesProcessingCompleted_Frame()
{
Action result;
Call_StartForward(g_fwdLcOnPhrasesProcessingCompleted);
Call_Finish(result);
/* // no sense, since we can't call it by name anyway
if( GetFunctionByName(null, "OnPhrasesProcessingCompleted") != INVALID_FUNCTION )
{
Call_StartFunction(null, OnPhrasesProcessingCompleted);
Call_Finish(result);
}
*/
}
// #endregion Forward }
//{ #region Parser
/* ==============================================================================
Parser
================================================================================*/
void Loc_ReadIndexFile()
{
g_hMapLcStamp.Clear();
int p, iStamp;
char str[LC_MAX_TRANSLATION_LENGTH];
File hr = OpenFile(LC_RESOURCE_INDEX_FILE, "rt");
if( hr )
{
while( !hr.EndOfFile() && hr.ReadLine(str, sizeof(str)) )
{
if( -1 != (p = FindCharInString(str, '|')) )
{
str[p] = 0;
iStamp = StringToInt(str[p+1]);
g_hMapLcStamp.SetValue(str[0], iStamp, true);
}
}
hr.Close();
}
}
void Loc_WriteIndexFile()
{
char name[128], str[128];
int iStamp;
File hFile = OpenFile(LC_RESOURCE_INDEX_FILE, "wt");
if( hFile ) {
StringMapSnapshot hSnap = g_hMapLcStamp.Snapshot();
if( hSnap )
{
for( int i = 0; i < hSnap.Length; i++ )
{
hSnap.GetKey(i, name, sizeof(name));
g_hMapLcStamp.GetValue(name, iStamp);
FormatEx(str, sizeof(str), "%s|%i", name, iStamp);
hFile.WriteLine(str);
}
delete hSnap;
}
hFile.Close();
}
}
void Loc_GetPhraseFiles(char[] search)
{
DirectoryListing hDir;
char sFile[LC_MAX_LANG_FILE_LENGTH], prefix[32], guess[LC_MAX_LANG_FILE_LENGTH];
int iCount, iLen, n, iLenSearch = strlen(search);
FileType fileType;
StringMap hUniqPrefix = new StringMap();
hDir = OpenDirectory(LC_RESOURCE_ENCODED_DIR, true);
if( hDir )
{
while( hDir.GetNext(sFile, sizeof(sFile), fileType) )