Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Read Tajima DST embroidery designs (#397)

cre8ive-marketing5bdcbed57618
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 6f69b593..d78e331b 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -7,7 +7,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
|---|---|---|
| ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, MNG, QOI, DDS, PCX, CUR, XPM, XBM, WBMP, PAM, PFM, SGI, Sun Raster, MIFF ↔ each other, and **APNG** (Filee's own reader and writer); HEIC (written with FFmpeg), XCF, camera RAW (LibRaw), DICOM (uncompressed ones by Filee's own reader), Photo CD, OpenEXR, Radiance HDR, EMF/WMF (Windows) and the photo of an iPhone LIVP read |
| Windows Imaging Component | part of Windows (Windows only) | **JPEG XR** (JXR, WDP, HDP; HDR screenshots of Windows) → the images ImageMagick writes, and PDF, ICNS, HEIC and SVG through PNG; HDR tone-mapped to SDR |
-| Vector graphics | built in (Svg.Skia, SkiaSharp, ACadSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, **SVG → DXF** (→ DWG with the CAD engine), **raster images → SVG (tracing)**, PDF-compatible AI → PDF |
+| Vector graphics | built in (Svg.Skia, SkiaSharp, ACadSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, **SVG → DXF** (→ DWG with the CAD engine), **raster images → SVG (tracing)**, PDF-compatible AI → PDF, **Tajima DST embroidery → SVG** (stitches as lines, a palette colour per thread; → PNG, JPG, PDF from there) |
| ICNS | built in | images → ICNS (16–1024 px), ICNS → images |
| PDFsharp | built in (library) | images → PDF, merge, split, page ranges, **compression** (smaller PDFs, see below) |
| PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) |
diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs
index 1ec46736..6456ba3c 100644
--- a/src/Filee.Core/Formats/FormatRegistry.cs
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -67,6 +67,8 @@ public static class FormatRegistry
new("cdr", "CDR", FormatCategory.Vector, ["cdr"], Writable: false),
new("cgm", "CGM", FormatCategory.Vector, ["cgm"], Writable: false),
new("vsd", "VSD", FormatCategory.Vector, ["vsd", "vsdx"], Writable: false),
+ // Tajima embroidery designs: the stitches drawn as lines (issue #397).
+ new("dst", "DST", FormatCategory.Vector, ["dst"], Writable: false),
new("odg", "ODG", FormatCategory.Vector, ["odg"]),
new("fodg", "FODG", FormatCategory.Vector, ["fodg"], Writable: false),
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 4f488dcb..3df95d28 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -112,7 +112,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 32;
+ public const int CurrentSchemaVersion = 33;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 7aff0c84..5a909eda 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -750,6 +750,9 @@ internal static class SettingsMigrations
// v32: logs and script source, Video CD DAT and Workbench archives learn their donuts; custom claims stay put.
if (from < 32)
changed |= LearnExtensions(profiles, out _, ["log", "py", "pac", "bat", "command", "dat", "wbpz"]);
+ // v33: Tajima embroidery designs (.dst) learn the vector donut; custom claims stay put.
+ if (from < 33)
+ changed |= LearnExtensions(profiles, out _, ["dst"]);
return changed;
}
diff --git a/src/Filee.Engines/Vector/DstEmbroidery.cs b/src/Filee.Engines/Vector/DstEmbroidery.cs
new file mode 100644
index 00000000..5b73b7cd
--- /dev/null
+++ b/src/Filee.Engines/Vector/DstEmbroidery.cs
@@ -0,0 +1,94 @@
+// Tajima DST embroidery designs (issue #397) as SVG: the stitches as lines, a colour per thread, for the vector engine
+// to render to PNG, JPG or PDF. A DST file is a 512-byte text header ("LA:" name, stitch count, extents) and 3-byte
+// stitch records. Each record moves the needle by up to ±121 in X and Y (0.1 mm units), the bits standing for ±1, ±3,
+// ±9, ±27 and ±81, and is a stitch, a jump, a colour change, a sequin-mode switch or the end (the same bits as
+// pyembroidery's DstReader). Threads have no colours in DST, so the colour changes cycle through a fixed palette.
+
+using System.Globalization;
+using System.Text;
+
+namespace Filee.Engines.Vector;
+
+internal static class DstEmbroidery
+{
+ private const int HeaderSize = 512;
+
+ private static readonly string[] Palette =
+ ["#1D3557", "#E63946", "#2A9D8F", "#F4A261", "#6A4C93", "#264653", "#E9C46A", "#8D99AE"];
+
+ /// <summary>The stitched runs of each thread, in file order, as (x, y) in 0.1 mm with Y up.</summary>
+ /// <exception cref="InvalidDataException">The file isn't a DST embroidery design (AutoCAD sheet sets use .dst too).</exception>
+ public static List<List<List<(int X, int Y)>>> Read(byte[] data)
+ {
+ if (data.Length < HeaderSize || data[0] != 'L' || data[1] != 'A' || data[2] != ':')
+ throw new InvalidDataException("The file isn't a Tajima DST embroidery design (it has no \"LA:\" header).");
+
+ List<List<List<(int X, int Y)>>> threads = [[]];
+ List<(int X, int Y)>? run = null;
+ int x = 0, y = 0;
+ for (var i = HeaderSize; i + 3 <= data.Length; i += 3)
+ {
+ int b0 = data[i], b1 = data[i + 1], b2 = data[i + 2];
+ if ((b2 & 0xF3) == 0xF3)
+ break; // end
+ var dx = Step(b0, b1, b2, 0x01, 0x02, 0x04, 0x08, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08);
+ var dy = Step(b0, b1, b2, 0x80, 0x40, 0x20, 0x10, 0x80, 0x40, 0x20, 0x10, 0x20, 0x10);
+ x += dx;
+ y += dy;
+ if ((b2 & 0xC3) == 0xC3)
+ {
+ threads.Add([]); // colour change: the next thread
+ run = null;
+ }
+ else if ((b2 & 0x43) == 0x43 || (b2 & 0x83) == 0x83)
+ {
+ run = null; // a jump, or a sequin-mode switch or drop: no thread
+ }
+ else
+ {
+ if (run is null)
+ {
+ // A stitch starts at the needle's last position.
+ run = [(x - dx, y - dy)];
+ threads[^1].Add(run);
+ }
+ run.Add((x, y));
+ }
+ }
+ threads.RemoveAll(t => t.Count == 0);
+ return threads;
+ }
+
+ /// <summary>One axis of a record: the ±1 and ±9 bits of byte 0, ±3 and ±27 of byte 1, ±81 of byte 2.</summary>
+ private static int Step(int b0, int b1, int b2, int p1, int m1, int p9, int m9, int p3, int m3, int p27, int m27, int p81, int m81) =>
+ ((b0 & p1) != 0 ? 1 : 0) - ((b0 & m1) != 0 ? 1 : 0) + ((b0 & p9) != 0 ? 9 : 0) - ((b0 & m9) != 0 ? 9 : 0)
+ + ((b1 & p3) != 0 ? 3 : 0) - ((b1 & m3) != 0 ? 3 : 0) + ((b1 & p27) != 0 ? 27 : 0) - ((b1 & m27) != 0 ? 27 : 0)
+ + ((b2 & p81) != 0 ? 81 : 0) - ((b2 & m81) != 0 ? 81 : 0);
+
+ /// <summary>The design as SVG at its real size (millimetres), each thread a colour of <see cref="Palette"/>.</summary>
+ public static string ToSvg(byte[] data)
+ {
+ var threads = Read(data);
+ var points = threads.SelectMany(t => t).SelectMany(r => r).ToList();
+ if (points.Count == 0)
+ throw new InvalidDataException("The DST file has no stitches.");
+ const int margin = 20; // 2 mm around the design
+ int minX = points.Min(p => p.X) - margin, maxX = points.Max(p => p.X) + margin;
+ int minY = points.Min(p => p.Y) - margin, maxY = points.Max(p => p.Y) + margin;
+ int width = maxX - minX, height = maxY - minY;
+ string Mm(int tenths) => (tenths / 10.0).ToString("0.#", CultureInfo.InvariantCulture);
+
+ var svg = new StringBuilder();
+ svg.Append($"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{Mm(width)}mm\" height=\"{Mm(height)}mm\" viewBox=\"0 0 {width} {height}\">");
+ svg.Append($"<rect width=\"{width}\" height=\"{height}\" fill=\"#FFFFFF\"/>");
+ for (var t = 0; t < threads.Count; t++)
+ {
+ // A thread about 0.4 mm thick; Y flipped, DST counts it upwards.
+ svg.Append($"<g fill=\"none\" stroke=\"{Palette[t % Palette.Length]}\" stroke-width=\"4\" stroke-linecap=\"round\" stroke-linejoin=\"round\">");
+ foreach (var run in threads[t])
+ svg.Append("<polyline points=\"").AppendJoin(' ', run.Select(p => $"{p.X - minX},{maxY - p.Y}")).Append("\"/>");
+ svg.Append("</g>");
+ }
+ return svg.Append("</svg>").ToString();
+ }
+}
diff --git a/src/Filee.Engines/Vector/VectorConverter.cs b/src/Filee.Engines/Vector/VectorConverter.cs
index d23f0fdb..9645e140 100644
--- a/src/Filee.Engines/Vector/VectorConverter.cs
+++ b/src/Filee.Engines/Vector/VectorConverter.cs
@@ -41,6 +41,8 @@ public sealed class VectorConverter : IConverter, IImageTransformer
new("svgz", "dxf"),
// Illustrator files are PDF inside (or PostScript, see ConvertIllustratorAsync).
new("ai", "pdf"),
+ // Embroidery designs: their stitches as lines (DstEmbroidery), PNG / PDF / ... from there.
+ new("dst", "svg"),
// Raster images are traced (other raster formats through PNG, e.g. ICNS; never vector files or documents).
.. ImageEncoder.Readable.Select(source => new ConversionEdge(source, "svg", TraceCost, ImageSourcesOnly: true)),
];
@@ -54,6 +56,7 @@ public sealed class VectorConverter : IConverter, IImageTransformer
("ai", "pdf") => await ConvertIllustratorAsync(step, progress, cancellationToken),
("svg", "svgz") => await Task.Run(() => Compress(step), cancellationToken),
("svgz", "svg") => await Task.Run(() => Decompress(step), cancellationToken),
+ ("dst", "svg") => await Task.Run(() => Embroidery(step), cancellationToken),
(_, "svg") => await Task.Run(() => RasterTracing.Run(step, progress, cancellationToken), cancellationToken),
(_, "dxf") => await Task.Run(() => ToDxf(step, cancellationToken), cancellationToken),
(_, "pdf") => await Task.Run(() => ToPdf(step, cancellationToken), cancellationToken),
@@ -63,6 +66,16 @@ public sealed class VectorConverter : IConverter, IImageTransformer
return written;
}
+ private static IReadOnlyList<string> Embroidery(ConversionStep step)
+ {
+ var svg = DstEmbroidery.ToSvg(File.ReadAllBytes(step.InputPath));
+ var output = step.Output.Allocate("svg");
+ if (output is null)
+ return [];
+ File.WriteAllText(output, svg, new UTF8Encoding(false));
+ return [output];
+ }
+
private static IReadOnlyList<string> ToPdf(ConversionStep step, CancellationToken ct)
{
using var drawing = SvgRenderer.Load(step.InputPath);
diff --git a/tests/Filee.Engines.Tests/DstEmbroideryTests.cs b/tests/Filee.Engines.Tests/DstEmbroideryTests.cs
new file mode 100644
index 00000000..1e0895e7
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DstEmbroideryTests.cs
@@ -0,0 +1,115 @@
+// Tajima DST embroidery designs (issue #397): the stitch records decoded, drawn as SVG and rendered to PNG through the
+// vector engine. The test designs are written here record by record, as embroidery software writes them.
+
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+using Filee.Engines.Vector;
+using ImageMagick;
+
+namespace Filee.Engines.Tests;
+
+public class DstEmbroideryTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ /// <summary>A DST file: the 512-byte header, then one record per (dx, dy, kind), then the end record.</summary>
+ private static byte[] Dst(params (int Dx, int Dy, char Kind)[] records)
+ {
+ var bytes = new List<byte>();
+ var header = "LA:TEST \rST:0000010\rCO: 1\r";
+ bytes.AddRange(header.Select(c => (byte)c));
+ bytes.AddRange(Enumerable.Repeat((byte)' ', 512 - header.Length));
+ foreach (var (dx, dy, kind) in records)
+ {
+ var x = Ternary(dx);
+ var y = Ternary(dy);
+ int b0 = Bits(x[0], 0x01, 0x02) | Bits(x[2], 0x04, 0x08) | Bits(y[0], 0x80, 0x40) | Bits(y[2], 0x20, 0x10);
+ int b1 = Bits(x[1], 0x01, 0x02) | Bits(x[3], 0x04, 0x08) | Bits(y[1], 0x80, 0x40) | Bits(y[3], 0x20, 0x10);
+ int b2 = 0x03 | Bits(x[4], 0x04, 0x08) | Bits(y[4], 0x20, 0x10) | kind switch { 'j' => 0x80, 'c' => 0xC0, 'q' => 0x40, _ => 0 };
+ bytes.AddRange([(byte)b0, (byte)b1, (byte)b2]);
+ }
+ bytes.AddRange([0x00, 0x00, 0xF3]);
+ return [.. bytes];
+
+ static int Bits(int digit, int plus, int minus) => digit > 0 ? plus : digit < 0 ? minus : 0;
+ }
+
+ /// <summary>Balanced ternary digits of <paramref name="value"/> for 1, 3, 9, 27 and 81.</summary>
+ private static int[] Ternary(int value)
+ {
+ var digits = new int[5];
+ for (var k = 0; k < 5; k++)
+ {
+ var r = ((value % 3) + 3) % 3;
+ digits[k] = r == 2 ? -1 : r;
+ value = (value - digits[k]) / 3;
+ }
+ return digits;
+ }
+
+ /// <summary>Two 10 mm squares in two threads, joined by a jump, as a design has them.</summary>
+ private static byte[] TwoSquares() => Dst(
+ (100, 0, 's'), (0, 100, 's'), (-100, 0, 's'), (0, -100, 's'),
+ (121, 0, 'j'), (29, 0, 'c'),
+ (100, 0, 's'), (0, 100, 's'), (-100, 0, 's'), (0, -100, 's'));
+
+ [Fact]
+ public void Stitches_jumps_and_colour_changes_are_decoded()
+ {
+ var threads = DstEmbroidery.Read(TwoSquares());
+
+ Assert.Equal(2, threads.Count);
+ Assert.Equal([(0, 0), (100, 0), (100, 100), (0, 100), (0, 0)], Assert.Single(threads[0]));
+ Assert.Equal([(150, 0), (250, 0), (250, 100), (150, 100), (150, 0)], Assert.Single(threads[1]));
+ }
+
+ [Fact]
+ public void A_sequin_mode_switch_moves_without_a_thread()
+ {
+ var runs = Assert.Single(DstEmbroidery.Read(Dst((10, 0, 's'), (50, 0, 'q'), (10, 0, 's'))));
+
+ Assert.Equal([[(0, 0), (10, 0)], [(60, 0), (70, 0)]], runs);
+ }
+
+ [Fact]
+ public void Every_step_size_is_read_both_ways()
+ {
+ foreach (var d in new[] { 1, -1, 3, -3, 9, -9, 27, -27, 81, -81, 121, -121, 40, -77 })
+ {
+ var run = Assert.Single(Assert.Single(DstEmbroidery.Read(Dst((d, -d, 's')))));
+ Assert.Equal((d, -d), run[^1]);
+ }
+ }
+
+ [Fact]
+ public async Task A_design_becomes_an_svg_and_a_png_of_its_threads()
+ {
+ var path = Path.Combine(fx.NewFolder(), "badge.dst");
+ await File.WriteAllBytesAsync(path, TwoSquares(), TestContext.Current.CancellationToken);
+ Assert.Equal("dst", FormatRegistry.Detect(path)?.Id);
+
+ var svgJob = await fx.ConvertAsync([path], new Preset { TargetFormat = "svg" });
+ Assert.True(svgJob.State == JobState.Completed, string.Join("; ", svgJob.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var svg = await File.ReadAllTextAsync(svgJob.Outputs.Single(), TestContext.Current.CancellationToken);
+ Assert.Contains("width=\"29mm\"", svg); // 25 mm of design and 2 mm on each side
+ Assert.Contains("stroke=\"#1D3557\"", svg);
+ Assert.Contains("stroke=\"#E63946\"", svg);
+
+ var pngJob = await fx.ConvertAsync([path], new Preset { TargetFormat = "png" });
+ Assert.True(pngJob.State == JobState.Completed, string.Join("; ", pngJob.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ using var png = new MagickImage(pngJob.Outputs.Single());
+ Assert.True(png.Width > png.Height); // two squares side by side
+ Assert.True(png.Histogram().Count > 2, "the threads are drawn in colour");
+ }
+
+ [Fact]
+ public async Task An_autocad_sheet_set_with_the_same_extension_fails_with_a_reason()
+ {
+ var path = Path.Combine(fx.NewFolder(), "project.dst");
+ await File.WriteAllTextAsync(path, "<?xml version=\"1.0\"?><AcSmDatabase/>", TestContext.Current.CancellationToken);
+
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "png" });
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Contains("LA:", job.Files[0].ErrorDetail);
+ }
+}