Skip to content

Commit

Permalink
Merge branch 'resource-dictionary'
Browse files Browse the repository at this point in the history
  • Loading branch information
gknyihar committed Jun 28, 2024
2 parents 87e6fcc + 32e9eea commit 11f4c54
Show file tree
Hide file tree
Showing 20 changed files with 282 additions and 54 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,5 @@ UpgradeLog.XML
# OS generated files #
.DS_Store?
ehthumbs.db
Thumbs.db
Thumbs.db
/SvgToXaml/SvgToXaml_TemporaryKey.pfx
3 changes: 2 additions & 1 deletion IconResources/IconResources.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>IconResources</RootNamespace>
<AssemblyName>IconResources</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
Expand Down
3 changes: 1 addition & 2 deletions IconResources/Images/Icons.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.CodeAnalysis;
using System.Windows;

namespace IconResources.Images
Expand Down
1 change: 1 addition & 0 deletions SvgConverter/CmdLineHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public static int HandleCommandLine(string arg)
string[] args = arg != null ? arg.Split(' ') : new string[0];
return HandleCommandLine(args);
}

public static int HandleCommandLine(string[] args)
{
var clp = new CommandLineParser { SkipCommandsWhenHelpRequested = true };
Expand Down
42 changes: 36 additions & 6 deletions SvgConverter/CmdLineTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ public int BuildDict(
[ArgumentParam(DefaultValue = false, ExplicitNeeded = false, LongDesc = "If true, PixelsPerDip is filtered to ensure compatibility for < 4.6.2, default: false")]
bool filterPixelsPerDip = false,
[ArgumentParam(DefaultValue = false, ExplicitNeeded = false, LongDesc = "Recursive goes through inputdir subfolders")]
bool handleSubFolders = false
bool handleSubFolders = false,
[ArgumentParam(DefaultValue = false, ExplicitNeeded = false, LongDesc = "Create resource dictionary instead")]
bool createResourceDictionary = false,
[ArgumentParam(DefaultValue = null, ExplicitNeeded = false, LongDesc = "Postfix of drawing image keys")]
string postfix = null
)
{
Console.WriteLine("Building resource dictionary...");
Expand All @@ -49,13 +53,39 @@ public int BuildDict(
NameSpaceName = compResKeyNSName,
};

File.WriteAllText(outFileName, ConverterLogic.SvgDirToXaml(inputdir, resKeyInfo, null, filterPixelsPerDip, handleSubFolders));
Console.WriteLine("xaml written to: {0}", Path.GetFullPath(outFileName));
if (createResourceDictionary)
{
var folder = outputname;
if (Path.HasExtension(folder))
{
folder = Path.ChangeExtension(folder, "");
}
var absoluteFolder = Path.Combine(outputdir ?? inputdir, folder);
if (!Directory.Exists(absoluteFolder))
{
Directory.CreateDirectory(absoluteFolder);
}
var dict = ConverterLogic.SvgDirToXamlDicts(inputdir, resKeyInfo, null, filterPixelsPerDip, handleSubFolders, postfix);
foreach (var d in dict)
{
var dictFileName = Path.Combine(absoluteFolder, $"{d.Key}.xaml");
File.WriteAllText(dictFileName, d.Value);
Console.WriteLine("xaml written to: {0}", Path.GetFullPath(dictFileName));
}
var wrapper = ConverterLogic.WrapperFileFromList(dict, folder);
var wrapperPath = Path.Combine(outputdir ?? inputdir, $"{folder}.xaml");
File.WriteAllText(wrapperPath, wrapper);
Console.WriteLine("xaml written to: {0}", Path.GetFullPath(wrapperPath));
}
else
{
File.WriteAllText(outFileName, ConverterLogic.SvgDirToXaml(inputdir, resKeyInfo, null, filterPixelsPerDip, handleSubFolders));
Console.WriteLine("xaml written to: {0}", Path.GetFullPath(outFileName));
}

if (buildhtmlfile)
{
var htmlFilePath = Path.Combine(inputdir,
Path.GetFileNameWithoutExtension(outputname));
var htmlFilePath = Path.Combine(outputdir ?? inputdir, Path.GetFileNameWithoutExtension(outputname));
var files = ConverterLogic.SvgFilesFromFolder(inputdir);
BuildHtmlBrowseFile(files, htmlFilePath);
}
Expand Down Expand Up @@ -88,7 +118,7 @@ private static void BuildHtmlBrowseFile(IEnumerable<string> files, string output
new XElement("br"),
files.Select(
f => new XElement("img",
new XAttribute("src", Path.GetFileName(f) ?? ""),
new XAttribute("src", Path.GetFullPath(f)),
new XAttribute("title", Path.GetFileNameWithoutExtension(f) ?? ""),
new XAttribute("height", size),
new XAttribute("width", size)
Expand Down
137 changes: 117 additions & 20 deletions SvgConverter/ConverterLogic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using CloneDeep;
using SharpVectors.Converters;
using SharpVectors.Dom.Resources;
using SharpVectors.Renderers.Wpf;

namespace SvgConverter
Expand Down Expand Up @@ -50,9 +52,11 @@ public static ConvertedSvgData ConvertSvg(string filepath, ResultMode resultMode
//var obj = ConvertSvgToObject(filepath, resultMode, null, out name) as DependencyObject;
//var xaml = SvgObjectToXaml(obj, false, name);
//var svg = File.ReadAllText(filepath);

return new ConvertedSvgData { Filepath = filepath
//, ConvertedObj = obj, Svg = svg, Xaml = xaml

return new ConvertedSvgData
{
Filepath = filepath
//, ConvertedObj = obj, Svg = svg, Xaml = xaml
};
}

Expand Down Expand Up @@ -122,6 +126,70 @@ public static string SvgDirToXaml(string folder, ResKeyInfo resKeyInfo, WpfDrawi
return doc.ToString();
}

public static IDictionary<string, string> SvgDirToXamlDicts(string folder, ResKeyInfo resKeyInfo, WpfDrawingSettings wpfDrawingSettings,
bool filterPixelsPerDip, bool handleSubFolders = false, string postfix = null)
{
//firstChar Upper
var firstChar = char.ToUpperInvariant(resKeyInfo.XamlName[0]);
resKeyInfo.XamlName = firstChar + resKeyInfo.XamlName.Remove(0, 1);

if (postfix != null && postfix.Length > 0)
{
var postfixFirstChar = char.ToUpperInvariant(postfix[0]);
postfix = postfixFirstChar + postfix.Remove(0, 1);
}

var files = SvgFilesFromFolder(folder, handleSubFolders);
var dict = ConvertFilesToResourceDictionary(files, wpfDrawingSettings, resKeyInfo, postfix);
var xamlUntidy = WpfObjToXaml(dict, wpfDrawingSettings?.IncludeRuntime ?? false);

var doc = XDocument.Parse(xamlUntidy);
RemoveResDictEntries(doc.Root);
var drawingGroupElements = doc.Root.XPathSelectElements("defns:DrawingGroup", NsManager).ToList();

var rootTemplate = new XDocument(doc);
rootTemplate.Root.RemoveAll();


var resDict = new Dictionary<string, string>();
foreach (var drawingGroupElement in drawingGroupElements)
{
BeautifyDrawingElement(drawingGroupElement, null);
if (filterPixelsPerDip)
FilterPixelsPerDip(drawingGroupElement);

var root = new XDocument(rootTemplate);
root.Root.Add(drawingGroupElement);


AddNameSpaceDef(rootTemplate.Root, resKeyInfo);
AddDrawingGroupsToDrawingImages(root.Root);

var key = drawingGroupElement.Attribute(Nsx + "Key").Value;
if (postfix != null)
{
key = key.Substring(0, key.LastIndexOf(postfix));
}

resDict.Add(key, root.ToString());
}

return resDict;
}

public static string WrapperFileFromList(IDictionary<string, string> files, string folder)
{
var root = new XDocument(new XElement(NsDef + "ResourceDictionary"));
var node = new XElement(NsDef + "ResourceDictionary.MergedDictionaries");
foreach (var file in files)
{
var elem = new XElement(NsDef + "ResourceDictionary", new XAttribute("Source", $"{folder}/{file.Key}.xaml"));
node.Add(elem);
}
root.Root.Add(node);
return root.ToString();
}

public static IEnumerable<string> SvgFilesFromFolder(string folder, bool handleSubFolders = false)
{
try
Expand Down Expand Up @@ -163,21 +231,21 @@ private static void ReplaceBrushesInDrawingGroupsOld(XElement rootElement, ResKe
.Distinct(StringComparer.InvariantCultureIgnoreCase) //same Color only once
.Select((s, i) => new
{
ResKey1 = BuildColorName(i+1, resKeyInfo),
ResKey2 = BuildColorBrushName(i + 1, resKeyInfo),
ResKey1 = BuildColorName(i + 1, resKeyInfo),
ResKey2 = BuildColorBrushName(i + 1, resKeyInfo),
Color = s
}) //add numbers
.ToList();

//building global Elements like: <SolidColorBrush x:Key="ImagesColorBrush1" Color="{DynamicResource ImagesColor1}" />
rootElement.AddFirst(allBrushes
.Select(brush => new XElement(NsDef + "SolidColorBrush",
.Select(brush => new XElement(NsDef + "SolidColorBrush",
new XAttribute(Nsx + "Key", brush.ResKey2),
new XAttribute("Color", $"{{DynamicResource {brush.ResKey1}}}"))));

//building global Elements like: <Color x:Key="ImagesColor1">#FF000000</Color>
rootElement.AddFirst(allBrushes
.Select(brush => new XElement(NsDef + "Color",
.Select(brush => new XElement(NsDef + "Color",
new XAttribute(Nsx + "Key", brush.ResKey1),
brush.Color)));

Expand All @@ -191,24 +259,24 @@ private static void ReplaceBrushesInDrawingGroupsOld(XElement rootElement, ResKe
var keyDg = node.Attribute(Nsx + "Key").Value;
var elemName = GetElemNameFromResKey(keyDg, resKeyInfo);
var elemBaseName = elemName.Replace("DrawingGroup", "");

var brushAttributes = CollectBrushAttributesWithColor(node).ToList();

foreach (var brushAttribute in brushAttributes)
{
var color = brushAttribute.Value;
string resKeyColor;
if (colorKeys.TryGetValue(color, out resKeyColor))
{ //global color found

//build resourcename
var nameBrush = brushAttributes.Count > 1
? $"{elemBaseName}Color{brushAttributes.IndexOf(brushAttribute) + 1}Brush"
: $"{elemBaseName}ColorBrush"; //dont add number if only one color
var resKeyBrush = BuildResKey(nameBrush, resKeyInfo);
node.AddBeforeSelf(new XElement(NsDef + "SolidColorBrush",
new XAttribute(Nsx + "Key", resKeyBrush),
new XAttribute("Color", $"{{Binding Color, Source={BuildResKeyReference(resKeyColor, false)}}}") ));
node.AddBeforeSelf(new XElement(NsDef + "SolidColorBrush",
new XAttribute(Nsx + "Key", resKeyBrush),
new XAttribute("Color", $"{{Binding Color, Source={BuildResKeyReference(resKeyColor, false)}}}")));
//set brush value as Reference
// <GeometryDrawing Brush="{DynamicResource {x:Static nsname:Test.cloud-3-iconBrushColor}}" ... />
brushAttribute.Value = BuildResKeyReference(resKeyBrush, true);
Expand All @@ -224,7 +292,7 @@ private static void ReplaceBrushesInDrawingGroups(XElement rootElement, ResKeyIn
foreach (var node in drawingGroups)
{
var brushAttributes = CollectBrushAttributesWithColor(node).ToList();

foreach (var brushAttribute in brushAttributes)
{
var color = brushAttribute.Value;
Expand Down Expand Up @@ -261,14 +329,38 @@ private static void AddDrawingImagesToDrawingGroups(XElement rootElement)
}
}

internal static ResourceDictionary ConvertFilesToResourceDictionary(IEnumerable<string> files, WpfDrawingSettings wpfDrawingSettings, ResKeyInfo resKeyInfo)
private static void AddDrawingGroupsToDrawingImages(XElement rootElement)
{
var drawingGroups = rootElement.Elements(NsDef + "DrawingGroup").ToList();
rootElement.RemoveAll();
rootElement.SetAttributeValue(XNamespace.Xmlns + "x", "http://schemas.microsoft.com/winfx/2006/xaml");
foreach (var node in drawingGroups)
{
//get Name of DrawingGroup
var nameDg = node.Attribute(Nsx + "Key").Value;
node.Attribute(Nsx + "Key").Remove();
var nameImg = nameDg.Replace("DrawingGroup", "DrawingImage");
//<DrawingImage x:Key="xxx" Drawing="{StaticResource cloud_5_icon_DrawingGroup}"/>
var drawingImage = new XElement(NsDef + "DrawingImage",
new XAttribute(Nsx + "Key", nameImg)
);
var drawing = new XElement(NsDef + "DrawingImage.Drawing");
drawing.Add(node);
drawingImage.Add(drawing);
rootElement.Add(drawingImage);
}
}

internal static ResourceDictionary ConvertFilesToResourceDictionary(IEnumerable<string> files, WpfDrawingSettings wpfDrawingSettings, ResKeyInfo resKeyInfo, string postfix = null)
{
var dict = new ResourceDictionary();
foreach (var file in files)
{
var drawingGroup = ConvertFileToDrawingGroup(file, wpfDrawingSettings);
var elementName = Path.GetFileNameWithoutExtension(file);
var keyDg = BuildDrawingGroupName(elementName, resKeyInfo);
var keyDg = postfix != null
? BuildPostfixName(elementName, postfix, resKeyInfo)
: BuildDrawingGroupName(elementName, resKeyInfo);
dict[keyDg] = drawingGroup;
}
return dict;
Expand Down Expand Up @@ -386,8 +478,8 @@ private static bool IsSvgz(string filepath)
private static void FixIds(XElement root)
{
var idAttributesStartingWithDigit = root.DescendantsAndSelf()
.SelectMany(d=>d.Attributes())
.Where(a=>string.Equals(a.Name.LocalName, "Id", StringComparison.InvariantCultureIgnoreCase));
.SelectMany(d => d.Attributes())
.Where(a => string.Equals(a.Name.LocalName, "Id", StringComparison.InvariantCultureIgnoreCase));
foreach (var attr in idAttributesStartingWithDigit)
{
if (char.IsDigit(attr.Value.FirstOrDefault()))
Expand All @@ -407,7 +499,7 @@ internal static DrawingImage DrawingToImage(Drawing drawing)

internal static string WpfObjToXaml(object wpfObject, bool includeRuntime)
{
XmlXamlWriter writer = new XmlXamlWriter(new WpfDrawingSettings { IncludeRuntime = includeRuntime});
XmlXamlWriter writer = new XmlXamlWriter(new WpfDrawingSettings { IncludeRuntime = includeRuntime });
var xaml = writer.Save(wpfObject);
return xaml;
}
Expand Down Expand Up @@ -545,7 +637,7 @@ private static void ExtractGeometries(XElement drawingGroupElement, ResKeyInfo r
: (int?)null;
var localName = BuildGeometryName(name, no, resKeyInfo);
//Add this: <Geometry x:Key="cloud_3_iconGeometry">F1 M512,512z M0,0z M409.338,216.254C398.922,351.523z</Geometry>
drawingGroupElement.AddBeforeSelf(new XElement(NsDef+"Geometry",
drawingGroupElement.AddBeforeSelf(new XElement(NsDef + "Geometry",
new XAttribute(Nsx + "Key", localName),
geo.Value));
geo.Value = BuildResKeyReference(localName, false);
Expand Down Expand Up @@ -583,6 +675,11 @@ internal static string BuildDrawingImageName(string elementName, ResKeyInfo resK
var rawName = elementName + "DrawingImage";
return BuildResKey(rawName, resKeyInfo);
}
internal static string BuildPostfixName(string elementName, string postfix, ResKeyInfo resKeyInfo)
{
var rawName = elementName + postfix;
return BuildResKey(rawName, resKeyInfo);
}

internal static string BuildGeometryName(string name, int? no, ResKeyInfo resKeyInfo)
{
Expand Down
2 changes: 1 addition & 1 deletion SvgConverter/SvgConverter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SvgConverter</RootNamespace>
<AssemblyName>SvgConverter</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
Expand Down
2 changes: 1 addition & 1 deletion SvgConverter/app.config
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/></startup></configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/></startup></configuration>
2 changes: 1 addition & 1 deletion SvgConverterTest/SvgConverterTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SvgConverterTest</RootNamespace>
<AssemblyName>SvgConverterTest</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
Expand Down
2 changes: 1 addition & 1 deletion SvgConverterTest/app.config
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/></startup></configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/></startup></configuration>
Loading

0 comments on commit 11f4c54

Please sign in to comment.