-
Notifications
You must be signed in to change notification settings - Fork 13
/
MainWindow.xaml.cs
433 lines (380 loc) · 17.1 KB
/
MainWindow.xaml.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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Xml;
using System.Xml.Linq;
namespace StyleSnooper
{
public sealed partial class MainWindow : INotifyPropertyChanged
{
private readonly Style _bracketStyle, _elementStyle, _quotesStyle, _textStyle, _attributeStyle;
public MainWindow()
{
Styles = GetStyles(typeof(FrameworkElement).Assembly).ToList();
InitializeComponent();
// get syntax coloring styles
_bracketStyle = (Style)Resources["BracketStyle"];
_elementStyle = (Style)Resources["ElementStyle"];
_quotesStyle = (Style)Resources["QuotesStyle"];
_textStyle = (Style)Resources["TextStyle"];
_attributeStyle = (Style)Resources["AttributeStyle"];
// start out by looking at Button
CollectionViewSource.GetDefaultView(Styles).MoveCurrentTo(Styles.Single(s => s.ElementType == typeof(Button)));
}
public List<StyleModel> Styles { get; private set; }
private static IEnumerable<Type> GetFrameworkElementTypesFromAssembly(Assembly assembly)
{
// Returns all types in the specified assembly that are non-abstract,
// and non-generic, derive from FrameworkElement, and have a default constructor
foreach (var type in assembly.GetTypes())
{
if (// type.IsPublic && // maybe we wanna peek at nonpublic ones?
!type.IsAbstract &&
!type.ContainsGenericParameters &&
typeof(FrameworkElement).IsAssignableFrom(type) &&
(type.GetConstructor(Type.EmptyTypes) != null ||
type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null) != null // allow a nonpublic ctor
))
{
yield return type;
}
}
}
private static IEnumerable<StyleModel> GetStyles(Assembly assembly)
{
return GetFrameworkElementTypesFromAssembly(assembly)
.OrderBy(type => type.Name, StringComparer.Ordinal)
.SelectMany(GetStyles);
}
private static IEnumerable<StyleModel> GetStyles(Type type)
{
// make an instance of the type and get its default style key
if (type.GetConstructor(Type.EmptyTypes) != null)
{
var element = (FrameworkElement)Activator.CreateInstance(type, false);
var defaultStyleKey = element.GetValue(DefaultStyleKeyProperty);
yield return new StyleModel(
DisplayName: type.Name,
ResourceKey: defaultStyleKey,
ElementType: type);
foreach (var styleModel in GetStylesFromStaticProperties(element))
{
yield return styleModel;
}
}
}
private static IEnumerable<StyleModel> GetStylesFromStaticProperties(FrameworkElement element)
{
var properties = element.GetType()
.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)
.Where(p => p.Name.EndsWith("StyleKey") && p.PropertyType == typeof(ResourceKey));
foreach (var property in properties)
{
var elementType = element.GetType();
var resourceKey = property.GetValue(element);
yield return new StyleModel(
DisplayName: $"{elementType.Name}.{property.Name}",
ResourceKey: resourceKey,
ElementType: elementType);
}
}
private void OnLoadClick(object sender, RoutedEventArgs e)
{
// create the file open dialog
var openFileDialog = new Microsoft.Win32.OpenFileDialog
{
CheckFileExists = true,
Multiselect = false,
Filter = "Assemblies (*.exe;*.dll)|*.exe;*.dll"
};
if (openFileDialog.ShowDialog(this) != true)
return;
try
{
AsmName.Text = openFileDialog.FileName;
var styles = GetStyles(Assembly.LoadFile(openFileDialog.FileName)).ToList();
if (styles.Count == 0)
{
MessageBox.Show("Assembly does not contain any compatible types.");
}
else
{
Styles = styles;
OnPropertyChanged(nameof(Styles));
}
}
catch
{
MessageBox.Show("Error loading assembly.");
}
}
private void ShowStyle(object sender, SelectionChangedEventArgs e)
{
if (styleTextBox == null) return;
// see which type is selected
if (typeComboBox.SelectedValue is StyleModel style)
{
var success = TrySerializeStyle(style.ResourceKey, out var serializedStyle);
if (success)
{
serializedStyle = CleanupStyle(serializedStyle);
}
// show the style in a document viewer
styleTextBox.Document = CreateFlowDocument(success, serializedStyle);
}
}
/// <summary>
/// Serializes a style using XamlWriter.
/// </summary>
/// <param name="resourceKey"></param>
/// <param name="serializedStyle"></param>
/// <returns></returns>
private static bool TrySerializeStyle(object? resourceKey, out string serializedStyle)
{
var success = false;
serializedStyle = "[Style not found]";
if (resourceKey != null)
{
// try to get the default style for the type
if (Application.Current.TryFindResource(resourceKey) is Style style)
{
// try to serialize the style
try
{
var stringWriter = new StringWriter();
var xmlTextWriter = new XmlTextWriter(stringWriter) { Formatting = Formatting.Indented };
System.Windows.Markup.XamlWriter.Save(style, xmlTextWriter);
serializedStyle = stringWriter.ToString();
success = true;
}
catch (Exception exception)
{
serializedStyle = "[Exception thrown while serializing style]" +
Environment.NewLine + Environment.NewLine + exception;
}
}
}
return success;
}
/// <summary>
/// Creates a FlowDocument from the serialized XAML with simple syntax coloring.
/// </summary>
/// <param name="success"></param>
/// <param name="serializedStyle"></param>
/// <returns></returns>
private FlowDocument CreateFlowDocument(bool success, string serializedStyle)
{
var document = new FlowDocument();
if (success)
{
using (var reader = new XmlTextReader(serializedStyle, XmlNodeType.Document, null))
{
var indent = 0;
var paragraph = new Paragraph();
while (reader.Read())
{
if (reader.IsStartElement()) // opening tag, e.g. <Button
{
string elementName = reader.Name;
// indentation
paragraph.AddRun(_textStyle, new string(' ', indent * 4));
paragraph.AddRun(_bracketStyle, "<");
paragraph.AddRun(_elementStyle, elementName);
if (reader.HasAttributes)
{
// write tag attributes
while (reader.MoveToNextAttribute())
{
paragraph.AddRun(_attributeStyle, " " + reader.Name);
paragraph.AddRun(_bracketStyle, "=");
paragraph.AddRun(_quotesStyle, "\"");
if (reader.Name == "TargetType") // target type fix - should use the Type MarkupExtension
{
paragraph.AddRun(_textStyle, "{x:Type " + reader.Value + "}");
}
else if (reader.Name == "Margin" || reader.Name == "Padding")
{
paragraph.AddRun(_textStyle, SimplifyThickness(reader.Value));
}
else
{
paragraph.AddRun(_textStyle, reader.Value);
}
paragraph.AddRun(_quotesStyle, "\"");
paragraph.AddLineBreak();
paragraph.AddRun(_textStyle, new string(' ', indent * 4 + elementName.Length + 1));
}
paragraph.RemoveLastLineBreak();
reader.MoveToElement();
}
if (reader.IsEmptyElement) // empty tag, e.g. <Button />
{
paragraph.AddRun(_bracketStyle, " />");
paragraph.AddLineBreak();
--indent;
}
else // non-empty tag, e.g. <Button>
{
paragraph.AddRun(_bracketStyle, ">");
paragraph.AddLineBreak();
}
++indent;
}
else // closing tag, e.g. </Button>
{
--indent;
// indentation
paragraph.AddRun(_textStyle, new string(' ', indent * 4));
// text content of a tag, e.g. the text "Do This" in <Button>Do This</Button>
if (reader.NodeType == XmlNodeType.Text)
{
var value = reader.ReadContentAsString();
if (reader.Name == "Thickness")
value = SimplifyThickness(value);
paragraph.AddRun(_textStyle, value);
}
paragraph.AddRun(_bracketStyle, "</");
paragraph.AddRun(_elementStyle, reader.Name);
paragraph.AddRun(_bracketStyle, ">");
paragraph.AddLineBreak();
}
}
document.Blocks.Add(paragraph);
}
}
else // no style found
{
document.Blocks.Add(new Paragraph(new Run(serializedStyle)) { TextAlignment = TextAlignment.Left });
}
return document;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private static readonly XNamespace xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
private static readonly XNamespace xmlns_s = "clr-namespace:System;assembly=mscorlib";
private static readonly XNamespace xmlns_x = "http://schemas.microsoft.com/winfx/2006/xaml";
private static string CleanupStyle(string serializedStyle)
{
XDocument styleXml = XDocument.Parse(serializedStyle);
RemoveEmptyResources(styleXml);
SimplifyStyleSetterValues(styleXml);
SimplifyAttributeValues(styleXml);
return styleXml.ToString();
}
private static void RemoveEmptyResources(XDocument styleXml)
{
foreach (var elt in styleXml.Descendants())
{
var localName = elt.Name.LocalName;
var eltResources = elt.Element(xmlns + $"{localName}.Resources");
if (eltResources != null)
{
var eltResourceDictionary = eltResources.Element(xmlns + "ResourceDictionary");
if (eltResourceDictionary?.IsEmpty ?? false)
eltResources.Remove();
}
}
}
private static void SimplifyStyleSetterValues(XDocument styleXml)
{
foreach (var elt in styleXml.Descendants())
{
var localName = elt.Name.LocalName;
var eltValueNode = elt.Element(xmlns + $"{localName}.Value");
if (eltValueNode == null)
continue;
var eltValue = eltValueNode.Elements().SingleOrDefault();
switch (eltValue?.Name)
{
case { } name when name == xmlns + "SolidColorBrush":
elt.SetAttributeValue("Value", SimplifyHexColor(eltValue.Value));
eltValueNode.Remove();
break;
case { } name when name == xmlns + "DynamicResource":
elt.SetAttributeValue("Value", $"{{DynamicResource {eltValue.Attribute("ResourceKey")?.Value}}}");
eltValueNode.Remove();
break;
case { } name when name == xmlns + "StaticResource":
elt.SetAttributeValue("Value", $"{{StaticResource {eltValue.Attribute("ResourceKey")?.Value}}}");
eltValueNode.Remove();
break;
case { } name when name.Namespace == xmlns_s:
elt.SetAttributeValue("Value", eltValue.Value);
eltValueNode.Remove();
break;
case { } name when name == xmlns + "Thickness":
elt.SetAttributeValue("Value", SimplifyThickness(eltValue.Value));
eltValueNode.Remove();
break;
case { } name when name == xmlns_x + "Static":
{
var value = eltValue.Attribute("Member")?.Value;
value = value?.Split('.').Last();
if (value != null)
{
elt.SetAttributeValue("Value", value);
eltValueNode.Remove();
}
break;
}
}
}
}
private static void SimplifyAttributeValues(XDocument styleXml)
{
foreach (var element in styleXml.Descendants())
{
foreach (var attribute in element.Attributes())
{
switch (attribute.Name.LocalName)
{
case "Color":
case "BorderBrush":
case "Fill":
case "StrokeBrush":
case "Background":
attribute.Value = SimplifyHexColor(attribute.Value);
break;
case "BorderThickness":
case "StrokeThickness":
case "CornerRadius":
attribute.Value = SimplifyThickness(attribute.Value);
break;
}
}
}
}
private static string SimplifyThickness(string s)
{
var four = Regex.Match(s, @"(-?[\d+]),\1,\1,\1");
if (four.Success)
return four.Groups[1].Value;
var two = Regex.Match(s, @"(-?[\d+]),(-?[\d+]),\1,\2");
if (two.Success)
return $"{two.Groups[1].Value},{two.Groups[2].Value}";
return s;
}
private static string SimplifyHexColor(string hex)
{
if (hex.Length == 9 && hex.StartsWith("#FF"))
{
return "#" + hex.Substring(3);
}
return hex;
}
}
}