-
Notifications
You must be signed in to change notification settings - Fork 1
/
20220412 resource parser.linq
1609 lines (1467 loc) · 61.4 KB
/
20220412 resource parser.linq
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
<Query Kind="Program">
<NuGetReference>Microsoft.CodeAnalysis.CSharp</NuGetReference>
<NuGetReference>TextCopy</NuGetReference>
<Namespace>Microsoft.CodeAnalysis</Namespace>
<Namespace>Microsoft.CodeAnalysis.CSharp</Namespace>
<Namespace>Microsoft.CodeAnalysis.CSharp.Syntax</Namespace>
<Namespace>static UserQuery.Global</Namespace>
<Namespace>System.Dynamic</Namespace>
<Namespace>System.Globalization</Namespace>
<Namespace>TextCopy</Namespace>
</Query>
//#define THROW_ON_NOTIMPLEMENTED_OBJECT
#define ENABLE_GENERIC_VALUE_OBJECT_PARSING
#define REPLACE_UNO_PLATFORM_XMLNS
#define ALLOW_DUPLICATED_KEYS // temp workaround for platform specifics
#define ALLOW_DUPLICATED_KEYS_WITHOUT_WARNING
public class Script
{
public static void Main()
{
ResourceDictionary.ThemeMapping = new Dictionary<string, string>
{
["Light"] = "Light",
["Dark"] = "Default,Dark" // Default=Dark is a weird concept introduced by lightweight styling...
};
Specialized.ListThemes();
//Specialized.ListExposedThemeV2Styles();
//Specialized.ListExposedCupertinoStyles();
//Specialized.ListExposedToolkitV2Styles();
//Specialized.DiffThemeToolkitV2InnerResources();
//Specialized.CheckLightWeightResourceParity(@"D:\code\uno\platform\Uno.Themes\src/library/Uno.Material/Styles/Controls/v2/NavigationView.xaml");
/*var additionalResources = new[]
{
@"D:\code\uno\framework\Uno\src\Uno.UI\UI\Xaml\Style\Generic\SystemResources.xaml",
@"D:\code\uno\framework\Uno\src\Uno.UI.FluentTheme.v2\themeresources_v2.xaml",
@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\Common\TextBoxVariables.xaml",
@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\Common\Fonts.xaml",
@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\Typography.xaml",
@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\SharedColors.xaml",
@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\SharedColorPalette.xaml",
@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\_Resources.xaml",
@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\TextBlock.xaml"
}.Aggregate(new ResourceDictionary(), (acc, file) => acc.Merge((ResourceDictionary)ScuffedXamlParser.Load(file)));*/
//Specialized.CheckLightWeightResourceParity(@"D:\code\uno\platform\Uno.Themes\src/library/Uno.Material/Styles/Controls/v2/ToggleSwitch.xaml");
//Specialized.ExtractLightWeightResources(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\Button.xaml", additionalResources);
//Specialized.ExtractLightWeightResources(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\Slider.xaml", additionalResources);
//string.Join("\n\n", Directory.GetFiles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\", "*.xaml")
// .Prepend(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\Typography.xaml")
// .Select(x => string.Join("\n", $"# {Path.GetFileName(x)}", Specialized.ExtractLightWeightResources(x, additionalResources)))
//).OnDemand("Click to expand").Dump("All in one");
//foreach (var control in Directory.GetFiles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\", "*.xaml"))
// Specialized.ExtractLightWeightResources(control, additionalResources);
//ListColors(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v1\ColorPalette.xaml");
//ListColors(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\SharedColorPalette.xaml");
//ListColors(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\SharedColors.xaml");
////ListColors(@"D:\code\uno\platform\Uno.Todo\src\ToDo.UI\Styles\ColorPaletteOverride.xaml");
//ListColors(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v1\MaterialColors.xaml");
/*SpecializedListColorTheme(
@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\SharedColorPalette.xaml",
@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\SharedColors.xaml",
generateBrushesBasedOnColorAndOpacity: false);*/
//foreach (var control in Directory.GetFiles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\", "*.xaml").Where(x => !Path.GetFileName(x).Contains('_')))
// ListStyles(control.Dump());
//ListStyles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v1\Button.xaml");
//ListStyles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\FloatingActionButton.xaml");
//ListStyles(@"D:\code\uno\platform\Uno.UI.Toolkit\src\library\Uno.Toolkit.Material\Styles\Controls\v2\ChipGroup.xaml");
//CompareStyles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v1\TextBlock.xaml", x => x.BasedOn != null);
//CompareStyles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\TextBlock.xaml", x => true || x.BasedOn != null, x => Regex.Replace(x, @"^{(Static|Theme)Resource (?<key>\w+)}$", "(*${key})"));
//CompareStyles(@"D:\code\uno\platform\Uno.Toolkit\src\library\Uno.Toolkit.Material\Styles\Controls\v2\Chip.xaml", x => x.BasedOn != null, SimplifyReference);
//CompareStyles(@"D:\code\uno\platform\Uno.Toolkit\src\library\Uno.Toolkit.Material\Styles\Controls\v2\ChipGroup.xaml", x => x.BasedOn != null, SimplifyReference);
/*var typography = (ResourceDictionary)ScuffedXamlParser.Load(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\Typography.xaml").Dump("Typography", 0);
CompareStyles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\TextBlock.xaml", x => true || x.BasedOn != null);
CompareStyles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\TextBlock.xaml",
x => true || x.BasedOn != null,
resolveResource: x => ResolveResource(typography, x, 3)
);*/
Match TryMatch(string input, string pattern) => Regex.Match(input, pattern) is { Success: true } m ? m : null;
string SimplifyReference(string value) => TryMatch(value, @"^{StaticResource (?<key>\w+)}$")?.Result("*${key}") ?? value;
string ResolveResource(ResourceDictionary resources, string value, int maxDepth = 1)
{
for (int depth = 0; depth < maxDepth && value != null && TryMatch(value, @"^{StaticResource (?<key>\w+)}$") is { Success: true } match; depth++)
{
value = match.Groups["key"].Value.Apply(y => (resources[y] as StaticResource)?.Value?.ToString());
}
return value;
}
}
private static void ListColors(string path)
{
Util.Metatext($"==================== {path}").Dump();
var document = XDocument.Load(path);
var root = (ResourceDictionary)ScuffedXamlParser.Parse(document.Root);
object FormatColor(Color x) => Util.HorizontalRun(true, x.ToColoredBlock(), x.ToRgbText());
root.Values
.Where(x => x.IsReferenceFor<Color>())
.Select(x => x switch
{
StaticResource sr => new { x.Key, Value = FormatColor((Color)sr.Value) },
ThemeResource tr => new { x.Key, LightValue = FormatColor((Color)tr.LightValue), DarkValue = FormatColor((Color)tr.DarkValue) },
_ => (object)null,
})
.Dump("Colors", 0);
root.Values
.Where(x => x.IsReferenceFor<Double>())
.Dump("Doubles", 0);
var brushes = root.Values
.Where(x => x.IsStaticResourceFor<SolidColorBrush>())
.Select(x => new { x.Key, Value = (x as StaticResource).Value as SolidColorBrush })
.Select(x => new
{
x.Key,
//Color = IKeyedResource.GetKeyFromMarkup(x.Value.GetDP("Color")),
//Opacity = IKeyedResource.GetKeyFromMarkup(x.Value.GetDP("Opacity")),
Color = x.Value.GetDP("Color"),
Opacity = x.Value.GetDP("Opacity"),
})
.OrderBy(x => x.Color)
.ThenBy(x => x.Opacity)
.Dump("Brushes", 0);
brushes
.GroupBy(x => x.Color, (g, k) => Util.OnDemand($"{g}[{k.Count()}]", () => k))
.Dump("Brushes by Color", 0);
}
private static void SpecializedListColorTheme(string paletteFile, string brushFile, bool generateBrushesBasedOnColorAndOpacity = false)
{
#if false
var paletteRD = (ResourceDictionary)ScuffedXamlParser.Parse(XDocument.Load(paletteFile).Root);
var brushRD = (ResourceDictionary)ScuffedXamlParser.Parse(XDocument.Load(brushFile).Root);
var colors = paletteRD.Values
.Where(x => x.IsReferenceFor<Color>())
.Select(x => x switch
{
StaticResource sr => new { x.Key, Value = new[] { (Color)sr.Value } },
ThemeResource tr => new { x.Key, Value = new[] { (Color)tr.LightValue, (Color)tr.DarkValue } },
_ => throw new Exception(),
})
.Dump("Colors", 0);
var opacities = paletteRD.Values
.Where(x => x.IsReferenceFor<Double>())
.Dump("Opacities", 0);
var brushes = brushRD.Values
.Where(x => x.IsReferenceFor<SolidColorBrush>())
//.Select(x => new { x.Key, Value = (x as StaticResource).Value as SolidColorBrush })
.Select(x => new { x.Key, Value = (x as ThemeResource).LightValue as SolidColorBrush }) // both light and default(dark) are just duplicated for lightweight styling
.Select(x => new
{
x.Key,
//Color = IKeyedResource.GetKeyFromMarkup(x.Value.GetDP("Color")),
//Opacity = IKeyedResource.GetKeyFromMarkup(x.Value.GetDP("Opacity")),
//ColorValue = paletteRD.TryGetValue(IKeyedResource.GetKeyFromMarkup(x.Value.GetDP("Color")), out var color) ? color : default,
//OpacityValue = paletteRD.TryGetValue(IKeyedResource.GetKeyFromMarkup(x.Value.GetDP("Opacity")), out var opacity) ? opacity : default,
})
.OrderBy(x => x.Color)
.ThenBy(x => x.Opacity)
.Dump("Brushes");
colors.Select(color => new
{
BaseColor = color.Key,
Brushes = from opacity in opacities.Prepend(null)
let key = color.Key.Key[0..^5] + opacity?.Key.Key[0..^7] + "Brush"
select new
{
Key = key,
Opacity = (opacity as StaticResource)?.Value as double? ?? 1,
Defined = Util.HighlightIf(brushes.Any(x => x.Key.Key == key), x => !x),
Copy = Util.HorizontalRun(true,
Clickable.CopyText("Key", key),
Clickable.CopyText("Ref", $"{{StaticResource {key}}}"),
Clickable.CopyText("Fwd", $"<StaticResource x:Key=\"\" ResourceKey=\"{key}\" />")
),
}
}).Dump("Quick Lookup", 0);
if (generateBrushesBasedOnColorAndOpacity)
{
var crossProducts = (
from color in colors
from opacity in opacities.Prepend(null)
let sanity0 = color.Key.Key.EndsWith("Color") ? true : throw new NotImplementedException()
let sanity1 = opacity?.Key.Key.EndsWith("Opacity") != false ? true : throw new NotImplementedException()
let key = color.Key.Key[0..^5] + opacity?.Key.Key[0..^7] + "Brush"
select new
{
CK = color.Key,
OK = opacity?.Key,
Key = key,
Defined = brushes.Any(x => x.Key.Key == key)
}
).ToArray();
crossProducts.Dump("cross-products: Colors x Doubles", 0);
crossProducts.GroupBy(x => x.CK).SelectMany(g => g.Select(x =>
$@"<SolidColorBrush x:Key='{x.Key}'
Color='{{ThemeResource {x.CK.Key}}}'
{(x.OK.Apply(y => $"Opacity='{{StaticResource {y.Key}}}'"))}
/>"
.RegexReplace(@"\s+", " ")
.Replace('\'', '"')
)
.Prepend($"<!--#region {g.Key.Key} -->")
.Append($"<!--#endregion {g.Key.Key}-->")
)
.JoinBy("\n").Dump("all brushes");
brushes.Select(x => x.Key.Key).Except(crossProducts.Select(x => x.Key)).Dump("missing brushes", 0);
}
#endif
}
private static void ListStyles(string path)
{
var document = XDocument.Load(path);
var root = (ResourceDictionary)ScuffedXamlParser.Parse(document.Root);
root.Values
.Select(x => (x as StaticResource)?.Value)
.OfType<Style>()
.Dump(path, 1);
}
private static void CompareStyles(string path, Func<Style, bool> predicate, Func<string, string> resolveResource = null)
{
// ^resolveResource: return null if unresolvable
var document = XDocument.Load(path);
var root = (ResourceDictionary)ScuffedXamlParser.Parse(document.Root);
var styles = root.Values
.Select(x => (x as StaticResource)?.Value)
.OfType<Style>()
.Where(predicate);
PivotHelper.Pivot(styles,
x => x.Key,
x => x.Setters.ToDictionary(
x => x.Property,
x => (object)x.Value?.Apply(resolveResource ?? (_ => null)) ?? x.Value
)
).Dump(path);
}
private static partial class Specialized
{
public static void ListExposedThemeV2Styles()
{
var resources = new ResourceDictionary();
var controls = Directory.GetFiles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\", "*.xaml")
.Where(x => !Path.GetFileName(x).Contains('_'));
foreach (var control in controls)
{
//Util.Metatext($"Processing: {control}").Dump();
var filename = Path.GetFileNameWithoutExtension(control);
var document = XDocument.Load(control);
var root = (ResourceDictionary)ScuffedXamlParser.Parse(document.Root);
var filter = (filename switch
{
"ContentDialog" => "Button",
"DatePicker" => "Button",
"NavigationView" => "Button,SplitView,TextBlock,ContentControl",
"PasswordBox" => "Button",
"PipsPager.Base" => "Button",
"Slider" => "Thumb",
"TextBox" => "Button",
_ => "",
});
var filtered = root.Values
.Where(x =>
x is StaticResource { Value: Style { Key: string key, TargetType: string type } } &&
!filter.Split(',').Contains(type)
);
//filtered
// .OfStaticResourceType<Style>()
// .Select(x => new { x.Key, x.TargetType })
// .Dump($"{Path.GetFileNameWithoutExtension(control)}: {filtered.OfStaticResourceType<Style>().Count()} styles", 0);
resources.AddRange(filtered);
}
var _resources = (ResourceDictionary)ScuffedXamlParser.Load(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Controls\v2\_Resources.xaml");
var implicitStyles = _resources.Values.OfStaticResourceOf<Style>()
.Select(x => x.BasedOn)
#if true // Themes 3.0
.Select(x => ((resources[x] as StaticResource)?.Value as Style)?.BasedOn)
#endif
.ToArray()
.Dump("ImplicitStyles", 0);
var aliasMap = _resources.Values.Where(x => x.IsStaticResourceFor<StaticResourceRef>())
.Select(x => new { x.Key, Key2 = ((x as StaticResource)?.Value as StaticResourceRef)?.Key })
.ToDictionary(x => x.Key2, x => x.Key)
.Dump("Aliases", 0);
resources.Values.OfStaticResourceOf<Style>()
.Where(x => x.Key != null)
.Where(x => x.Key is string k && !@"
MaterialDefault, MaterialBase,
BaseStyle, BaseMaterial, BaseTextBlockStyle,
MUX_
".Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.SelectMany(x => x.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
.Any(k.Contains)
)
.Select(x => new
{
x.Key,
AliasedKey = aliasMap.TryGetValue(x.Key, out var key) ? key : "",
x.TargetType,
ImplicitStyle = implicitStyles.Contains(x.Key) ? "true" : "",
})
.Dump("=== Style Exports ===", 0)
.ToCopyableMarkdownTable()
.Dump();
}
/*not updated since uno5*/
public static void ListExposedCupertinoStyles()
{
var styles = new ResourceDictionary();
var controls = Directory.GetFiles(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Cupertino\Styles\Controls\", "*.xaml")
.Where(x => !Path.GetFileName(x).Contains('_'));
foreach (var control in controls)
{
//Util.Metatext($"Processing: {control}").Dump();
var document = XDocument.Load(control);
var root = (ResourceDictionary)ScuffedXamlParser.Parse(document.Root);
styles.Merge(root);
}
//var styleInfos = ParseGetStyleInfos(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\MaterialResourcesV2.cs");
styles.Values.OfStaticResourceOf<Style>()
.OrderBy(x => x.TargetType)
//.Join(styleInfos, style => style.Key, info => info.ResourceKey, (style, info) => new { Style = style, Info = info })
.Where(x => x.Key.StartsWith("Cupertino"))
.Select(x => new
{
x.TargetType,
Key = x.Key
})
//.OrderBy(x => x.TargetType)
//.GroupBy(x => x.TargetType, (k, g) => $"`{k}`|" + string.Join("<br/>", g.Select(x => x.Key)))
.Dump("CupertinoStyles", 0);
}
public static void ListExposedToolkitV2Styles()
{
var resources = new ResourceDictionary();
var controls = Directory.GetFiles(@"D:\code\uno\platform\Uno.Toolkit\src\library\Uno.Toolkit.Material\Styles\Controls\v2\", "*.xaml")
.Where(x => !Path.GetFileName(x).Contains('_'));
foreach (var control in controls)
{
//Util.Metatext($"Processing: {control}").Dump();
var filename = Path.GetFileNameWithoutExtension(control);
var document = XDocument.Load(control);
var root = (ResourceDictionary)ScuffedXamlParser.Parse(document.Root);
var filter = (filename switch
{
"Chip" => "Button",
"NavigationBar" => "utu:NavigationBarPresenter",
"TabBar" => "utu:TabBarSelectionIndicatorPresenter",
_ => "",
});
var filtered = root.Values
.Where(x =>
x is StaticResource { Value: Style { Key: string key, TargetType: string type } }
? !filter.Split(',').Contains(type)
: true
);
filtered
.OfStaticResourceOf<Style>()
.Select(x => new { x.Key, x.TargetType })
.Dump($"{Path.GetFileNameWithoutExtension(control)}: {filtered.OfStaticResourceOf<Style>().Count()} styles", 0);
resources.AddRange(filtered);
}
var _common = (ResourceDictionary)ScuffedXamlParser.Load(@"D:\code\uno\platform\Uno.Toolkit\src\library\Uno.Toolkit.Material\Styles\Controls\v2\_Common.xaml");
var implicitStyles = _common.Values.OfStaticResourceOf<Style>()
.Select(x => x.BasedOn)
#if true // Toolkit 4.2
//.Select(x => ((resources[x] as StaticResource)?.Value as Style)?.BasedOn)
#endif
.ToArray()
.Dump("ImplicitStyles", 0);
var aliasMap = _common.Values.Where(x => x.IsStaticResourceFor<StaticResourceRef>())
.Select(x => new { x.Key, Key2 = ((x as StaticResource)?.Value as StaticResourceRef)?.Key })
.ToDictionary(x => x.Key2, x => x.Key)
.Dump("Aliases", 0);
resources.Values.OfStaticResourceOf<Style>()
.Where(x => x.Key != null)
.Where(x => x.Key is string k && !@"
MaterialDefault, MaterialBase,
BaseStyle, BaseMaterial, BaseTextBlockStyle,
".Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.SelectMany(x => x.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
.Any(k.Contains)
)
.Select(x => new
{
x.Key,
AliasedKey = aliasMap.TryGetValue(x.Key, out var key) ? key : "",
x.TargetType,
ImplicitStyle = implicitStyles.Contains(x.Key) ? "true" : "",
})
.Dump("=== Style Exports ===", 0)
.ToCopyableMarkdownTable()
.Dump();
}
[Obsolete]
private static IEnumerable<(string ResourceKey, string SharedKey, bool IsDefaultStyle)> GetThemeV2StyleInfos()
{
const string StylePrefix = "M3Material";
var result = new List<(string ResourceKey, string SharedKey, bool IsDefaultStyle)>();
Add("M3MaterialCheckBoxStyle", isImplicit: true);
Add("M3MaterialAppBarButtonStyle", isImplicit: true);
Add("M3MaterialCommandBarStyle", isImplicit: true);
Add("M3MaterialRadioButtonStyle", isImplicit: true);
Add("M3MaterialDisplayLarge");
Add("M3MaterialDisplayMedium");
Add("M3MaterialDisplaySmall");
Add("M3MaterialHeadlineLarge");
Add("M3MaterialHeadlineMedium");
Add("M3MaterialHeadlineSmall");
Add("M3MaterialTitleLarge");
Add("M3MaterialTitleMedium");
Add("M3MaterialTitleSmall");
Add("M3MaterialLabelLarge");
Add("M3MaterialLabelMedium");
Add("M3MaterialLabelSmall");
Add("M3MaterialBodyLarge");
Add("M3MaterialBodyMedium", isImplicit: true);
Add("M3MaterialBodySmall");
Add("M3MaterialOutlinedTextBoxStyle");
Add("M3MaterialFilledTextBoxStyle", isImplicit: true);
Add("M3MaterialOutlinedPasswordBoxStyle");
Add("M3MaterialFilledPasswordBoxStyle", isImplicit: true);
Add("M3MaterialElevatedButtonStyle");
Add("M3MaterialFilledButtonStyle", isImplicit: true);
Add("M3MaterialFilledTonalButtonStyle");
Add("M3MaterialOutlinedButtonStyle");
Add("M3MaterialTextButtonStyle");
Add("M3MaterialIconButtonStyle");
Add("M3MaterialCalendarViewStyle", isImplicit: true);
Add("M3MaterialCalendarDatePickerStyle", isImplicit: true);
Add("M3MaterialFlyoutPresenterStyle", isImplicit: true);
Add("M3MaterialMenuFlyoutPresenterStyle", isImplicit: true);
Add("M3MaterialNavigationViewStyle", isImplicit: true);
Add("M3MaterialNavigationViewItemStyle", isImplicit: true);
Add("M3MaterialListViewStyle", isImplicit: true);
Add("M3MaterialListViewItemStyle", isImplicit: true);
Add("M3MaterialTextToggleButtonStyle", isImplicit: true);
Add("M3MaterialIconToggleButtonStyle");
Add("M3MaterialDatePickerStyle", isImplicit: true);
return result;
void Add(string key, string alias = null, bool isImplicit = false) =>
result.Add((key, alias ?? key.Substring(StylePrefix.Length), isImplicit));
}
[Obsolete]
private static IEnumerable<(string ResourceKey, string SharedKey, bool IsDefaultStyle)> GetToolkitV2StyleInfos()
{
const string StylePrefix = "M3Material";
var result = new List<(string ResourceKey, string SharedKey, bool IsDefaultStyle)>();
Add("M3MaterialDividerStyle", isImplicit: true);
Add("M3MaterialNavigationBarStyle", isImplicit: true);
Add("M3MaterialModalNavigationBarStyle");
Add("M3MaterialMainCommandStyle", isImplicit: true);
Add("M3MaterialModalMainCommandStyle");
Add("M3MaterialTopTabBarStyle");
Add("M3MaterialColoredTopTabBarStyle");
Add("M3MaterialElevatedSuggestionChipStyle");
Add("M3MaterialSuggestionChipStyle");
Add("M3MaterialInputChipStyle");
Add("M3MaterialElevatedFilterChipStyle");
Add("M3MaterialFilterChipStyle");
Add("M3MaterialElevatedAssistChipStyle");
Add("M3MaterialAssistChipStyle");
Add("M3MaterialElevatedSuggestionChipGroupStyle");
Add("M3MaterialSuggestionChipGroupStyle");
Add("M3MaterialInputChipGroupStyle");
Add("M3MaterialElevatedFilterChipGroupStyle");
Add("M3MaterialFilterChipGroupStyle");
Add("M3MaterialElevatedAssistChipGroupStyle");
Add("M3MaterialAssistChipGroupStyle");
return result;
void Add(string key, string? alias = null, bool isImplicit = false) =>
result.Add((key, alias ?? key.Substring(StylePrefix.Length), isImplicit));
}
[Obsolete]
private static IEnumerable<(string ResourceKey, string SharedKey, bool IsDefaultStyle)> ParseGetStyleInfos(string path)
{
var source = File.ReadAllText(path);
var tree = CSharpSyntaxTree.ParseText(source)/*.DumpSyntaxTree()*/;
var getStyleInfos = tree.GetRoot()
.DescendantNodes().OfType<MethodDeclarationSyntax>()
.FirstOrDefault(x => x.Identifier.Text == "GetStyleInfos");
return getStyleInfos.Body
//.DumpSyntaxNode()
.ChildNodes().OfType<ExpressionStatementSyntax>()
.Select(x => x.Expression)
.OfType<InvocationExpressionSyntax>()
.Where(x => (x.Expression as IdentifierNameSyntax)?.Identifier.Text == "Add")
.Select(x => new
{
Key = x.ArgumentList.Arguments[0].Expression.Cast<LiteralExpressionSyntax>().Token.ValueText,
Implicit = x.ArgumentList.Arguments
.FirstOrDefault(y => y.NameColon?.Name?.Identifier.ValueText == "isImplicit")
?.Expression.Cast<LiteralExpressionSyntax>().Token.Value
as bool? ?? false
})
.Select(x => (x.Key, x.Key.RegexReplace("^M3Material", ""), x.Implicit));
}
}
private static partial class Specialized
{
public static void CheckLightWeightResourceParity(string path)
{
var document = XDocument.Load(path);
var root = (ResourceDictionary)ScuffedXamlParser.Parse(document.Root);
var themeResources = root.Values.OfType<ThemeResource>()
.Select(x => new
{
x.Key,
x.LightValue,
x.DarkValue,
Parity = x.AreThemeDefinitionEqual(),
})
.ToArray()
.Dump("ThemeResources", 0);
var staticResources = root.Values.OfType<StaticResource>()
.ToArray()
.Dump("StaticResources", 0);
Regex.Matches(document.ToString(), @"\{StaticResource (\w+)\}").Cast<Match>()
.Select(x => x.Groups[1].Value)
.Where(x => themeResources.Select(x => x.Key).Contains(x))
.GroupBy(x => x, (k, g) => $"{k} x{g.Count()}")
.Dump();
if (themeResources.Count(x => !x.Parity) is { } count && count != 0)
Util.WithStyle($"{count} of the {themeResources.Length} theme-resources are in disparity", $"color: red").Dump();
else
Util.WithStyle($"All {themeResources.Length} theme-resources are in parity", $"color: green").Dump();
}
public static string ExtractLightWeightResources(string inspectFile, ResourceDictionary additionalResources)
{
var root = (ResourceDictionary)ScuffedXamlParser.Load(inspectFile).Dump(inspectFile, 0);
var resources = new ResourceDictionary(additionalResources).Merge(root);
var table = root.Values
.Where(x => !x.IsStaticResourceFor<Style>())
.Where(x => x is not StaticResource) // only theme resource should be included for whats considered LightWeight
.Select(x =>
x is StaticResource sr ? new { x.Key, RefValue = GetResource(sr.Value) } :
x is ThemeResource tr ? new { x.Key, RefValue = GetResource(tr.DarkValue) } :
throw new ArgumentOutOfRangeException()
)
.Select(x => new
{
x.Key.Key,
x.RefValue.Type,
Value = FormatValue(x.RefValue.Value),
})
.ToArray()
.Dump();
var markdown = table.ToMarkdownTable();
Clickable.CopyText("Copy as markdown table", markdown).Dump();
return markdown;
(string Type, object Value) GetResource(object value)
{
if (!(value is StaticResourceRef or ThemeResource))
{
return (GetTypename(value), value);
}
var innerKey = default(string);
while (true)
{
if (value is StaticResourceRef srr)
{
innerKey = srr.Key;
if (resources[srr.Key] is { } mapped)
{
value = mapped;
}
else
{
return (InferTypenameFromSystemKey(srr.Key), srr.Key);
}
}
else if (value is ThemeResource tr)
{
innerKey = tr.Key.Key;
value = tr.DarkValue;
}
else break;
}
return (GetTypename(value), innerKey);
}
string InferTypenameFromSystemKey(string key)
{
var mappings = new (string Pattern, string Replacement)?[]
{
("Brush$", "Brush"),
("FontFamily$", "FontFamily"),
("FontSize$", "Double"),
("CornerRadius$", "CornerRadius"),
};
var result = mappings
.FirstOrDefault(x => Regex.IsMatch(key, x.Value.Pattern))
?.Replacement;
if (result != null)
Util.WithStyle($"Inferring '{key}' as type '{result}'", "color: orange").Dump();
return result;
}
string GetTypename(object value) => value switch
{
GenericValueObject gvo => gvo.Typename,
StaticResource sr => sr.Value?.GetType().Name,
_ => value?.GetType().Name,
};
string FormatValue(object value) => value switch
{
GenericValueObject gvo => gvo.Value,
_ => value?.ToString(),
};
}
public static void ListThemes() // Colors,Opacities,Brushes
{
var palette = (ResourceDictionary)ScuffedXamlParser.Load(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\SharedColorPalette.xaml");
palette.Values.OfThemeResource<Color>()
.Dump("Colors", 0)
.ToCopyableMarkdownTable()
.Dump();
palette.Values.OfStaticResource<double>()
.Dump("Opacities", 0)
.ToCopyableMarkdownTable()
.Dump();
var colors = (ResourceDictionary)ScuffedXamlParser.Load(@"D:\code\uno\platform\Uno.Themes\src\library\Uno.Material\Styles\Application\v2\SharedColors.xaml");
colors.Values.OfThemeResource<SolidColorBrush>()
.MustAll(x => x.AreThemeDefinitionEqual())
.Select(x => new
{
x.Key, Value = (x.LightValue as SolidColorBrush)
})
.Select(x => new
{
x.Key,
Color = x.Value.GetDP("Color") is StaticResourceRef srColor ? (object)srColor.Key : x.Value.Color,
Opacity = x.Value.GetDP("Opacity") is StaticResourceRef srOpacity ? (object)srOpacity.Key : x.Value.Opacity,
})
.Dump("Brushes", 0)
.ToCopyableMarkdownTable()
.Dump();
}
public static void DiffThemeToolkitV2InnerResources()
{
#if false // THEMES
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "Button.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "CalendarDatePicker.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "CalendarView.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "CheckBox.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "ComboBox.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "CommandBar.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "ContentDialog.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "DatePicker.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "FloatingActionButton.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "Flyout.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "HyperlinkButton.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "ListView.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "NavigationView.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "PasswordBox.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "PipsPager.xaml", "PipsPager.UWP.xaml", "PipsPager.Base.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "ProgressBar.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "ProgressRing.xaml", "ProgressRingWinUI.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "RadioButton.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "Ripple.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "Slider.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "TextBlock.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "TextBox.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "ToggleButton.xaml");
//DiffResources(@"D:\code\temp\diff_projects\themes@{2.6,3.0}\Styles\Controls\v2", "ToggleSwitch.xaml");
#elif true // TOOLKIT
//DiffResources(@"D:\code\temp\diff_projects\toolkit@{3.0,4.2}\src\library\Uno.Toolkit.Material\Styles\Controls\v2\", "Card.xaml");
//DiffResources(@"D:\code\temp\diff_projects\toolkit@{3.0,4.2}\src\library\Uno.Toolkit.Material\Styles\Controls\v2\", "CardContentControl.xaml");
//DiffResources(@"D:\code\temp\diff_projects\toolkit@{3.0,4.2}\src\library\Uno.Toolkit.Material\Styles\Controls\v2\", "Chip.xaml");
//DiffResources(@"D:\code\temp\diff_projects\toolkit@{3.0,4.2}\src\library\Uno.Toolkit.Material\Styles\Controls\v2\", "ChipGroup.xaml");
//DiffResources(@"D:\code\temp\diff_projects\toolkit@{3.0,4.2}\src\library\Uno.Toolkit.Material\Styles\Controls\v2\", "Divider.xaml");
//DiffResources(@"D:\code\temp\diff_projects\toolkit@{3.0,4.2}\src\library\Uno.Toolkit.Material\Styles\Controls\v2\", "NavigationBar.xaml");
//DiffResources(@"D:\code\temp\diff_projects\toolkit@{3.0,4.2}\src\library\Uno.Toolkit.Material\Styles\Controls\v2\", "TabBar.xaml");
#endif
//ExtractInnerResources((ResourceDictionary)ScuffedXamlParser.Load(@"D:\code\temp\diff_projects\[email protected]\src\library\Uno.Toolkit.Material\Styles\Controls\v2\NavigationBar.xaml")).Dump();
(string Key, bool Themed, string Value)[] ExtractInnerResources(ResourceDictionary rd)
{
return rd
.OrderByDescending(x => x.Value is ThemeResource)
.Select(x => ((string Key, bool Themed, string Value))(
x.Key.ToString(),
x.Value is ThemeResource,
x.Value switch
{
StaticResource sr => FormatValue(sr.Value),
ThemeResource tr => tr.AreThemeDefinitionEqual()
? FormatValue(tr.LightValue)
: throw new Exception($"Polarized resource: key={x.Dump().Key}"),
_ => throw new ArgumentOutOfRangeException($"Invalid resource dictionary value type: {x.Value.GetType().Name} (key={x.Key})"),
}
))
.ToArray();
}
void DiffResources(string basePattern, params string[] files)
{
if (Regex.Match(basePattern, "{.+}") is not { Success: true } match ||
!match.Value.TryStripPair("{}", out var args) ||
args.Split(',') is not [var oldArg, var newArg])
{
throw new ArgumentException($"Invalid base pattern: {basePattern}");
}
var oldBase = basePattern[..match.Index] + oldArg + basePattern[(match.Index + match.Length)..];
var newBase = basePattern[..match.Index] + newArg + basePattern[(match.Index + match.Length)..];
var oldResources = ExtractInnerResources(GetResources(oldBase, files));
var newResources = ExtractInnerResources(GetResources(newBase, files));
var keys = oldResources.Concat(newResources).Select(x => x.Key).ToList();
var table = Pair(oldResources, newResources, x => x.Key)
.OrderByDescending(x => x.Old?.Themed ?? x.New?.Themed)
.ThenBy(x => keys.IndexOf(x.Old?.Key ?? x.New?.Key))
.Select(x => new
{
OldKey = x.Old?.Key ?? "- NEWLY ADDED -",
NewKey = x.New?.Key ?? "- REMOVED -",
Themed = CompareValue(x.Old?.Themed.ToString(), x.New?.Themed.ToString()),
Value = CompareValue(x.Old?.Value, x.New?.Value),
})
//.Dump(Path.GetFileNameWithoutExtension(files.First()))
//.Where(x => x.OldKey != "- NEWLY ADDED -")
//.ToCopyableMarkdownTable().Dump()
;
$"# {Path.GetFileNameWithoutExtension(files[0])}".Dump();
table.ToMarkdownTable().Dump();
ResourceDictionary GetResources(string basePath, string[] files)
{
return files.Select(x => Path.Combine(basePath, x))
.Where(x => File.Exists(x))
.Aggregate(new ResourceDictionary(), (acc, x) => acc.Merge((ResourceDictionary)ScuffedXamlParser.Load(x)));
}
IEnumerable<(T? Old, T? New)> Pair<T>(IEnumerable<T> oldSource, IEnumerable<T> newSource, Func<T, string> keySelector) where T : struct
{
var oldMap = oldSource.ToDictionary(keySelector);
var newMap = newSource.ToDictionary(keySelector);
foreach (var (o, n) in oldMap.Join(newMap, o => o.Key, n => n.Key, Tuple.Create).ToArray()) // MIDDLE
{
oldMap.Remove(o.Key);
newMap.Remove(n.Key);
yield return (o.Value, n.Value);
}
var knownPairs = new List<(string OldKey, string NewKey)>()
{
("MaterialComboBoxItemSelectedBackgroundThemeBrush", "ComboBoxItemBackgroundSelected"),
("MaterialComboBoxArrowForegroundThemeBrush", "ComboBoxArrowForeground"),
("MaterialComboBoxPlaceholderFocusedThemeBrush", "ComboBoxUpperPlaceHolderForeground"),
("MaterialComboBoxPlaceholderForegroundThemeBrush", "ComboBoxPlaceHolderForeground"),
("MaterialDateTimeFlyoutBorderThickness", "DatePickerFlyoutBorderThickness"),
("MaterialDatePickerFlyoutPresenterBackgroundBrush", "DatePickerFlyoutPresenterBackground"),
("MaterialDatePickerBackgroundColorBrush", "DatePickerButtonBackground"),
("M3MateriaChipCheckGlyphSize", "ChipCheckGlyphSize"), // typo'd
("MaterialChipSelectedForeground", "ChipForegroundChecked"),
("MaterialChipSelectedBackground", "ChipBackgroundChecked"),
("_____", "_____"),
("_____", "_____"),
};
foreach (var knownPair in knownPairs) // MIDDLE'
{
if (oldMap.TryGetValue(knownPair.OldKey, out var oldValue) && newMap.TryGetValue(knownPair.NewKey, out var newValue))
{
oldMap.Remove(knownPair.OldKey);
newMap.Remove(knownPair.NewKey);
yield return (oldValue, newValue);
}
}
var mutationsT1 = new List<(Func<string, string> OldKeyMutator, Func<string, string> NewKeyMutator)>
{
(o => o.Replace("PathData", "Data"), n => n),
(o => o.RegexReplace("GlyphPathStyle", "GlyphPathData"), n => n),
(o => Path.GetFileNameWithoutExtension(files[0]) + o, n => n),
(o => Path.GetFileNameWithoutExtension(files[0]) + o.RegexReplace("^(M3)?Material", ""), n => n),
(o => o.RegexReplace("BackgroundBrush$", "Brush"), n => n),
(o => o.RegexReplace("(Theme|Color)Brush$", ""), n => n),
(o => o.RegexReplace("(Theme|Color)Brush$", "Brush"), n => n),
(o => o.RegexReplace("(Theme|Color)Brush$", "").RegexReplace("(Selected)?(PointerOver|Pressed|Focused|Unfocused|Disabled)(.+)$", "$3$1$2"), n => n),
(o => o.RegexReplace("(Theme|Color)Brush$", "").RegexReplace("(Selected)?(PointerOver|Pressed|Focused|Unfocused|Disabled)(.+)$", "$3$1$2"), n => n.Replace("Checked", "Selected")),
(o => o.RegexReplace("(Theme|Color)Brush$", "").RegexReplace("(Selected)?(PointerOver|Pressed|Focused|Unfocused|Disabled)(.+)$", "$3$1$2"), n => n.Replace("Background", "")),
};
var mutationsT2 = new List<(Func<string, string> OldKeyMutator, Func<string, string> NewKeyMutator)>
{
(o => o, n => n),
(o => o.RegexReplace("^(M3)?Material", ""), n => n),
(o => o.Replace(Path.GetFileNameWithoutExtension(files[0]), ""), n => n.Replace(Path.GetFileNameWithoutExtension(files[0]), "")),
//(o => o.Replace("Selected", "Checked"), n => n),
(o => o.Replace("SurfaceFab", "FabSurface"), n => n),
(o => o.Replace("SecondaryFab", "FabSecondary"), n => n),
(o => o.Replace("TertiaryFab", "FabTertiary"), n => n),
};
foreach (var t2 in mutationsT2)
foreach (var t1 in mutationsT1)
{
(Func<string, string> OldKeyMutator, Func<string, string> NewKeyMutator) mutation = (
OldKeyMutator: (string x) => t1.OldKeyMutator(t2.OldKeyMutator(x)),
NewKeyMutator: (string x) => t1.NewKeyMutator(t2.NewKeyMutator(x)));
foreach (var (o, n) in oldMap.Join(newMap, o => mutation.OldKeyMutator(o.Key), n => mutation.NewKeyMutator(n.Key), Tuple.Create).ToArray()) // MIDDLE'
{
oldMap.Remove(o.Key);
newMap.Remove(n.Key);
yield return (o.Value, n.Value);
}
}
foreach (var o in oldMap) // LEFT
{
yield return (o.Value, default);
}
// we dont care above new values for migration reference
//foreach (var n in newMap) // RIGHT
//{
// yield return (default, n.Value);
//}
}
}
string FormatValue(object value)
{
return value switch
{
StaticResourceRef srr => srr.Key,
Style style => $"Style@{style.TargetType}",
GenericValueObject gvo when gvo.Typename == "LottieVisualSource" => gvo.Value,
GenericValueObject gvo when gvo.Typename == "GridLength" => gvo.Value,
GenericValueObject gvo when gvo.Typename == "ControlTemplate" => null,
_ => value?.ToString(),
};
}
string CompareValue(string o, string n)
{
if (o == null) return n;
if (n == null) return o;
if (o == n) return o;
return o.Length + n.Length > 100
? string.Join("\n", o, "->", n)
: string.Join(" ", o, "->", n);
}
}
}
}
public record DependencyObject
{
private Dictionary<string, object> _properties = new();
public object GetDP(string dp) => _properties.TryGetValue(dp, out var value) ? value : default;
public void SetDP(string dp, object value) => _properties[dp] = value;
}
public record Thickness(double Left, double Top, double Right, double Bottom)
{
public override string ToString()
{
// format: uniform, [same-left-right,same-top-bottom], [left,top,right,bottom]
if (Left == Top && Top == Right && Right == Bottom) return $"{Left:0.#}";
if (Left == Right && Top == Bottom) return $"{Left:0.#},{Top:0.#}";
return $"{Left:0.#},{Top:0.#},{Right:0.#},{Bottom:0.#}";
}
}
public record CornerRadius(double TopLeft, double TopRight, double BottomRight, double BottomLeft)
{
public override string ToString()
{
// format: uniform, [left,top,right,bottom]
if (TopLeft == TopRight && TopRight == BottomRight && BottomRight == BottomLeft) return $"{TopLeft:0.#}";
return $"{TopLeft:0.#},{TopRight:0.#},{BottomRight:0.#},{BottomLeft:0.#}";
}
}
public record Color(byte A, byte R, byte G, byte B)
{
public override string ToString() => "#" + this.ToRgbText();
}
public record SolidColorBrush(Color Color = default, double Opacity = 1) : DependencyObject
{
public override string ToString()
{
var color = GetDP(nameof(Color)) switch
{
IResourceRef rf => rf.Key,
null => Color.ToString(),
_ => throw new ArgumentOutOfRangeException(),
};
var opacity = GetDP(nameof(Opacity)) switch
{
IResourceRef rf => $"*{rf.Key}",
null when Opacity != 1 => $"*{Opacity}",
null => "",
_ => throw new ArgumentOutOfRangeException(),
};
return $"{color}{opacity}";
}
}
public record Style(string Key = null, string TargetType = null, string BasedOn = null)
{
public List<Setter> Setters = new();
private object ToDump() => new { Key, TargetType, BasedOn, Setters };
public static Style ParseStyle(XElement e)
{
var result = new Style(
ResourceDictionary.GetKey(e),
e.Attribute("TargetType")?.Value,
IKeyedResource.GetKeyFromMarkup(e.Attribute("BasedOn")?.Value)
);
foreach (var child in e.Elements())
{
if (child.Name == (Presentation + "Setter"))
{
ParseChild(child);
}
if (child.Name == (Presentation + "Styles.Setter"))
{
foreach (var setter in child.Elements())
{
ParseChild(child);
}
}
}
void ParseChild(XElement child)
{
if (child.Name == (Presentation + "Setter"))
{
result.Setters.Add(ScuffedXamlParser.ParseSetter(child));
}
else
{
throw new NotImplementedException("Unknown member: " + child.Name);
}
}
return result;
}
}
public record Setter(string Property, string Value);
public record GenericValueObject(string Typename, string Value);
public record IgnoredObject(string Typename);