forked from potatosalad775/MWC_Localization_Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternMatcher.cs
More file actions
336 lines (290 loc) · 12.1 KB
/
PatternMatcher.cs
File metadata and controls
336 lines (290 loc) · 12.1 KB
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
// Pattern matching system for Translation Strings
using MSCLoader;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace MWC_Localization_Core
{
/// <summary>
/// Unified pattern matching system for all translation types
/// Replaces separate FSM, Magazine, and Price pattern logic
/// </summary>
public class PatternMatcher
{
private List<TranslationPattern> patterns = new List<TranslationPattern>();
private Dictionary<string, string> translations;
private HashSet<string> patternSignatures = new HashSet<string>();
public PatternMatcher(Dictionary<string, string> translations)
{
this.translations = translations;
ResetPatterns();
}
/// <summary>
/// Reset pattern registry to a clean built-in state.
/// Call before loading file patterns to make reload idempotent.
/// </summary>
public void ResetPatterns()
{
patterns.Clear();
patternSignatures.Clear();
InitializeBuiltInPatterns();
}
/// <summary>
/// Initialize built-in patterns (can be overridden by config file)
/// </summary>
private void InitializeBuiltInPatterns()
{
// Magazine price/phone pattern (custom handler)
var magazinePricePattern = new TranslationPattern(
"MagazinePrice",
TranslationMode.CustomHandler,
"h.{price},- puh.{phone}",
"{price} MK, {PHONE} - {phone}"
);
magazinePricePattern.PathMatcher = path => path.Contains("YellowPagesMagazine");
magazinePricePattern.TextMatcher = text => text.StartsWith("h.") && text.Contains(",- puh.");
magazinePricePattern.CustomHandler = TranslateMagazinePriceLine;
AddPatternInternal(magazinePricePattern, true);
// Magazine comma-separated words
var magazineWordsPattern = new TranslationPattern(
"MagazineWords",
TranslationMode.CommaSeparated,
"",
""
);
magazineWordsPattern.PathMatcher = path => path.Contains("YellowPagesMagazine");
magazineWordsPattern.TextMatcher = text => text.Split(',').Length == 3;
AddPatternInternal(magazineWordsPattern, true);
// Multi-line Computer command text handler
var pcScreenPattern = new TranslationPattern(
"PCMultiLine",
TranslationMode.CustomHandler,
"",
""
);
pcScreenPattern.PathMatcher = path => path.Contains("COMPUTER/SYSTEM/POS/Text");
pcScreenPattern.TextMatcher = text => text.Contains("\n");
pcScreenPattern.CustomHandler = TranslateMultilineScreen;
AddPatternInternal(pcScreenPattern, true);
}
/// <summary>
/// Load patterns from file (FSM patterns, custom patterns, etc.)
/// </summary>
public void LoadPatternsFromFile(string filePath)
{
if (!File.Exists(filePath))
{
CoreConsole.Print("[PatternMatcher] No pattern file found, using built-in patterns only");
return;
}
try
{
string[] lines = File.ReadAllLines(filePath, Encoding.UTF8);
string currentSection = null;
int loadedCount = 0;
foreach (string line in lines)
{
string trimmed = line.Trim();
// Skip comments and empty lines
if (string.IsNullOrEmpty(trimmed) || trimmed.StartsWith("#"))
continue;
// Check for section header
if (trimmed.StartsWith("[") && trimmed.EndsWith("]"))
{
currentSection = trimmed.Substring(1, trimmed.Length - 2);
continue;
}
// Parse pattern - auto-detects FsmPattern vs FsmPatternWithTranslation
if (TryParseFsmPattern(trimmed, out TranslationPattern pattern))
{
if (AddPatternInternal(pattern, false))
{
loadedCount++;
}
}
}
CoreConsole.Print($"[PatternMatcher] Loaded {loadedCount} patterns from file");
}
catch (System.Exception ex)
{
CoreConsole.Error($"[PatternMatcher] Failed to load patterns: {ex.Message}");
}
}
private bool TryParseFsmPattern(string line, out TranslationPattern pattern)
{
pattern = null;
int equalsIndex = FindUnescapedEquals(line);
if (equalsIndex <= 0)
return false;
string original = line.Substring(0, equalsIndex).Trim().ToUpperInvariant();
string translation = line.Substring(equalsIndex + 1).Trim();
// Unescape special characters
original = UnescapeString(original);
translation = UnescapeString(translation);
if (string.IsNullOrEmpty(original) || string.IsNullOrEmpty(translation))
return false;
// Check if this is a pattern (contains {0}, {1}, etc.)
// Auto-detect: if translation has placeholders, use FsmPatternWithTranslation (translate the params)
// If translation has NO placeholders, use FsmPattern (just substitute - rare case)
if (original.Contains("{0}") || original.Contains("{1}") || original.Contains("{2}"))
{
bool translationHasPlaceholders = translation.Contains("{0}") || translation.Contains("{1}") || translation.Contains("{2}");
pattern = new TranslationPattern(
"FSM_" + original.Substring(0, System.Math.Min(20, original.Length)),
translationHasPlaceholders ? TranslationMode.FsmPatternWithTranslation : TranslationMode.FsmPattern,
original,
translation
);
return true;
}
return false;
}
/// <summary>
/// Try to translate text using pattern matching
/// Returns null if no pattern matched
/// </summary>
public string TryTranslateWithPattern(string text, string path)
{
foreach (var pattern in patterns)
{
string result = pattern.TryTranslate(text.ToUpperInvariant(), path, translations);
if (result != null)
{
return result;
}
}
return null;
}
/// <summary>
/// Add a pattern programmatically
/// </summary>
public void AddPattern(TranslationPattern pattern)
{
AddPatternInternal(pattern, false);
}
/// <summary>
/// Clear all patterns
/// </summary>
public void ClearPatterns()
{
patterns.Clear();
patternSignatures.Clear();
}
private bool AddPatternInternal(TranslationPattern pattern, bool appendToEnd)
{
if (pattern == null)
return false;
string signature = BuildSignature(pattern);
if (!patternSignatures.Add(signature))
return false;
if (appendToEnd)
{
patterns.Add(pattern);
}
else
{
// User file patterns take priority over built-ins.
patterns.Insert(0, pattern);
}
return true;
}
private string BuildSignature(TranslationPattern pattern)
{
string original = pattern.OriginalPattern ?? string.Empty;
string translated = pattern.TranslatedTemplate ?? string.Empty;
return ((int)pattern.Mode).ToString() + "|" + original + "|" + translated;
}
/// <summary>
/// Custom handler for magazine price/phone lines
/// Format: "h.149,- puh.123456" -> "149 MK, PHONE - 123456"
/// </summary>
private TranslationPattern.CustomHandlerResult TranslateMagazinePriceLine(string text, string path, Dictionary<string, string> translations)
{
try
{
// Remove "h." prefix and split by ",- puh."
if (!text.StartsWith("h."))
return new TranslationPattern.CustomHandlerResult(false, null);
string withoutPrefix = text.Substring(2);
string[] parts = withoutPrefix.Split(new string[] { ",- puh." }, System.StringSplitOptions.None);
if (parts.Length == 2)
{
string pricePart = parts[0].Trim();
string phonePart = parts[1].Trim();
// Get phone label from translations
string phoneLabel = translations.TryGetValue("PHONE", out string translation)
? translation
: "PHONE";
return new TranslationPattern.CustomHandlerResult(true, $"{pricePart} MK, {phoneLabel} - {phonePart}");
}
}
catch (System.Exception ex)
{
CoreConsole.Warning($"Failed to parse magazine price/phone line: {text} - {ex.Message}");
}
return new TranslationPattern.CustomHandlerResult(false, null);
}
/// <summary>
/// Custom handler for multi-line computer screen text
/// Splits lines and translates each line individually
private TranslationPattern.CustomHandlerResult TranslateMultilineScreen(string text, string path, Dictionary<string, string> translations)
{
try
{
string[] lines = text.Split(new string[] { "\n" }, System.StringSplitOptions.None);
List<string> translatedLines = new List<string>();
bool anyTranslated = false;
foreach (string line in lines)
{
string trimmed = line.Trim();
if (string.IsNullOrEmpty(trimmed))
{
translatedLines.Add(""); // Preserve empty lines
continue;
}
// Try to translate this line
string key = trimmed.ToUpperInvariant();
if (translations.TryGetValue(key, out string translation))
{
translatedLines.Add(translation);
anyTranslated = true;
}
else
{
translatedLines.Add(trimmed); // Keep original if not found
}
}
if (anyTranslated)
{
return new TranslationPattern.CustomHandlerResult(true, string.Join("\n", translatedLines.ToArray()));
}
}
catch (System.Exception ex)
{
CoreConsole.Warning($"Failed to translate multi-line screen: {ex.Message}");
}
return new TranslationPattern.CustomHandlerResult(false, null);
}
// Utility methods from TeletextHandler
private int FindUnescapedEquals(string line)
{
for (int i = 0; i < line.Length; i++)
{
if (line[i] == '=')
{
// Check if escaped
if (i > 0 && line[i - 1] == '\\')
continue;
return i;
}
}
return -1;
}
private string UnescapeString(string str)
{
if (string.IsNullOrEmpty(str))
return str;
return str.Replace("\\=", "=").Replace("\\n", "\n");
}
}
}