Skip to content

Commit 9d6fb72

Browse files
committed
Unsphagettied the code. Refactoring.
1 parent 1a59c87 commit 9d6fb72

35 files changed

+2010
-2730
lines changed

SvgFileType/Export/SvgExport.cs

Lines changed: 5 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,7 @@ internal static partial class SvgExport
2525
IFileSystemService fss = Services.Get<IFileSystemService>();
2626
string path = Path.Combine(fss.PerUserAppFilesPath, "Shapes");
2727
if (!Directory.Exists(path))
28-
{
2928
Directory.CreateDirectory(path);
30-
}
3129
return path;
3230
}
3331
catch
@@ -39,9 +37,8 @@ internal static partial class SvgExport
3937
public static string? ShowSaveShapeDialog()
4038
{
4139
if (!UIHelper.IsSaveConfigDialogVisible())
42-
{
4340
return null;
44-
}
41+
4542
return UIHelper.RunOnUIThread(() =>
4643
{
4744
using SaveFileDialog sfd = new SaveFileDialog();
@@ -116,21 +113,15 @@ public static void Export(Surface input, Stream output, PropertyCollection props
116113
int newWidth = maxDimForPreview;
117114
int newHeight = maxDimForPreview;
118115
if (input.Width > input.Height)
119-
{
120116
newHeight = (int)Math.Round(maxDimForPreview / ar);
121-
}
122117
else
123-
{
124118
newWidth = (int)Math.Round(maxDimForPreview * ar);
125-
}
126119

127120
surface = new Surface(newWidth, newHeight);
128121
surface.FitSurface(ResamplingAlgorithm.Cubic, input);
129122
}
130123
else
131-
{
132124
surface = input.Clone();
133-
}
134125

135126
using (surface)
136127
using (CancellationTokenSource cts = new CancellationTokenSource())
@@ -173,9 +164,7 @@ void OnProgress(float prog)
173164
gm.HighPassFilter(lambda: highpass);
174165

175166
if (lowpass > 0)
176-
{
177167
gm.LowPassFilter(lambda: lowpass);
178-
}
179168

180169
if (gmScale > 1)
181170
{
@@ -184,22 +173,16 @@ void OnProgress(float prog)
184173
backend.Ry *= gmScale;
185174
}
186175
else
187-
{
188176
bm = gm.Threshold(c: brightnessCutoff);
189-
}
190177
}
191178

192179
using (bm)
193180
{
194181
if (invert)
195-
{
196182
bm.Invert();
197-
}
198183

199184
if (enclose)
200-
{
201185
bm.Enclose();
202-
}
203186

204187
Progress<ProgressArgs> progress = new Progress<ProgressArgs>((prog) => OnProgress(ConvertProgressValue(prog)));
205188
trace = bm.Trace(turdsize, turnpolicy, alphamax, opttolerance, progress, cancellationToken);
@@ -210,13 +193,9 @@ void OnProgress(float prog)
210193
if (trace == null)
211194
{
212195
if (UIHelper.IsSaveConfigDialogVisible())
213-
{
214196
return;
215-
}
216197
else
217-
{
218198
throw new InvalidOperationException(StringResources.NoPath);
219-
}
220199
}
221200

222201
if (dialogVisible && scanMode == ScanMode.Transparent && shapePath.Length > 0)
@@ -227,9 +206,7 @@ void OnProgress(float prog)
227206
DisplayName = shapeName
228207
};
229208
using (FileStream shapeStream = File.Open(shapePath, FileMode.Create, FileAccess.Write))
230-
{
231209
pdnbackend.Save(shapeStream, trace, imginfo, cancellationToken);
232-
}
233210

234211
StringBuilder msg = new StringBuilder();
235212
msg.AppendFormat(StringResources.ShapeSaved, shapePath);
@@ -241,7 +218,10 @@ void OnProgress(float prog)
241218
msg.AppendLine(StringResources.ShapeSavedRestart);
242219
}
243220

244-
UIHelper.RunOnUIThread(() => { MessageBox.Show(msg.ToString(), StringResources.ShapeSavedCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); });
221+
UIHelper.RunOnUIThread(() =>
222+
{
223+
MessageBox.Show(msg.ToString(), StringResources.ShapeSavedCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
224+
});
245225
}
246226
backend.Save(output, trace, imginfo, cancellationToken);
247227
}
@@ -264,9 +244,7 @@ private static float ConvertProgressValue(ProgressArgs args)
264244
{
265245
float progress = args.Progress * .5f;
266246
if (args.Level == ProgressLevel.Tracing)
267-
{
268247
progress += .5f;
269-
}
270248
return progress;
271249
}
272250
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright 2025 Osman Tunçelli. All rights reserved.
2+
// Use of this source code is governed by GNU General Public License (GPL-2.0) that can be found in the COPYING file.
3+
4+
using System;
5+
6+
namespace SvgFileTypePlugin.Extensions;
7+
8+
internal static class StringExtensions
9+
{
10+
/// <exception cref="ArgumentNullException"></exception>
11+
/// <exception cref="ArgumentOutOfRangeException"></exception>
12+
public static string Truncate(this string s, int maxLength, string suffix = "...")
13+
{
14+
ArgumentNullException.ThrowIfNull(s);
15+
ArgumentOutOfRangeException.ThrowIfNegative(maxLength);
16+
17+
return s.Length > maxLength ? $"{s[..maxLength]}{suffix}" : s;
18+
}
19+
}

