-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
517 lines (450 loc) · 24.1 KB
/
Program.cs
File metadata and controls
517 lines (450 loc) · 24.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
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
/*
* Copyright (C) 2025 Tekat, ha-ves
*
* This program is licensed under the GNU Affero General Public License v3 or later.
* See <https://www.gnu.org/licenses/>.
*/
using CommandLine;
using CommandLine.Text;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.VisualBasic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using TyranoScriptMemoryUnlocker.Asar;
using TyranoScriptMemoryUnlocker.Res;
using static TyranoScriptMemoryUnlocker.TyranoScript.TyranoScript;
namespace TyranoScriptMemoryUnlocker
{
public class TSMU
{
public class TSMUArgs
{
[Option('v', "verbose", FlagCounter = true, HelpText = nameof(LocalizedString.HelpTextVerbose), ResourceType = typeof(LocalizedString))]
public int Verbosity { get; set; } = 0;
[Option('a', "asar", Required = true, HelpText = nameof(LocalizedString.HelpTextAsar), ResourceType = typeof(LocalizedString))]
public string AsarPath { get; set; } = string.Empty;
[Option('s', "sav", Required = true, HelpText = nameof(LocalizedString.HelpTextSav), ResourceType = typeof(LocalizedString))]
public string SavPath { get; set; } = string.Empty;
[Option("dry", HelpText = nameof(LocalizedString.HelpTextDryRun), ResourceType = typeof(LocalizedString))]
public bool DryRun { get; set; } = false;
}
internal const string SearchTopPath = "data/scenario";
internal const string ScriptExt = "ks";
internal const string CGKsPath = "data/scenario/cg.ks";
internal const string ReplayKsPath = "data/scenario/replay.ks";
internal const string CGViewKey = "cg_view";
internal const string ReplayViewKey = "replay_view";
internal const string ViewStorageKey = "storage";
internal const string ViewTargetKey = "target";
internal const string CGEnableValue = "on";
private static ILoggerFactory? logger;
private static ILogger? log;
static TSMUArgs? Args;
#pragma warning disable IDE0079 // Remove unnecessary suppression
[SuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code",
Justification = Suppressions.JsonTrimmingJustification)]
#pragma warning restore IDE0079 // Remove unnecessary suppression
[DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(TSMUArgs))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(LocalizedString))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(LocalizedArgsSentenceBuild))]
public static void Main(string[] args)
{
Console.OutputEncoding = new UTF8Encoding(false);
LocalizedString.Culture = System.Globalization.CultureInfo.CurrentCulture;
var cmd = Assembly.GetExecutingAssembly()
.GetName().Name;
var title = Assembly.GetExecutingAssembly()
.GetCustomAttribute<AssemblyTitleAttribute>()?
.Title;
var desc = string.Format(LocalizedString.Desc, title);
var build = Assembly.GetExecutingAssembly()
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
.InformationalVersion;
if (build?.IndexOf('+') is int idx && idx > 0)
// only get up to the short commit hash if present
build = build[..(idx + 14)];
var copr = Assembly.GetExecutingAssembly()
.GetCustomAttribute<AssemblyCopyrightAttribute>()?
.Copyright;
var lic = LocalizedString.AppLic;
var dsclmr = LocalizedString.AppDisclaimer;
SentenceBuilder.Factory = () => new LocalizedArgsSentenceBuild();
var parser = new Parser(with =>
{
with.HelpWriter = null;
with.AutoVersion = false;
with.AllowMultiInstance = true;
});
var parsed = parser.ParseArguments<TSMUArgs>(args);
parsed.WithParsed(args =>
{
if (!Path.Exists(args.SavPath = Path.GetFullPath(args.SavPath ?? string.Empty)))
{
ExitArgsError(string.Format(LocalizedString.ErrorSavNotFound, args.SavPath),
cmd, title, build, copr, lic, dsclmr);
return;
}
if (!Path.Exists(args.AsarPath = Path.GetFullPath(args.AsarPath ?? string.Empty)))
{
ExitArgsError(string.Format(LocalizedString.ErrorAsarNotFound, args.AsarPath),
cmd, title, build, copr, lic, dsclmr);
return;
}
})
.WithNotParsed(errors =>
{
if (errors.IsHelp())
{
HelpArgExit(title, desc, build, copr, lic, dsclmr, parsed);
return;
}
var err = errors.FirstOrDefault() switch
{
MissingRequiredOptionError m => string.Format(LocalizedString.ArgMissing, $" '-{m.NameInfo.ShortName}' / '--{m.NameInfo.LongName}'"),
UnknownOptionError u => string.Format(LocalizedString.ArgUnknown, $" '{(u.Token.Length > 1 ? "--" : '-')}{u.Token}'"),
NamedError n => string.Format(LocalizedString.ArgInvalid, $" '{n.NameInfo.NameText}' "),
CommandLine.Error e => $"{LocalizedString.ArgErrorUnknown} ({e.Tag}:{e.GetType()})",
_ => LocalizedString.ArgErrorUnknown
};
ExitArgsError(err, cmd, title, build, copr, lic, dsclmr);
return;
});
Args = parsed.Value;
logger = LoggerFactory.Create(cfg =>
{
cfg.ClearProviders().AddSimpleConsole(opt =>
{
opt.IncludeScopes = opt.SingleLine = true;
opt.TimestampFormat = "[HH:mm:ss.ffffff]";
});
cfg.SetMinimumLevel((LogLevel)Math.Max((int)(LogLevel.Information - Args.Verbosity), 0));
});
log = logger.CreateLogger(nameof(TSMU));
var tablelog = LoggerFactory.Create(cfg =>
{
cfg.ClearProviders().AddSimpleConsole(opt =>
{
opt.IncludeScopes = true;
opt.TimestampFormat = "[HH:mm:ss.ffffff]";
opt.SingleLine = false;
});
cfg.SetMinimumLevel((LogLevel)Math.Max((int)(LogLevel.Information - Args.Verbosity), 0));
})
.CreateLogger(nameof(TSMU));
log.LogInformation("{title} {build} {copr}. {lic} {dsclmr}", title, build, copr, lic, dsclmr);
if (Args.DryRun)
log.LogInformation("{Dry}", LocalizedString.DryModeNotice);
try
{
log.LogDebug("{asar}", string.Format(LocalizedString.OpenAsar, Args.AsarPath));
using var asar = AsarFile.Open(Args.AsarPath ?? string.Empty);
var scripts = FindFilesByExt(asar, ScriptExt, SearchTopPath).ToList();
if (log.IsEnabled(LogLevel.Trace))
tablelog.PrintTable(LogLevel.Trace, scripts.Select(s => s.Name), LocalizedString.FoundScripts, widthOfTable: 76);
log.LogDebug("{count}", string.Format(LocalizedString.FoundAsarScripts, scripts.Count));
var cgks = asar.Files[CGKsPath] as AsarFileEntry ?? throw new FileNotFoundException("File not found in archive.", CGKsPath);
var cggallery = GetUnlockableCG(new StreamReader(cgks.ReadAsFileStream(true), Encoding.UTF8)).ToList();
if (log.IsEnabled(LogLevel.Trace))
tablelog.PrintTable(LogLevel.Trace, cggallery, LocalizedString.UnlockableCGs, widthOfTable: 76);
log.LogInformation("{count}", string.Format(LocalizedString.FoundCGs, cggallery.Count));
var replayks = asar.Files[ReplayKsPath] as AsarFileEntry ?? throw new FileNotFoundException("File not found in archive.", ReplayKsPath);
var replaygallery = GetReplayButton(new StreamReader(replayks.ReadAsFileStream(true), Encoding.UTF8)).ToList();
if (log.IsEnabled(LogLevel.Trace))
tablelog.PrintTable(LogLevel.Trace, replaygallery, LocalizedString.UnlockableReplays, widthOfTable: 76);
log.LogInformation("{count}", string.Format(LocalizedString.FoundReplays, replaygallery.Count));
FileAccess accs = FileAccess.ReadWrite;
if (Args.DryRun)
accs = FileAccess.Read; // Read-only access for dry run
log.LogInformation("{sav}", string.Format(LocalizedString.OpenSav, Args.SavPath));
using var savfs = new FileStream(Args.SavPath ?? string.Empty, FileMode.Open, accs);
string bakfile;
int iter = 0;
do
{
bakfile = Path.ChangeExtension(Args.SavPath ?? string.Empty, $"bak{DateTime.Now:yyyyMMddHHmmss}.{iter++}{Path.GetExtension(Args.SavPath)}");
}
while (File.Exists(bakfile));
if (!Args.DryRun)
{
log.LogDebug("{bak}", string.Format(LocalizedString.SavBackup, Args.SavPath, bakfile));
using (var savbak = new FileStream(bakfile, FileMode.CreateNew, FileAccess.Write))
savfs.CopyTo(savbak);
savfs.Position = 0;
}
else
{
log.LogDebug("{bak}", LocalizedString.SavBackupCancel);
log.LogDebug("{bak}", string.Format(LocalizedString.SavBackupDry, Args.SavPath, bakfile));
}
log.LogDebug("{json}", LocalizedString.SavJsonParse);
using var savread = new StreamReader(savfs, Encoding.UTF8, leaveOpen: true);
var savun = Uri.UnescapeDataString(savread.ReadToEnd());
JsonNode savjson;
List<string> savcgs;
List<KeyValuePair<string, string>> savrply;
try
{
savjson = JsonNode.Parse(savun) ?? throw new JsonException(LocalizedString.ExcInvalidSav);
savcgs = [..(savjson[CGViewKey] as JsonObject)?.Select(p => p.Key)
?? throw new JsonException(string.Format(LocalizedString.ExcInvalidView, CGViewKey))];
if (log.IsEnabled(LogLevel.Trace))
tablelog.PrintTable(LogLevel.Trace, savcgs, LocalizedString.UnlockedCGsAlr, widthOfTable: 76);
savrply = [..(savjson[ReplayViewKey] as JsonObject)?.Select(p =>
new KeyValuePair<string, string>(p.Key, p.Value![ViewStorageKey]!.GetValue<string>()))
?? throw new JsonException(string.Format(LocalizedString.ExcInvalidView, ReplayViewKey))];
if (log.IsEnabled(LogLevel.Trace))
tablelog.PrintTable(LogLevel.Trace, savrply.Select(kvp => $"{kvp.Key}={kvp.Value}"),
LocalizedString.UnlockedReplaysAlr, widthOfTable: 76);
}
catch (JsonException exc)
{
log.LogError(exc, "{exc}", LocalizedString.JsonExc);
Environment.Exit(1);
return; // Unreachable, but required to satisfy compiler
}
var cgremain = cggallery.Except(savcgs);
if (cgremain.Any())
log.LogInformation("{count}", string.Format(LocalizedString.UnlockedCGs, cgremain.Count()));
savcgs = [.. savcgs, .. cgremain];
var savcgsdict = savcgs.GroupBy(k => k).ToDictionary(g => g.Key, k => CGEnableValue);
// check if there are replays to add
Dictionary<string, Dictionary<string, string>>? savrplydict = null;
var replayremain = replaygallery.Except(savrply.Select(s => s.Key));
if (replayremain.Any())
{
/// only get the <see cref="ViewStorageKey"/> but maybe some replays use the <see cref="ViewTargetKey"/> too...
/// TODO: check if the <see cref="ViewTargetKey"/> is used in the replays.
var replayable = scripts.SelectMany(fl => GetUnlockableReplay(new StreamReader(fl.ReadAsFileStream(true), Encoding.UTF8)));
log.LogInformation("{count}", string.Format(LocalizedString.UnlockedReplays, replayremain.Count()));
savrply = [.. savrply, .. replayable];
savrplydict = savrply.GroupBy(k => k.Key).ToDictionary(g => g.Key,
g => new Dictionary<string, string>
{
[ViewStorageKey] = g.Last().Value,
[ViewTargetKey] = string.Empty
});
}
log.LogDebug("{json}", LocalizedString.SavJsonSerialize);
savjson[CGViewKey] = JsonSerializer.SerializeToNode(savcgsdict,JsonDictSerializeContext.Default.CGViewKey);
savjson[ReplayViewKey] = JsonSerializer.SerializeToNode(savrplydict, JsonDictSerializeContext.Default.ReplayViewKey);
savfs.Position = 0;
var savjsoned = savjson.ToJsonString();
var savjsonen = Uri.EscapeDataString(savjsoned);
if (Args.DryRun)
{
log.LogInformation("{dry}", LocalizedString.DryModeNotice);
log.LogDebug("{sav}", string.Format(LocalizedString.SavingSavDry, Args.SavPath));
}
else
{
log.LogInformation("{sav}", string.Format(LocalizedString.SavingSav, Args.SavPath));
using var savwrite = new StreamWriter(savfs, new UTF8Encoding(false));
savwrite.Write(savjsonen);
savwrite.Flush();
}
log.LogInformation("{sym}", LocalizedString.LogLineDone);
log.LogInformation("{msg}", LocalizedString.AppSuccess_Line1);
log.LogInformation("{msg}", LocalizedString.AppSuccess_Line2);
log.LogInformation("{msg}", string.Format(LocalizedString.AppSuccess_Line3, savcgsdict.Count));
if (savrplydict != null)
log.LogInformation("{msg}", string.Format(LocalizedString.AppSuccess_Line4, savrplydict.Count));
else
log.LogInformation("{msg}", string.Format(LocalizedString.AppSuccess_Line4, savrply.Count));
log.LogInformation("{sym}", LocalizedString.LogLine);
log.LogInformation("{sym}", LocalizedString.LogLineTY);
log.LogInformation("{title} {ver}", title, build);
log.LogInformation("{copr}. {lic}", copr, lic);
log.LogInformation("{sym}", LocalizedString.LogLine);
}
catch (Exception exc)
{
log?.LogError(exc, "{exc}", LocalizedString.ErrorAsarSav);
Environment.Exit(1);
}
}
private static void HelpArgExit(string? title, string desc, string? build, string? copr, string lic, string dsclmr, ParserResult<TSMUArgs> parsed)
{
var helpText = HelpText.AutoBuild(parsed, h =>
{
h.AddEnumValuesToHelpText = true;
h.AutoVersion = false;
h.Heading = $"{title} {build} {copr}.";
h.Copyright = $"{lic} {dsclmr} {Environment.NewLine}";
h.AddPreOptionsText(string.Format(LocalizedString.HelpTextDesc,
desc, Environment.NewLine, LocalizedString.HelpTextOptPath));
return h;
}, e => e);
Console.WriteLine(helpText);
Environment.Exit(0);
}
private static void ExitArgsError(string? err, string? cmd, string? title, string? build, string? copr, string? lic, string? dsclmr)
{
var errText = new HelpText
{
Heading = $"{title} {build} {copr}.",
Copyright = $"{lic} {dsclmr}" + Environment.NewLine,
};
errText.AddPreOptionsLine(err);
errText.AddPreOptionsLine(string.Empty);
errText.AddPreOptionsLine(string.Format(LocalizedString.ErrorHelpCmd, cmd));
Console.WriteLine(errText);
Environment.Exit(1);
}
}
public static class LogExtensions
{
public static void PrintTable(this ILogger logger, LogLevel level, IEnumerable<string?>? items, string? title = null, int widthOfTable = 80, int forceCols = -1)
{
if (items == null || !items.Any())
return;
// Helper function to calculate display width (counts kana and fullwidth characters as 2)
int GetDisplayWidth(string text)
{
int width = 0;
foreach (var c in text)
{
if ((c >= '\u3040' && c <= '\u309F') || // Hiragana
(c >= '\u30A0' && c <= '\u30FF') || // Katakana
(c >= '\uFF01' && c <= '\uFF60') || // Fullwidth punctuation and symbols
(c >= '\u4E00' && c <= '\u9FFF')) // CJK Unified Ideographs (Kanji)
{
width += 2;
}
else
{
width += 1;
}
}
return width;
}
// Helper function to truncate a string by display width
string TruncateToDisplayWidth(string text, int maxWidth)
{
int width = 0;
var sb = new StringBuilder();
foreach (var c in text)
{
int charWidth = ((c >= '\u3040' && c <= '\u309F') ||
(c >= '\u30A0' && c <= '\u30FF') ||
(c >= '\uFF01' && c <= '\uFF60')) ? 2 : 1;
if (width + charWidth > maxWidth)
break;
sb.Append(c);
width += charWidth;
}
return sb.ToString();
}
// Define padding to add extra spaces between columns.
int padding = 2;
// In PrintTable, ensure items are not null before using .Average(s => s.Length).
double avgLen = items!.Average(s => s!.Length);
int tentativeCellWidth = (int)Math.Ceiling(avgLen);
// Determine effective width using the provided widthOfTable.
int availableWidth = Math.Min(Console.WindowWidth, widthOfTable);
// Compute the number of columns based on tentative cell width.
int computedCols = forceCols > 0 ? forceCols : Math.Max(1, availableWidth / (tentativeCellWidth + padding + 3));
int columns = computedCols;
// Recalculate cellWidth so that the table always maximizes to the availableWidth.
// TotalWidth = columns * (cellWidth + 2) + (columns + 1) should equal availableWidth.
int cellWidth = (availableWidth - (3 * columns + 1)) / columns;
// Group items into rows based on the computed column count.
var rowsList = items
.Select((val, idx) => new { val, idx })
.GroupBy(x => x.idx / columns)
.Select(g => g.Select(x => x.val).ToList())
.ToList();
// Local word-wrap function: splits a string into lines of maximum width (cellWidth).
static List<string> WordWrap(string text, int maxWidth)
{
var wrapped = new List<string>();
if (string.IsNullOrEmpty(text))
{
wrapped.Add(string.Empty);
return wrapped;
}
var words = text.Split(' ');
var line = new StringBuilder();
foreach (var word in words)
{
if (line.Length + word.Length + 1 > maxWidth)
{
if (line.Length > 0)
{
wrapped.Add(line.ToString());
line.Clear();
}
// If the single word is longer than maxWidth, split it.
string tempWord = word;
while (tempWord.Length > maxWidth)
{
wrapped.Add(tempWord[..maxWidth]);
tempWord = tempWord[maxWidth..];
}
line.Append(tempWord);
}
else
{
if (line.Length > 0)
line.Append(' ');
line.Append(word);
}
}
if (line.Length > 0)
wrapped.Add(line.ToString());
return wrapped;
}
// Calculate total width: each cell has vertical borders.
int totalWidth = columns * (cellWidth + 2) + (columns + 1);
string horizontalLine = new('-', totalWidth);
var sb = new StringBuilder();
sb.AppendLine(horizontalLine);
if (!string.IsNullOrEmpty(title))
{
// Create a single row for the title spanning all columns.
int spanWidth = totalWidth - 2; // subtracting borders
string formattedTitle = GetDisplayWidth(title) > spanWidth ? TruncateToDisplayWidth(title, spanWidth) : title;
int titleDisplayWidth = GetDisplayWidth(formattedTitle);
int padTotal = spanWidth - titleDisplayWidth;
int padLeft = padTotal / 2;
int padRight = padTotal - padLeft;
formattedTitle = new string(' ', padLeft) + formattedTitle + new string(' ', padRight);
sb.AppendLine("|" + formattedTitle + "|");
sb.AppendLine(horizontalLine);
}
for (int i = 0; i < rowsList.Count; i++)
{
var row = rowsList[i];
// Fix for CS8604: Ensure 'cell' is not null before passing to WordWrap
var wrappedCells = row.Select(cell => WordWrap(cell ?? string.Empty, cellWidth)).ToList();
int rowHeight = wrappedCells.Max(wrap => wrap.Count);
for (int lineIdx = 0; lineIdx < rowHeight; lineIdx++)
{
sb.Append('|');
foreach (var cellWrap in wrappedCells)
{
string cellLine = lineIdx < cellWrap.Count ? cellWrap[lineIdx] : string.Empty;
sb.Append(' ');
sb.Append(cellLine.PadRight(cellWidth));
sb.Append(" |");
}
sb.AppendLine();
}
sb.AppendLine(horizontalLine);
}
logger.Log(level, "{table}", sb.ToString());
}
}
[JsonSourceGenerationOptions(WriteIndented = false)]
[JsonSerializable(typeof(Dictionary<string, string>),
GenerationMode = JsonSourceGenerationMode.Serialization,
TypeInfoPropertyName = nameof(TSMU.CGViewKey))]
[JsonSerializable(typeof(Dictionary<string, Dictionary<string, string>>),
GenerationMode = JsonSourceGenerationMode.Serialization,
TypeInfoPropertyName = nameof(TSMU.ReplayViewKey))]
internal partial class JsonDictSerializeContext : JsonSerializerContext { }
}