forked from potatosalad775/MWC_Localization_Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranslationPattern.cs
More file actions
348 lines (290 loc) · 12 KB
/
TranslationPattern.cs
File metadata and controls
348 lines (290 loc) · 12 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
337
338
339
340
341
342
343
344
345
346
347
348
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
namespace MWC_Localization_Core
{
/// <summary>
/// Represents a translation pattern with extraction and formatting logic
/// Supports placeholders, regex, comma-separated values, and custom handlers
/// </summary>
public class TranslationPattern
{
public string Name { get; private set; }
public TranslationMode Mode { get; private set; }
public string OriginalPattern { get; private set; }
public string TranslatedTemplate { get; private set; }
// For path-based matching
public Func<string, bool> PathMatcher { get; set; }
public Func<string, bool> TextMatcher { get; set; }
// For FsmPattern mode
private string[] originalParts;
private string[] translationParts;
// For RegexExtract mode
private Regex regexPattern;
// For CustomHandler mode
public Func<string, string, Dictionary<string, string>, CustomHandlerResult> CustomHandler { get; set; }
// Result struct for custom handlers (NET35 compatible)
public struct CustomHandlerResult
{
public bool Success;
public string Result;
public CustomHandlerResult(bool success, string result)
{
Success = success;
Result = result;
}
}
public TranslationPattern(string name, TranslationMode mode, string originalPattern, string translatedTemplate)
{
Name = name;
Mode = mode;
OriginalPattern = originalPattern;
TranslatedTemplate = translatedTemplate;
Initialize();
}
private void Initialize()
{
switch (Mode)
{
case TranslationMode.FsmPattern:
case TranslationMode.FsmPatternWithTranslation:
InitializeFsmPattern();
break;
case TranslationMode.RegexExtract:
InitializeRegexPattern();
break;
}
}
private void InitializeFsmPattern()
{
// Split patterns by placeholders to get static parts
// Example: "pakkasta {0} astetta" -> ["pakkasta ", " astetta"]
originalParts = SplitPattern(OriginalPattern);
translationParts = SplitPattern(TranslatedTemplate);
}
private string[] SplitPattern(string pattern)
{
List<string> parts = new List<string>();
int lastIndex = 0;
// Find all placeholders {0}, {1}, {2}, ... in the pattern
for (int i = 0; i < 10; i++)
{
string placeholder = "{" + i + "}";
int index = pattern.IndexOf(placeholder, lastIndex);
if (index >= 0)
{
// Add text before this placeholder
parts.Add(pattern.Substring(lastIndex, index - lastIndex));
lastIndex = index + placeholder.Length;
}
else
{
// No more placeholders found - break early
break;
}
}
// Add remaining text after last placeholder
if (lastIndex < pattern.Length)
{
parts.Add(pattern.Substring(lastIndex));
}
else if (lastIndex == pattern.Length && parts.Count > 0)
{
// Pattern ends with a placeholder - add empty string
parts.Add("");
}
return parts.ToArray();
}
private void InitializeRegexPattern()
{
try
{
regexPattern = new Regex(OriginalPattern, RegexOptions.IgnoreCase);
}
catch (Exception ex)
{
Debug.LogError($"Failed to compile regex pattern '{OriginalPattern}': {ex.Message}");
}
}
/// <summary>
/// Check if this pattern matches the given text and path
/// </summary>
public bool Matches(string text, string path)
{
// Check path matcher if defined
if (PathMatcher != null && !PathMatcher(path))
return false;
// Check text matcher if defined
if (TextMatcher != null && !TextMatcher(text))
return false;
// Mode-specific matching
switch (Mode)
{
case TranslationMode.FsmPattern:
case TranslationMode.FsmPatternWithTranslation:
return TryExtractFsmValues(text) != null;
case TranslationMode.RegexExtract:
return regexPattern != null && regexPattern.IsMatch(text);
case TranslationMode.CommaSeparated:
return text.Contains(",");
default:
return false;
}
}
/// <summary>
/// Extract values from text and apply translation template
/// Returns null if extraction failed
/// </summary>
public string TryTranslate(string text, string path, Dictionary<string, string> translations)
{
if (!Matches(text, path))
return null;
switch (Mode)
{
case TranslationMode.FsmPattern:
return TranslateWithFsmPattern(text);
case TranslationMode.FsmPatternWithTranslation:
return TranslateWithFsmPatternAndTranslateParams(text, translations);
case TranslationMode.RegexExtract:
return TranslateWithRegex(text, translations);
case TranslationMode.CommaSeparated:
return TranslateCommaSeparated(text, translations);
case TranslationMode.CustomHandler:
if (CustomHandler != null)
{
var result = CustomHandler(text, path, translations);
return result.Success ? result.Result : null;
}
break;
}
return null;
}
private string TranslateWithFsmPattern(string text)
{
string[] values = TryExtractFsmValues(text);
if (values == null)
return null;
string result = TranslatedTemplate;
for (int i = 0; i < values.Length; i++)
{
result = result.Replace("{" + i + "}", values[i]);
}
return result;
}
private string TranslateWithFsmPatternAndTranslateParams(string text, Dictionary<string, string> translations)
{
string[] values = TryExtractFsmValues(text);
if (values == null)
return null;
string result = TranslatedTemplate;
for (int i = 0; i < values.Length; i++)
{
string originalValue = values[i];
// Try to translate the parameter value
string translatedValue = originalValue;
string key = MLCUtils.FormatUpperKey(originalValue);
if (translations.TryGetValue(key, out string translation))
{
translatedValue = translation;
}
result = result.Replace("{" + i + "}", translatedValue);
}
return result;
}
private string[] TryExtractFsmValues(string input)
{
if (originalParts == null || originalParts.Length == 0)
return null;
List<string> values = new List<string>();
string remaining = input;
for (int i = 0; i < originalParts.Length; i++)
{
string part = originalParts[i];
// Skip empty parts in the middle (consecutive placeholders like {0}{1})
if (string.IsNullOrEmpty(part) && i < originalParts.Length - 1)
{
// Empty part between placeholders - no static text to match
continue;
}
if (i == originalParts.Length - 1)
{
// Last part - must end with this
if (!remaining.EndsWith(part))
return null;
// Extract everything before this last part (only if part is non-empty)
if (part.Length > 0)
{
if (remaining.Length > part.Length)
{
values.Add(remaining.Substring(0, remaining.Length - part.Length));
}
}
else
{
// Pattern ends with placeholder - remaining text IS the last value
if (!string.IsNullOrEmpty(remaining))
{
values.Add(remaining);
}
}
}
else
{
// Middle part - find this part in remaining string
int idx = remaining.IndexOf(part);
if (idx < 0)
return null;
// Extract value before this part (if any)
if (idx > 0)
{
values.Add(remaining.Substring(0, idx));
}
// Move past this part
remaining = remaining.Substring(idx + part.Length);
}
}
return values.ToArray();
}
private string TranslateWithRegex(string text, Dictionary<string, string> translations)
{
Match match = regexPattern.Match(text);
if (!match.Success)
return null;
string result = TranslatedTemplate;
// Replace {0}, {1}, {2} with captured groups
for (int i = 1; i < match.Groups.Count; i++)
{
result = result.Replace("{" + (i - 1) + "}", match.Groups[i].Value);
}
// Replace {KEYNAME} with translations (e.g., {PRICETOTAL})
foreach (Match keyMatch in Regex.Matches(result, @"\{([A-Z]+)\}"))
{
string key = keyMatch.Groups[1].Value;
if (translations.TryGetValue(key, out string translation))
{
result = result.Replace("{" + key + "}", translation);
}
}
return result;
}
private string TranslateCommaSeparated(string text, Dictionary<string, string> translations)
{
string[] words = text.Split(',');
for (int i = 0; i < words.Length; i++)
{
string word = words[i].Trim();
string key = MLCUtils.FormatUpperKey(word);
if (translations.TryGetValue(key, out string translation))
{
words[i] = translation;
}
else
{
words[i] = word;
}
}
return string.Join(", ", words);
}
}
}