SvgFileType/Extensions/SurfaceExtensions.cs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,32 @@
44
using System;
55
using System.Runtime.CompilerServices;
66
using PaintDotNet;
7+
using PaintDotNet.Rendering;
78

89
namespace SvgFileTypePlugin.Extensions;
910

1011
internal static class SurfaceExtensions
1112
{
12-
public static Document CreateDocument(this Surface surface, bool takeOwnership = false)
13+
/// <exception cref="ArgumentNullException"></exception>
14+
public static Document CreateSingleLayerDocument(this Surface surface, bool takeOwnership = false)
1315
{
1416
ArgumentNullException.ThrowIfNull(surface);
1517

1618
Document document = new Document(surface.Width, surface.Height);
17-
document.Layers.Add(new BitmapLayer(surface, takeOwnership));
19+
try
20+
{
21+
BitmapLayer layer = new BitmapLayer(surface, takeOwnership);
22+
document.Layers.Add(layer);
23+
}
24+
catch
25+
{
26+
document.Dispose();
27+
throw;
28+
}
1829
return document;
1930
}
2031

21-
public static void ConvertFromRgba(this Surface surface)
32+
public static void ConvertFromPrgba(this Surface surface)
2233
{
2334
ArgumentNullException.ThrowIfNull(surface);
2435

@@ -31,6 +42,7 @@ public static void ConvertFromRgba(this Surface surface)
3142
pix = ref Unsafe.Add(ref pix, 1);
3243
}
3344
}
45+
surface.ConvertFromPremultipliedAlpha();
3446
}
3547

3648
public static bool IsEmpty(this Surface surface)

SvgFileType/Extensions/SvgDocumentExtensions.cs

Lines changed: 39 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -7,63 +7,67 @@
77
using System.Text;
88
using Svg;
99
using SvgFileTypePlugin.Import;
10-
using Disposable = SvgFileTypePlugin.Import.Disposable;
1110

1211
namespace SvgFileTypePlugin.Extensions;
1312

