-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathScanOptions.cs
636 lines (558 loc) · 22 KB
/
ScanOptions.cs
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
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PSXPrev.Common.Parsers;
using PSXPrev.Common.Utils;
namespace PSXPrev
{
public static class ScanFormats
{
public const string AN = ANParser.FormatNameConst;
public const string BFF = BFFParser.FormatNameConst;
//public const string CLT = CLTParser.FormatNameConst;
public const string HMD = HMDParser.FormatNameConst;
public const string MOD = MODParser.FormatNameConst;
public const string PIL = PILParser.FormatNameConst;
public const string PMD = PMDParser.FormatNameConst;
public const string PSX = PSXParser.FormatNameConst;
//public const string PXL = PXLParser.FormatNameConst;
public const string SPT = SPTParser.FormatNameConst;
public const string TIM = TIMParser.FormatNameConst;
public const string TMD = TMDParser.FormatNameConst;
public const string TOD = TODParser.FormatNameConst;
public const string VDF = VDFParser.FormatNameConst;
// note: CLT and PXL are not supported yet
public static readonly string[] All =
{
AN, BFF, /*CLT,*/ HMD, MOD, PIL, PMD, PSX, /*PXL,*/ SPT, TIM, TMD, TOD, VDF,
};
// Formats that can only be used if explicitly selected
// todo: AN produces too many false positives to be enabled by default
public static readonly string[] Explicit =
{
SPT,
};
// Formats that are used when no format is selected
// Setup during static constructor
public static readonly string[] Implicit;
public static int Count => All.Length;
public static bool IsSupported(string format)
{
return Array.IndexOf(All, format) != -1;
}
public static bool IsExplicit(string format)
{
return Array.IndexOf(Explicit, format) != -1;
}
public static bool IsImplicit(string format)
{
return Array.IndexOf(Implicit, format) != -1;
}
static ScanFormats()
{
Array.Sort(All);
Array.Sort(Explicit);
var implicitFormats = new List<string>();
foreach (var format in All)
{
if (!IsExplicit(format))
{
implicitFormats.Add(format);
}
}
Implicit = implicitFormats.ToArray();
}
}
[JsonObject]
public class ScanOptions : IEquatable<ScanOptions>, ICloneable
{
public static readonly ScanOptions Defaults = new ScanOptions();
public const string DefaultFilter = "*"; //"*.*";
public const string DefaultRegexPattern = "^.*$";
// Use a timeout to avoid user-specified runaway Regex patterns.
private static readonly TimeSpan MatchTimeout = TimeSpan.FromMilliseconds(100);
// Equality checking and optimization.
[JsonIgnore]
private string _equalityString;
[JsonIgnore]
private int _equalityStringHashCode;
[JsonIgnore]
private bool _isReadOnly;
// Set to true to claim that fields will not be changed. Used to optimize equality checks.
[JsonIgnore]
public bool IsReadOnly
{
get => _isReadOnly;
set
{
_isReadOnly = value;
if (!_isReadOnly)
{
_equalityString = null;
_equalityStringHashCode = 0;
}
}
}
// Optional display name to assign to history
[JsonProperty("displayName", DefaultValueHandling = DefaultValueHandling.Ignore)]
public string DisplayName { get; set; } = null;
// Optionally prevent this from being removed from the history list
[JsonProperty("bookmarked", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool IsBookmarked { get; set; } = false;
// These settings are only present for loading and saving purposes.
// File path:
[JsonProperty("path")]
public string Path { get; set; } = string.Empty;
[JsonProperty("wildcardFilter")]
public string WildcardFilter { get; set; } = DefaultFilter;
[JsonProperty("regexFilter")]
public string RegexPattern { get; set; } = DefaultRegexPattern;
[JsonIgnore]
public string ValidatedWildcardFilter
{
get
{
if (string.IsNullOrWhiteSpace(WildcardFilter))
{
return DefaultFilter;
}
return WildcardFilter;
}
}
[JsonIgnore]
public string ValidatedRegexPattern
{
get
{
if (string.IsNullOrEmpty(RegexPattern))
{
return DefaultRegexPattern;
}
return RegexPattern;
}
}
[JsonProperty("useRegexFilter")]
public bool UseRegex { get; set; } = false;
// Scanner formats:
[JsonProperty("formats")]
public List<string> Formats { get; set; } = new List<string>();
// Formats with reduced strictness, such as ignoring versions/magic
[JsonProperty("unstrictFormats")]
public List<string> UnstrictFormats { get; set; } = new List<string>();
public bool ContainsFormat(string format)
{
return ContainsFormat(format, out _);
}
public bool ContainsFormat(string format, out bool isImplicit)
{
if (Formats.Count > 0)
{
isImplicit = false;
return Formats.Contains(format);
}
else
{
isImplicit = ScanFormats.IsImplicit(format);
return isImplicit;
}
}
public bool AddFormat(string format)
{
if (!Formats.Contains(format) && ScanFormats.IsSupported(format))
{
Formats.Add(format);
Formats.Sort();
return true;
}
return false;
}
public bool RemoveFormat(string format)
{
return Formats.Remove(format);
}
public bool ContainsUnstrict(string format)
{
return UnstrictFormats.Contains(format);
}
public bool AddUnstrict(string format)
{
if (!UnstrictFormats.Contains(format) && ScanFormats.IsSupported(format))
{
UnstrictFormats.Add(format);
UnstrictFormats.Sort();
return true;
}
return false;
}
public bool RemoveUnstrict(string format)
{
return UnstrictFormats.Remove(format);
}
public string[] GetCheckedFormats(bool groupAll)
{
if (Formats.Count == ScanFormats.Count && groupAll)
{
return new string[] { "All" };
}
else if (Formats.Count == 0)
{
if (groupAll)
{
return new string[] { "Defaults" };
}
else
{
return (string[])ScanFormats.Implicit.Clone();
}
}
else
{
return Formats.ToArray();
}
}
// Scanner options:
[JsonProperty("fileOffsetAlign")]
public long Alignment { get; set; } = 1;
// We want nullables, but we also want to preserve the last-used values in the UI when null.
[JsonProperty("fileOffsetHasStart")]
public bool StartOffsetHasValue { get; set; } = false;
[JsonProperty("fileOffsetHasStop")]
public bool StopOffsetHasValue { get; set; } = false;
[JsonProperty("fileOffsetStart")]
public long StartOffsetValue { get; set; } = 0;
[JsonProperty("fileOffsetStop")]
public long StopOffsetValue { get; set; } = 1;
[JsonIgnore]
public long StartOffset => StartOffsetHasValue ? StartOffsetValue : 0;
[JsonIgnore]
public long? StopOffset => StopOffsetHasValue ? (long?)StopOffsetValue : null;
[JsonProperty("fileOffsetStartOnly")]
public bool StartOffsetOnly { get; set; } = false;
[JsonProperty("fileOffsetNext")]
public bool NextOffset { get; set; } = false;
[JsonProperty("fileScanAsync")]
public bool AsyncFileScan { get; set; } = true;
[JsonProperty("fileSearchTopDown")]
public bool TopDownFileSearch { get; set; } = true; // AKA depth-first
[JsonProperty("fileSearchISOContents")]
public bool ReadISOContents { get; set; } = true; // Disable this by default when parsing command line arguments
[JsonProperty("fileSearchBINContents")]
public bool ReadBINContents { get; set; } = false; // Read indexed files instead of data of BIN file.
[JsonProperty("fileSearchBINSectorData")]
public bool ReadBINSectorData { get; set; } = false; // Read BIN file as one large data file.
// We want nullables, but we also want to preserve the last-used values in the UI when null.
// These may be removed in the future because it turns out sector sizes are always the same.
// The reason I thought it was different is because Star Ocean 2 uses an archive format that cuts out more of the user size.
[JsonProperty("binSectorHasStartSize")]
public bool BINSectorUserStartSizeHasValue { get; set; } = false;
[JsonProperty("binSectorStart")]
public int BINSectorUserStartValue { get; set; } = BinCDStream.SectorUserStart;
[JsonProperty("binSectorSize")]
public int BINSectorUserSizeValue { get; set; } = BinCDStream.SectorUserSize;
[JsonIgnore]
public int BINSectorUserStart => BINSectorUserStartSizeHasValue ? BINSectorUserStartValue : BinCDStream.SectorUserStart;
[JsonIgnore]
public int BINSectorUserSize => BINSectorUserStartSizeHasValue ? BINSectorUserSizeValue : BinCDStream.SectorUserSize;
// Log options:
[JsonProperty("logToFile")]
public bool LogToFile { get; set; } = false;
[JsonProperty("logToConsole")]
public bool LogToConsole { get; set; } = true;
[JsonProperty("debugLogging")]
public bool DebugLogging { get; set; } = false;
[JsonProperty("errorLogging")]
public bool ErrorLogging { get; set; } = false;
// Program options:
[JsonProperty("drawAllToVRAM")]
public bool DrawAllToVRAM { get; set; } = false;
// Used for version upgrades to read properties that are no longer present in the current class
[JsonExtensionData(ReadData = true, WriteData = false)]
private Dictionary<string, JToken> _unknownData;
//[OnDeserialized]
//private void OnDeserializedMethod(StreamingContext context)
//{
//}
public void ValidateDeserialization(uint version)
{
Formats = ValidateFormats(Formats);
UnstrictFormats = ValidateFormats(UnstrictFormats);
if (version <= 2 && _unknownData != null)
{
UpgradeFormatsToVersion3(version);
}
// Handle normal validation that's used outside of just deserialization
Validate();
_unknownData = null; // We don't need this anymore
}
// Remove null, unsupported, and duplicate format names, then ensure formats are sorted
private static List<string> ValidateFormats(List<string> formats)
{
if (formats == null)
{
formats = new List<string>();
}
else
{
var duplicates = new HashSet<string>();
for (var i = 0; i < formats.Count; i++)
{
var format = formats[i];
if (format == null || !ScanFormats.IsSupported(format) || !duplicates.Add(format))
{
formats.RemoveAt(i);
i--;
}
}
formats.Sort();
}
return formats;
}
// Previously formats were stored in individual "format___": bool properties.
// Handle switching to list storage.
private void UpgradeFormatsToVersion3(uint version)
{
void UpgradeFormat(string propertyName, string format)
{
if (_unknownData.TryGetValue(propertyName, out var token))
{
_unknownData.Remove(propertyName); // Not unknown data anymore
if (token.Type == JTokenType.Boolean && token.ToObject<bool>())
{
AddFormat(format);
// PIL format was introduced in the middle of version 2,
// and was grouped together with BFF.
if (version == 2 && format == BFFParser.FormatNameConst)
{
AddFormat(PILParser.FormatNameConst);
}
}
}
}
void UpgradeUnstrict(string propertyName, string format)
{
if (_unknownData.TryGetValue(propertyName, out var token))
{
_unknownData.Remove(propertyName); // Not unknown data anymore
if (token.Type == JTokenType.Boolean && token.ToObject<bool>())
{
AddUnstrict(format);
}
}
}
UpgradeFormat("formatAN", ANParser.FormatNameConst);
UpgradeFormat("formatBFF", BFFParser.FormatNameConst);
UpgradeFormat("formatHMD", HMDParser.FormatNameConst);
UpgradeFormat("formatMOD", MODParser.FormatNameConst);
UpgradeFormat("formatPMD", PMDParser.FormatNameConst);
UpgradeFormat("formatPSX", PSXParser.FormatNameConst);
if (version == 2)
{
// Format introduced in version 2
UpgradeFormat("formatSPT", SPTParser.FormatNameConst);
}
UpgradeFormat("formatTIM", TIMParser.FormatNameConst);
UpgradeFormat("formatTMD", TMDParser.FormatNameConst);
UpgradeFormat("formatTOD", TODParser.FormatNameConst);
UpgradeFormat("formatVDF", VDFParser.FormatNameConst);
UpgradeUnstrict("ignoreHMDVersion", HMDParser.FormatNameConst);
UpgradeUnstrict("ignoreTIMVersion", TIMParser.FormatNameConst);
UpgradeUnstrict("ignoreTMDVersion", TMDParser.FormatNameConst);
}
public Regex GetRegexFilter(bool allowErrors)
{
try
{
if (!UseRegex)
{
return StringUtils.WildcardToRegex(ValidatedWildcardFilter, MatchTimeout);
}
else
{
return new Regex(ValidatedRegexPattern, RegexOptions.IgnoreCase, MatchTimeout);
}
}
catch
{
if (!allowErrors)
{
throw;
}
return null;
}
}
public void Validate()
{
if (Path == null)
{
Path = string.Empty;
}
if (string.IsNullOrEmpty(DisplayName))
{
DisplayName = null;
}
WildcardFilter = ValidatedWildcardFilter;
RegexPattern = ValidatedRegexPattern;
}
public override string ToString()
{
return ToString(-1);
}
public string ToString(int maxPathLength)
{
if (!string.IsNullOrEmpty(DisplayName))
{
return DisplayName;
}
var parts = new List<string>();
string pathStr = null;
if (maxPathLength != 0)
{
pathStr = Path ?? string.Empty;
if (maxPathLength > 0)
{
// Trim path by directories starting from the root.
// Add as many directories as possible until we hit the length cap.
var index = pathStr.Length;
do
{
// Alt: Allow overflow of at most one extra directory
//var length = pathStr.Length - index;
//if (length >= maxPathLength)
//{
// break;
//}
var sep = Math.Max(pathStr.LastIndexOf('\\', index - 1), pathStr.LastIndexOf('/', index - 1));
sep = Math.Max(0, sep);
// Current: Allow overflow for the file name only
var length = pathStr.Length - sep;
if (index != pathStr.Length && length > maxPathLength)
{
break;
}
index = sep;
}
while (index > 0);
// Don't bother using a substring if we're replacing the same number of characters with dots
// (technically the dots would take up less space though)
if (index > 3)
{
pathStr = "..." + pathStr.Substring(index);
}
}
}
string filterStr = null;
if (!UseRegex)
{
if (ValidatedWildcardFilter != DefaultFilter)
{
filterStr = ValidatedWildcardFilter;
}
}
else
{
if (ValidatedRegexPattern != DefaultRegexPattern)
{
filterStr = $"/{ValidatedRegexPattern}/"; // Use JavaScript notation to express this is regex
}
}
string formatsStr = null;
var formats = GetCheckedFormats(true);
if (formats.Length > 0)
{
formatsStr = string.Join(",", formats).ToLower();
}
if (formatsStr != null) parts.Add(formatsStr);
if (filterStr != null) parts.Add(filterStr);
if (pathStr != null) parts.Add(pathStr);
return string.Join(" | ", parts);
}
public ScanOptions Clone()
{
var options = (ScanOptions)MemberwiseClone();
options._unknownData = null;
options.Formats = new List<string>(Formats);
options.UnstrictFormats = new List<string>(UnstrictFormats);
return options;
}
object ICloneable.Clone() => Clone();
// Normalize settings for equality checks
private void Normalize()
{
Validate();
DisplayName = null;
IsBookmarked = false;
Path = Path?.ToLower();
if (Alignment < 1)
{
Alignment = 1;
}
WildcardFilter = WildcardFilter?.ToLower();
RegexPattern = RegexPattern?.ToLower();
/*if (!UseRegex)
{
WildcardFilter = WildcardFilter?.ToLower();
RegexPattern = Defaults.RegexPattern;
}
else
{
WildcardFilter = Defaults.WildcardFilter;
RegexPattern = RegexPattern?.ToLower();
}*/
/*if (!StartOffsetHasValue)
{
StartOffsetValue = Defaults.StartOffsetValue;
}
if (!StopOffsetHasValue)
{
StopOffsetValue = Defaults.StopOffsetValue;
}
if (!BINSectorUserStartSizeHasValue)
{
BINSectorUserStartValue = Defaults.BINSectorUserStartValue;
BINSectorUserSizeValue = Defaults.BINSectorUserSizeValue;
}*/
}
// It's easier to manage equality by *not* having to update the function every time settings are added.
// This is a lazy solution, but requires near-zero maintenance.
private string GetEqualityString(out int? hashCode)
{
string equalityString;
hashCode = null;
if (_equalityString != null)
{
equalityString = _equalityString;
hashCode = _equalityStringHashCode;
}
else
{
var options = Clone();
options.Normalize();
// Use settings to reduce the size of the string
var jsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.None,
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
};
equalityString = JsonConvert.SerializeObject(options, jsonSettings);// Formatting.None);
if (_isReadOnly)
{
hashCode = equalityString.GetHashCode();
_equalityString = equalityString;
_equalityStringHashCode = hashCode.Value;
}
}
return equalityString;
}
public bool Equals(ScanOptions other)
{
var str = GetEqualityString(out var hashCode);
var strOther = other.GetEqualityString(out var hashCodeOther);
// If both equalities are cached, then we can compare hash codes first to save time
return (!hashCode.HasValue || !hashCodeOther.HasValue || hashCode == hashCodeOther) && str == strOther;
}
}
}