-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1355 lines (1127 loc) · 40.5 KB
/
Program.cs
File metadata and controls
1355 lines (1127 loc) · 40.5 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
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
using System.Text;
namespace XyFavMenu;
internal static class Program
{
private static string GetVersion() =>
typeof(Program).Assembly.GetName().Version?.ToString(3) ?? "?";
private static int Main(string[] args)
{
if (args.Length == 1 && (args[0] == "--version" || args[0] == "-v"))
{
Console.WriteLine(GetVersion());
return 0;
}
if (args.Length == 0 || args.Length == 1 && (args[0] == "--help" || args[0] == "-h" || args[0] == "/?"))
{
Console.WriteLine($"XyFavMenu v{GetVersion()}");
Console.WriteLine(Options.UsageText);
return 0;
}
try
{
var options = Options.Parse(args);
var outputDirectory = options.CheckOnly
? null
: Path.GetDirectoryName(Path.GetFullPath(options.OutputPath!));
var folderIconConfig = FolderIconConfig.Load(outputDirectory);
var loader = new FavoritesLoader();
var directoryLoad = loader.Load(options.DirectoryFavoritesPath, FavoriteKind.Directory);
var fileLoad = loader.Load(options.FileFavoritesPath, FavoriteKind.File);
var problems = directoryLoad.Problems
.Concat(fileLoad.Problems)
.ToList();
var items = directoryLoad.Items
.Concat(fileLoad.Items)
.ToList();
var builder = new MenuBuilder();
var buildResult = builder.Build(items, folderIconConfig);
var root = buildResult.Root;
var outputProblems = GeneratedMenuValidator.RemoveInvalidGotoTargets(root);
if (outputProblems.Count > 0)
{
problems.AddRange(outputProblems);
}
ShowWarnings(buildResult.Warnings);
ShowProblems(problems);
if (options.CheckOnly)
{
var ok = problems.Count == 0;
Console.WriteLine(ok ? "Check passed." : "Check failed.");
return ok ? 0 : 1;
}
var renderer = new XyMenuRenderer();
var output = renderer.Render(root);
var linkedElements = LinkedElementExporter.Export(root);
if (!string.IsNullOrEmpty(outputDirectory))
{
Directory.CreateDirectory(outputDirectory);
}
File.WriteAllText(options.OutputPath!, output, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
File.WriteAllText(
GetItemsOutputPath(options.OutputPath!),
linkedElements,
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
Console.WriteLine($"Wrote {items.Count} source items to '{options.OutputPath}'.");
return 0;
}
catch (UsageException ex)
{
Console.Error.WriteLine(ex.Message);
Console.Error.WriteLine();
Console.Error.WriteLine(Options.UsageText);
return 2;
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
return 1;
}
}
private static string GetItemsOutputPath(string outputPath)
{
var directory = Path.GetDirectoryName(outputPath);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath);
return Path.Combine(directory ?? string.Empty, fileNameWithoutExtension + "-items.txt");
}
private static void ShowWarnings(IReadOnlyList<string> warnings)
{
foreach (var warning in warnings)
{
Console.Error.WriteLine($"Warning: {warning}");
}
}
private static void ShowProblems(IReadOnlyList<string> problems)
{
if (problems.Count == 0)
{
return;
}
Console.Error.WriteLine("Missing targets were skipped:");
foreach (var problem in problems)
{
Console.Error.WriteLine($" {problem}");
}
}
}
internal sealed record Options(
string DirectoryFavoritesPath,
string FileFavoritesPath,
string? OutputPath,
bool CheckOnly = false)
{
public const string UsageText =
"""
Usage:
XyFavMenu <dir-fav> <file-fav> <output> Generate menu files
XyFavMenu --check <dir-fav> <file-fav> Validate only, no output written
XyFavMenu --version Print version
XyFavMenu --help Show this help
""";
public static Options Parse(IReadOnlyList<string> args)
{
if (args.Count == 3 && !args[0].StartsWith("--", StringComparison.Ordinal))
{
return new Options(args[0], args[1], args[2]);
}
if (args.Count == 3 && string.Equals(args[0], "--check", StringComparison.OrdinalIgnoreCase))
{
return new Options(args[1], args[2], null, CheckOnly: true);
}
throw new UsageException("Invalid arguments.");
}
}
internal sealed class UsageException : Exception
{
public UsageException(string message) : base(message)
{
}
}
internal enum FavoriteKind
{
Directory,
File
}
internal abstract record SourceItem(FavoriteKind Kind, int LineNumber);
internal sealed record SeparatorItem(FavoriteKind Kind, int LineNumber) : SourceItem(Kind, LineNumber);
internal sealed record FavoriteItem(
FavoriteKind Kind,
int LineNumber,
string TargetPath,
IReadOnlyList<TitleElement> Titles) : SourceItem(Kind, LineNumber);
internal sealed record AdditionalMenuItem(
FavoriteKind Kind,
int LineNumber,
int Depth,
string Text,
string? Command,
string? IconPath) : SourceItem(Kind, LineNumber);
internal sealed record TitleElement(string MenuPath, string? IconPath);
internal sealed record LoadResult(IReadOnlyList<SourceItem> Items, IReadOnlyList<string> Problems);
internal sealed class FavoritesLoader
{
public LoadResult Load(string path, FavoriteKind kind)
{
if (!File.Exists(path))
{
throw new FileNotFoundException($"Input file not found: {path}", path);
}
var items = new List<SourceItem>();
var problems = new List<string>();
var lines = File.ReadAllLines(path);
var inMoreBlock = false;
int? moreBaseDepth = null;
for (var i = 0; i < lines.Length; i++)
{
var lineNumber = i + 1;
var rawLine = lines[i];
var trimmed = rawLine.Trim();
if (trimmed.Length == 0)
{
continue;
}
if (!inMoreBlock && string.Equals(trimmed, "more", StringComparison.OrdinalIgnoreCase))
{
inMoreBlock = true;
moreBaseDepth = null;
continue;
}
if (inMoreBlock)
{
var additional = ParseAdditionalMenuLine(kind, lineNumber, rawLine, ref moreBaseDepth);
if (TryValidate(path, additional, out var additionalProblem))
{
items.Add(additional);
}
else if (additionalProblem is not null)
{
problems.Add(additionalProblem);
}
continue;
}
if (trimmed == "-")
{
items.Add(new SeparatorItem(kind, lineNumber));
continue;
}
var favorite = ParseFavoriteLine(kind, lineNumber, trimmed);
if (TryValidate(path, favorite, out var favoriteProblem))
{
items.Add(favorite);
}
else if (favoriteProblem is not null)
{
problems.Add(favoriteProblem);
}
}
return new LoadResult(items, problems);
}
private static bool TryValidate(string sourcePath, SourceItem item, out string? problem)
{
problem = null;
switch (item)
{
case FavoriteItem favorite:
return TryValidateTargetPath(sourcePath, favorite.LineNumber, favorite.TargetPath, out problem);
case AdditionalMenuItem additional when TryExtractGotoPath(additional.Command, out var targetPath):
return TryValidateTargetPath(sourcePath, additional.LineNumber, targetPath, out problem);
default:
return true;
}
}
private static bool TryValidateTargetPath(string sourcePath, int lineNumber, string targetPath, out string? problem)
{
if (Directory.Exists(targetPath) || File.Exists(targetPath))
{
problem = null;
return true;
}
problem = $"{Path.GetFileName(sourcePath)}:{lineNumber}: {targetPath}";
return false;
}
private static bool TryExtractGotoPath(string? command, out string path)
{
path = string.Empty;
if (string.IsNullOrWhiteSpace(command))
{
return false;
}
var trimmed = command.Trim();
if (!(trimmed.StartsWith(":goto ", StringComparison.OrdinalIgnoreCase)
|| trimmed.StartsWith("goto ", StringComparison.OrdinalIgnoreCase)))
{
return false;
}
var firstQuote = trimmed.IndexOf('"');
if (firstQuote >= 0)
{
var secondQuote = trimmed.IndexOf('"', firstQuote + 1);
if (secondQuote > firstQuote)
{
path = trimmed[(firstQuote + 1)..secondQuote];
return path.Length > 0;
}
}
var parts = trimmed.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
{
return false;
}
path = parts[1].Trim();
return path.Length > 0;
}
private static FavoriteItem ParseFavoriteLine(FavoriteKind kind, int lineNumber, string line)
{
string? rawTitle = null;
string targetPath;
if (line[0] == '"')
{
var closingQuoteIndex = line.IndexOf('"', 1);
if (closingQuoteIndex < 0)
{
throw new FormatException($"Line {lineNumber}: missing closing quote.");
}
rawTitle = line[1..closingQuoteIndex];
targetPath = line[(closingQuoteIndex + 1)..].Trim();
if (targetPath.Length == 0)
{
targetPath = rawTitle;
rawTitle = null;
}
}
else
{
if (LooksLikeBarePath(line))
{
targetPath = line;
}
else
{
var splitIndex = FindUnquotedWhitespace(line);
if (splitIndex < 0)
{
targetPath = line;
}
else
{
rawTitle = line[..splitIndex].Trim();
targetPath = line[splitIndex..].Trim();
}
}
}
if (string.IsNullOrWhiteSpace(targetPath))
{
throw new FormatException($"Line {lineNumber}: missing target path.");
}
targetPath = ResolvePathVariables(targetPath);
targetPath = NormalizeTargetPath(kind, targetPath);
var titles = ParseTitleElements(rawTitle, targetPath);
return new FavoriteItem(kind, lineNumber, targetPath, titles);
}
private static string NormalizeTargetPath(FavoriteKind kind, string path)
{
if (kind == FavoriteKind.Directory && !path.EndsWith('\\') && !path.EndsWith('/'))
{
return path + '\\';
}
if (kind == FavoriteKind.File)
{
return path.TrimEnd('\\', '/');
}
return path;
}
private static bool LooksLikeBarePath(string line)
{
if (line.Length >= 3 && char.IsLetter(line[0]) && line[1] == ':' && (line[2] == '\\' || line[2] == '/'))
{
return true;
}
if (line.StartsWith(@"\\", StringComparison.Ordinal))
{
return true;
}
if (line.StartsWith('%') && line.LastIndexOf('%') > 0)
{
return true;
}
return false;
}
private static AdditionalMenuItem ParseAdditionalMenuLine(FavoriteKind kind, int lineNumber, string rawLine, ref int? baseDepth)
{
var indentCount = rawLine.TakeWhile(ch => ch == ' ').Count();
if (indentCount % 2 != 0)
{
throw new FormatException($"Line {lineNumber}: additional menu indentation must use multiples of 2 spaces.");
}
var absoluteDepth = indentCount / 2;
baseDepth ??= absoluteDepth;
if (absoluteDepth < baseDepth.Value)
{
throw new FormatException($"Line {lineNumber}: additional menu indentation moved above the block base level.");
}
var depth = absoluteDepth - baseDepth.Value;
var content = rawLine[indentCount..].TrimEnd();
var parts = SplitAdditionalMenuParts(content);
if (parts.Count < 2 || parts.Count > 3)
{
throw new FormatException($"Line {lineNumber}: invalid additional menu entry.");
}
var text = parts[0].Trim();
var command = parts[1].Trim();
var iconPath = parts.Count == 3 ? parts[2].Trim() : string.Empty;
if (text.Length == 0)
{
throw new FormatException($"Line {lineNumber}: additional menu text is empty.");
}
return new AdditionalMenuItem(
kind,
lineNumber,
depth,
text,
command.Length == 0 ? null : NormalizeAdditionalCommand(command),
iconPath.Length == 0 ? null : ResolvePathVariables(iconPath));
}
private static string NormalizeAdditionalCommand(string command)
{
return command
.Replace(";", ",")
.Replace("|", ",");
}
private static List<string> SplitAdditionalMenuParts(string content)
{
var parts = new List<string>();
var current = new StringBuilder();
var inQuotes = false;
foreach (var ch in content)
{
if (ch == '"')
{
inQuotes = !inQuotes;
current.Append(ch);
continue;
}
if (ch == '|' && !inQuotes && parts.Count < 2)
{
parts.Add(current.ToString());
current.Clear();
continue;
}
current.Append(ch);
}
parts.Add(current.ToString());
return parts;
}
private static IReadOnlyList<TitleElement> ParseTitleElements(string? rawTitle, string targetPath)
{
if (string.IsNullOrWhiteSpace(rawTitle))
{
return new[] { new TitleElement(targetPath, null) };
}
var elements = rawTitle
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(ParseTitleElement)
.ToList();
if (elements.Count == 0)
{
elements.Add(new TitleElement(targetPath, null));
}
return elements;
}
private static TitleElement ParseTitleElement(string rawElement)
{
var separatorIndex = rawElement.IndexOf('|');
if (separatorIndex < 0)
{
return new TitleElement(rawElement, null);
}
var menuPath = rawElement[..separatorIndex].Trim();
var iconPath = ResolvePathVariables(rawElement[(separatorIndex + 1)..].Trim());
return new TitleElement(menuPath, iconPath.Length == 0 ? null : iconPath);
}
private static string ResolvePathVariables(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return path;
}
return Environment.ExpandEnvironmentVariables(path);
}
private static int FindUnquotedWhitespace(string line)
{
for (var i = 0; i < line.Length; i++)
{
if (char.IsWhiteSpace(line[i]))
{
return i;
}
}
return -1;
}
}
internal sealed record BuildResult(MenuNode Root, IReadOnlyList<string> Warnings);
internal sealed class MenuBuilder
{
public BuildResult Build(IEnumerable<SourceItem> items, FolderIconConfig folderIconConfig)
{
var warnings = new List<string>();
var root = new MenuNode(string.Empty, null);
var additionalStack = new Stack<MenuNode>();
var pathEntries = new Dictionary<string, PathEntry>(StringComparer.OrdinalIgnoreCase);
additionalStack.Push(root);
foreach (var item in items)
{
switch (item)
{
case SeparatorItem:
root.Children.Add(new SeparatorNode());
additionalStack.Clear();
additionalStack.Push(root);
break;
case FavoriteItem favorite:
AddPathEntry(pathEntries, favorite.TargetPath, $":goto {Quote(favorite.TargetPath)}", favorite.Titles.Select(title => title.IconPath).FirstOrDefault(icon => !string.IsNullOrWhiteSpace(icon)));
foreach (var title in favorite.Titles)
{
AddFavorite(root, favorite, title, warnings);
}
additionalStack.Clear();
additionalStack.Push(root);
break;
case AdditionalMenuItem additional:
if (additional.Command is not null && TryExtractGotoPath(additional.Command, out var additionalPath))
{
AddPathEntry(pathEntries, additionalPath, additional.Command, additional.IconPath);
}
AddAdditional(additionalStack, additional);
break;
}
}
CollapseSingleChildMenusRecursive(root, isRoot: true);
SortChildrenRecursive(root);
var pathChildren = BuildPathChildren(pathEntries);
if (pathChildren.Count > 0)
{
root.Children.RemoveAll(child => child is not MenuNode);
root.Children.Add(new SeparatorNode());
root.Children.AddRange(pathChildren);
}
ApplyMenuIconsRecursive(root, folderIconConfig);
return new BuildResult(root, warnings);
}
private static void AddFavorite(MenuNode root, FavoriteItem favorite, TitleElement title, List<string> warnings)
{
var segments = title.MenuPath
.Split('>', StringSplitOptions.TrimEntries)
.Where(segment => segment.Length > 0)
.ToArray();
if (segments.Length == 0)
{
segments = new[] { favorite.TargetPath };
}
var current = root;
for (var i = 0; i < segments.Length - 1; i++)
{
current = current.GetOrAddMenu(segments[i]);
}
var label = segments[^1];
if (current.Children.OfType<CommandNode>().Any(c => string.Equals(c.Text, label, StringComparison.OrdinalIgnoreCase)))
{
var menuPath = string.Join(" > ", segments).Replace("&", "");
warnings.Add($"Duplicate menu entry: \"{menuPath}\"");
}
current.Children.Add(new CommandNode(label, title.IconPath, $":goto {Quote(favorite.TargetPath)}"));
}
private static void AddAdditional(Stack<MenuNode> stack, AdditionalMenuItem item)
{
while (stack.Count > item.Depth + 1)
{
stack.Pop();
}
if (stack.Count != item.Depth + 1)
{
throw new FormatException($"Line {item.LineNumber}: invalid nesting in additional menu block.");
}
var parent = stack.Peek();
var segments = SplitMenuPath(item.Text);
if (segments.Length == 0)
{
throw new FormatException($"Line {item.LineNumber}: additional menu text is empty.");
}
if (item.Command is null)
{
for (var i = 0; i < segments.Length - 1; i++)
{
parent = parent.GetOrAddMenu(segments[i]);
}
var menu = parent.GetOrAddMenu(segments[^1], item.IconPath);
stack.Push(menu);
return;
}
for (var i = 0; i < segments.Length - 1; i++)
{
parent = parent.GetOrAddMenu(segments[i]);
}
parent.Children.Add(new CommandNode(segments[^1], item.IconPath, item.Command));
}
private static void CollapseSingleChildMenusRecursive(MenuNode menu, bool isRoot)
{
for (var i = 0; i < menu.Children.Count; i++)
{
if (menu.Children[i] is not MenuNode childMenu)
{
continue;
}
CollapseSingleChildMenusRecursive(childMenu, isRoot: false);
menu.Children[i] = CollapseSingleChildMenu(childMenu, parentIsRoot: isRoot);
}
}
private static MenuChild CollapseSingleChildMenu(MenuNode menu, bool parentIsRoot)
{
if (parentIsRoot)
{
return menu;
}
if (menu.Children.Count != 1)
{
return menu;
}
return menu.Children[0] switch
{
CommandNode command => new CommandNode($"{menu.Text} > {command.Text}", command.IconPath, command.Command),
MenuNode childMenu => CreateMergedMenu(menu, childMenu),
_ => menu
};
}
private static MenuNode CreateMergedMenu(MenuNode parent, MenuNode child)
{
var merged = new MenuNode($"{parent.Text} > {child.Text}", child.IconPath ?? parent.IconPath);
foreach (var grandChild in child.Children)
{
merged.Children.Add(grandChild);
}
return merged;
}
private static void SortChildrenRecursive(MenuNode menu)
{
foreach (var childMenu in menu.Children.OfType<MenuNode>())
{
SortChildrenRecursive(childMenu);
}
var orderedChildren = menu.Children
.OrderBy(GetSortRank)
.ThenBy(GetSortText, StringComparer.OrdinalIgnoreCase)
.ToList();
menu.Children.Clear();
menu.Children.AddRange(orderedChildren);
}
private static void AddPathEntry(Dictionary<string, PathEntry> entries, string path, string command, string? iconPath)
{
if (!entries.ContainsKey(path))
{
entries.Add(path, new PathEntry(path, command, iconPath));
}
}
private static List<MenuChild> BuildPathChildren(Dictionary<string, PathEntry> entries)
{
if (entries.Count == 0)
{
return [];
}
var pathRoot = new PathNode(string.Empty);
foreach (var entry in entries.Values)
{
AddPathEntry(pathRoot, entry);
}
return pathRoot.Children.Values
.Select(BuildPathChild)
.OrderBy(GetSortText, StringComparer.OrdinalIgnoreCase)
.ThenBy(GetSortRank)
.ToList();
}
private static bool TryExtractGotoPath(string command, out string path)
{
path = string.Empty;
var trimmed = command.Trim();
if (!(trimmed.StartsWith(":goto ", StringComparison.OrdinalIgnoreCase)
|| trimmed.StartsWith("goto ", StringComparison.OrdinalIgnoreCase)))
{
return false;
}
var firstQuote = trimmed.IndexOf('"');
var lastQuote = trimmed.LastIndexOf('"');
if (firstQuote < 0 || lastQuote <= firstQuote)
{
return false;
}
path = trimmed[(firstQuote + 1)..lastQuote];
return path.Length > 0;
}
private static void AddPathEntry(PathNode root, PathEntry entry)
{
var segments = SplitFilesystemPath(entry.Path);
if (segments.Length == 0)
{
return;
}
var current = root;
foreach (var segment in segments)
{
current = current.GetOrAddChild(segment);
}
current.Command = entry.Command;
current.IconPath = entry.IconPath;
}
private static string[] SplitFilesystemPath(string path)
{
if (path.StartsWith(@"\\", StringComparison.Ordinal))
{
var trimmed = path.TrimEnd('\\');
var parts = trimmed.Split('\\', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
{
return new[] { path };
}
var segments = new List<string> { $@"\\{parts[0]}\{parts[1]}" };
segments.AddRange(parts.Skip(2));
return segments.ToArray();
}
if (path.Length >= 3 && char.IsLetter(path[0]) && path[1] == ':' && (path[2] == '\\' || path[2] == '/'))
{
var trimmed = path.TrimEnd('\\', '/');
var segments = new List<string> { path[..3] };
if (trimmed.Length > 3)
{
segments.AddRange(trimmed[3..].Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries));
}
return segments.ToArray();
}
return new[] { path };
}
private static void ApplyMenuIconsRecursive(MenuNode menu, FolderIconConfig folderIconConfig)
{
foreach (var childMenu in menu.Children.OfType<MenuNode>())
{
ApplyMenuIconsRecursive(childMenu, folderIconConfig);
}
if (string.IsNullOrWhiteSpace(menu.Text) || !string.IsNullOrWhiteSpace(menu.IconPath))
{
return;
}
menu.IconPath = DetermineMenuIcon(menu, folderIconConfig);
}
private static string? DetermineMenuIcon(MenuNode menu, FolderIconConfig folderIconConfig)
{
var overrideIcon = folderIconConfig.FindOverride(menu.Text);
if (!string.IsNullOrWhiteSpace(overrideIcon))
{
return overrideIcon;
}
var directSelfIcon = menu.Children
.OfType<CommandNode>()
.FirstOrDefault(child => string.Equals(NormalizeLookupKey(child.Text), NormalizeLookupKey(menu.Text), StringComparison.OrdinalIgnoreCase))
?.IconPath;
if (!string.IsNullOrWhiteSpace(directSelfIcon))
{
return directSelfIcon;
}
var childIcons = menu.Children
.Select(child => child switch
{
MenuNode childMenu => childMenu.IconPath,
CommandNode command => command.IconPath,
_ => null
})
.Where(icon => !string.IsNullOrWhiteSpace(icon))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
if (childIcons.Count == 1)
{
return childIcons[0];
}
return folderIconConfig.FallbackIconPath;
}
private static MenuChild BuildPathChild(PathNode node)
{
var label = node.Segment;
var current = node;
while (current.Command is null && current.Children.Count == 1)
{
current = current.Children.Values.Single();
label = CombinePathLabel(label, current.Segment);
}
if (current.Command is not null && current.Children.Count == 0)
{
return new CommandNode(label, current.IconPath, current.Command);
}
var menu = new MenuNode(label, current.IconPath);
if (current.Command is not null)
{
menu.Children.Add(new CommandNode(label, current.IconPath, current.Command));
}
foreach (var child in current.Children.Values
.Select(BuildPathChild)
.OrderBy(GetSortText, StringComparer.OrdinalIgnoreCase)
.ThenBy(GetSortRank))
{
menu.Children.Add(child);
}
return menu;
}
private static string CombinePathLabel(string left, string right)
{
if (left.EndsWith('\\') || left.EndsWith('/'))
{
return left + right;
}
return left + @"\" + right;
}
private static int GetSortRank(MenuChild child) => child switch
{
MenuNode => 0,
CommandNode command when !LooksLikePathText(command.Text) => 1,
CommandNode => 2,
SeparatorNode => 3,
_ => 4
};
private static string GetSortText(MenuChild child) => child switch
{
MenuNode menu => NormalizeSortText(menu.Text),
CommandNode command => NormalizeSortText(command.Text),
_ => string.Empty
};
private static string NormalizeSortText(string text)
{
var normalized = text
.Replace("&", string.Empty)
.Replace("Ä", "Ae", StringComparison.Ordinal)
.Replace("Ö", "Oe", StringComparison.Ordinal)
.Replace("Ü", "Ue", StringComparison.Ordinal)
.Replace("ä", "ae", StringComparison.Ordinal)
.Replace("ö", "oe", StringComparison.Ordinal)
.Replace("ü", "ue", StringComparison.Ordinal)
.Replace("ß", "ss", StringComparison.Ordinal);
return new string(normalized.Where(char.IsLetterOrDigit).ToArray());
}
private static string NormalizeLookupKey(string text)
{
return NormalizeSortText(text)
.Replace(">", @"\", StringComparison.Ordinal)
.Replace("/", @"\", StringComparison.Ordinal);
}
private static bool LooksLikePathText(string text)
{
if (text.Length >= 3 && char.IsLetter(text[0]) && text[1] == ':' && (text[2] == '\\' || text[2] == '/'))
{
return true;
}
if (text.StartsWith(@"\\", StringComparison.Ordinal))
{
return true;
}
if (text.StartsWith('%') && text.LastIndexOf('%') > 0)
{
return true;
}
return false;
}
private static string[] SplitMenuPath(string menuPath)
{
return menuPath
.Split('>' , StringSplitOptions.TrimEntries)
.Where(segment => segment.Length > 0)
.ToArray();
}
private static string Quote(string value) => $"\"{value}\"";
private sealed class PathNode(string segment)
{
public string Segment { get; } = segment;
public string? Command { get; set; }
public string? IconPath { get; set; }