1413
internal static class SvgDocumentExtensions
1514
{
16-
public static Stream AsStream(this SvgDocument svg)
15+
public static SvgDocument RemoveInvisibleAndNonTextElements(this SvgDocument svg)
1716
{
1817
ArgumentNullException.ThrowIfNull(svg);
1918

20-
byte[] bytes = Encoding.UTF8.GetBytes(svg.GetXML2());
21-
return new MemoryStream(bytes);
19+
SvgFragment clonedFragment = (SvgFragment)svg.Clone();
20+
clonedFragment.RemoveInvisibleAndNonTextElements();
21+
SvgDocument clonedDocument = new SvgDocument();
22+
clonedDocument.Children.Add(clonedFragment);
23+
return clonedDocument;
2224
}
2325

24-
public static string GetXML2(this SvgDocument svg)
26+
public static IDisposable UseSetRasterDimensions(this SvgDocument svg, SvgImportConfig config)
2527
{
2628
ArgumentNullException.ThrowIfNull(svg);
29+
ArgumentNullException.ThrowIfNull(config);
2730

28-
// A workaround until this gets resolved
29-
// https://github.com/RazrFalcon/resvg/issues/235
30-
return svg.GetXML().Replace("&quot;", string.Empty);
31+
int width = config.RasterWidth;
32+
int height = config.RasterHeight;
33+
SvgAspectRatio originalAspectRatio = svg.AspectRatio;
34+
SizeF originalSize = svg.GetDimensions();
35+
SvgViewBox originalViewbox = svg.ViewBox;
36+
SizeF rasterSize = originalSize;
37+
svg.RasterizeDimensions(ref rasterSize, width, height);
38+
svg.Width = rasterSize.Width;
39+
svg.Height = rasterSize.Height;
40+
svg.ViewBox = new SvgViewBox(0, 0, originalSize.Width, originalSize.Height);
41+
SvgPreserveAspectRatio aspectRatio = config.PreserveAspectRatio
42+
? SvgPreserveAspectRatio.xMinYMin
43+
: SvgPreserveAspectRatio.none;
44+
svg.AspectRatio = new SvgAspectRatio(aspectRatio);
45+
return Utils.DisposableFromAction(() =>
46+
{
47+
// Restore the original values back
48+
svg.AspectRatio = originalAspectRatio;
49+
svg.Width = originalSize.Width;
50+
svg.Height = originalSize.Height;
51+
svg.ViewBox = originalViewbox;
52+
});
3153
}
3254

33-
public static SvgDocument Cleanup(this SvgDocument svg)
55+
public static string GetXML2(this SvgDocument svg)
3456
{
3557
ArgumentNullException.ThrowIfNull(svg);
3658

37-
SvgFragment fragment = (SvgFragment)svg.Clone();
38-
fragment.Cleanup();
39-
SvgDocument clone = new SvgDocument();
40-
clone.Children.Add(fragment);
41-
return clone;
59+
// This issue has been resolved for resvg but,
60+
// apparently, Direct2D renderer is also affected.
61+
// https://github.com/RazrFalcon/resvg/issues/235
62+
return svg.GetXML().Replace("&quot;", string.Empty);
4263
}
4364

44-
public static IDisposable UseSetRasterDimensions(this SvgDocument svg, SvgImportConfig config)
65+
public static Stream AsStream(this SvgDocument svg, bool removeQuotes = false)
4566
{
4667
ArgumentNullException.ThrowIfNull(svg);
47-
ArgumentNullException.ThrowIfNull(config);
4868

49-
int width = config.Width;
50-
int height = config.Height;
51-
bool preserveAR = config.PreserveAspectRatio;
52-
SvgAspectRatio origAR = svg.AspectRatio;
53-
SizeF origSize = svg.GetDimensions();
54-
SizeF tmp = origSize;
55-
svg.RasterizeDimensions(ref tmp, width, height);
56-
svg.Width = tmp.Width;
57-
svg.Height = tmp.Height;
58-
SvgPreserveAspectRatio aspectRatio = preserveAR ? SvgPreserveAspectRatio.xMinYMin : SvgPreserveAspectRatio.none;
59-
svg.AspectRatio = new SvgAspectRatio(aspectRatio);
60-
return Disposable.FromAction(() =>
61-
{
62-
SizeF tmp = origSize;
63-
svg.AspectRatio = origAR;
64-
svg.RasterizeDimensions(ref tmp, 0, 0);
65-
svg.Width = tmp.Width;
66-
svg.Height = tmp.Height;
67-
});
69+
string xml = removeQuotes ? svg.GetXML2() : svg.GetXML();
70+
byte[] bytes = Encoding.UTF8.GetBytes(xml);
71+
return new MemoryStream(bytes);
6872
}
6973
}

SvgFileType/Extensions/SvgElementExtensions.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33

44
using System;
55
using System.Reflection;
6-
using System.Runtime.Intrinsics.Arm;
7-
using System.Xml.Linq;
86
using Svg;
97

108
namespace SvgFileTypePlugin.Extensions;
@@ -30,7 +28,7 @@ public static string GetName(this SvgElement element)
3028
return (SvgAttributeCollection?)AttributesGetter?.Invoke(element, null);
3129
}
3230

33-
public static void Cleanup(this SvgElement element)
31+
public static void RemoveInvisibleAndNonTextElements(this SvgElement element)
3432
{
3533
ArgumentNullException.ThrowIfNull(element);
3634

@@ -40,7 +38,7 @@ public static void Cleanup(this SvgElement element)
4038
if (child.Visibility != "visible" && child is not SvgTextBase)
4139
element.Children.RemoveAt(i);
4240
else
43-
child.Cleanup();
41+
child.RemoveInvisibleAndNonTextElements();
4442
}
4543
}
4644

SvgFileType/Extensions/SvgViewBoxExtensions.cs

Lines changed: 0 additions & 20 deletions
This file was deleted.

SvgFileType/FodyWeavers.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
3-
<ILMerge IncludeAssemblies="Svg|ExCss|Fizzler|resvg.net|BitmapVectorizer|SimplePaletteQuantizer|PaintDotNet.IndirectUI.Fluent" NamespacePrefix="" IncludeResources="\.(resources|dtd|zip)$" CompactMode="0" FullImport="0" />
3+
<ILMerge IncludeAssemblies="Svg|ExCss|resvg.net|BitmapVectorizer|SimplePaletteQuantizer|PaintDotNet.IndirectUI.Fluent" NamespacePrefix="" IncludeResources="\.(resources|dtd|zip)$" CompactMode="0" FullImport="0" />
44
</Weavers>

0 commit comments

Comments
 (0)