Welcome to mirror list, hosted at ThFree Co, Russian Federation.

GenericZIPFile.cs « FileFormats « UVtools.Core - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 44b4e50fdc24099e9eb8cfde5438f7d2e97c32c8 (plain)
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
/*
 *                     GNU AFFERO GENERAL PUBLIC LICENSE
 *                       Version 3, 19 November 2007
 *  Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 *  Everyone is permitted to copy and distribute verbatim copies
 *  of this license document, but changing it is not allowed.
 */

using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Util;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Xml.Serialization;
using UVtools.Core.Extensions;
using UVtools.Core.Layers;
using UVtools.Core.Operations;

namespace UVtools.Core.FileFormats;

#region Sub Classes

[XmlRoot(ElementName = "Manifest")]
public class GenericZipManifest
{
    public string CreatedBy { get; set; } = About.SoftwareWithVersion;
        
    public string UpdatedBy { get; set; } = About.SoftwareWithVersion;

    public string CreatedDate { get; set; } = DateTime.UtcNow.ToString("u");

    public string LastModifiedDate { get; set; } = DateTime.UtcNow.ToString("u");

    public float LayerHeight { get; set; }

    public ushort ResolutionX { get; set; }

    public ushort ResolutionY { get; set; }

    public float DisplayWidth { get; set; }

    public float DisplayHeight { get; set; }

    public float MachineZ { get; set; }

    public void Update()
    {
        UpdatedBy = About.SoftwareWithVersion;
        LastModifiedDate = DateTime.UtcNow.ToString("u");
    }
}
#endregion

public class GenericZIPFile : FileFormat
{
    #region Constants
    private const string ManifestFileName = "manifest.uvtools";
    #endregion

    #region Properties
    public GenericZipManifest ManifestFile { get; set; } = new ();

    public override FileFormatType FileType => FileFormatType.Archive;

    public override FileExtension[] FileExtensions { get; } = {
        new(typeof(GenericZIPFile), "zip", "Generic Zip / Phrozen Zip")
    };

    public override uint ResolutionX
    {
        get => ManifestFile.ResolutionX;
        set
        {
            ManifestFile.ResolutionX = (ushort) value;
            RaisePropertyChanged();
        }
    }

    public override uint ResolutionY
    {
        get => ManifestFile.ResolutionY;
        set
        {
            ManifestFile.ResolutionY = (ushort)value;
            RaisePropertyChanged();
        }
    }

    public override float DisplayWidth
    {
        get => ManifestFile.DisplayWidth;
        set
        {
            ManifestFile.DisplayWidth = value;
            RaisePropertyChanged();
        }
    }

    public override float DisplayHeight
    {
        get => ManifestFile.DisplayHeight;
        set
        {
            ManifestFile.DisplayHeight = value;
            RaisePropertyChanged();
        }
    }

    public override float MachineZ
    {
        get => ManifestFile.MachineZ > 0 ? ManifestFile.MachineZ : base.MachineZ;
        set
        {
            ManifestFile.MachineZ = value;
            RaisePropertyChanged();
        }
    }

    public override float LayerHeight
    {
        get => ManifestFile.LayerHeight;
        set
        {
            ManifestFile.LayerHeight = Layer.RoundHeight(value);
            RaisePropertyChanged();
        }
    }

    /*public override uint LayerCount
    {
        get => base.LayerCount;
        set => base.LayerCount = ManifestFile.Slices.LayerCount = base.LayerCount;
    }*/

    public override Size[]? ThumbnailsOriginalSize { get; } =
    {
        new(854, 480),
        new(472, 240)
    };


    public override object[] Configs => new object[] { 
        ManifestFile
    };

    #endregion

    #region Constructor
    public GenericZIPFile()
    { }
    #endregion

    #region Methods

    public override bool CanProcess(string? fileFullPath)
    {
        if(!base.CanProcess(fileFullPath)) return false;

        try
        {
            using var zip = ZipFile.Open(fileFullPath!, ZipArchiveMode.Read);
            foreach (var entry in zip.Entries)
            {
                if (entry.Name == ManifestFileName) return true;
                if (entry.Name.EndsWith(".gcode")) return false;
                if (entry.Name.EndsWith(".xml")) return false;
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
            return false;
        }
            

        return true;
    }

    protected override void EncodeInternally(OperationProgress progress)
    {
        using var outputFile = ZipFile.Open(TemporaryOutputFileFullPath, ZipArchiveMode.Create);

        if (Thumbnails is not null)
        {
            if (Thumbnails.Length > 0 && Thumbnails[0] is not null)
            {
                using var stream = outputFile.CreateEntry("preview.png").Open();
                stream.WriteBytes(Thumbnails[0]!.GetPngByes());
                stream.Close();
            }

            if (Thumbnails.Length > 1 && Thumbnails[1] is not null)
            {
                using var stream = outputFile.CreateEntry("preview_cropping.png").Open();
                using var vec = new VectorOfByte();
                stream.WriteBytes(Thumbnails[1]!.GetPngByes());
                stream.Close();
            }
        }

        EncodeLayersInZip(outputFile, IndexStartNumber.One, progress);

        ManifestFile.Update();

        var entry = outputFile.CreateEntry(ManifestFileName);
        using var streamManifest = entry.Open();
        XmlExtensions.Serialize(ManifestFile, streamManifest, XmlExtensions.SettingsIndent, true);
    }

    protected override void DecodeInternally(OperationProgress progress)
    {
        using var inputFile = ZipFile.Open(FileFullPath!, ZipArchiveMode.Read);
        var entry = inputFile.Entries.FirstOrDefault(zipEntry => zipEntry.Name == ManifestFileName);
        if (entry is not null)
        {
            try
            {
                using var stream = entry.Open();
                ManifestFile = XmlExtensions.DeserializeFromStream<GenericZipManifest>(stream);
            }
            catch (Exception)
            {
                // Not required
                //Clear();
                //throw new FileLoadException($"Unable to deserialize '{entry.Name}'\n{e}", FileFullPath);
            }
        }

        uint layerCount = 0;
        foreach (var zipEntry in inputFile.Entries)
        {
            if (!zipEntry.Name.EndsWith(".png")) continue;
            var filename = Path.GetFileNameWithoutExtension(zipEntry.Name);
            if (!filename.All(char.IsDigit)) continue;
            if (!uint.TryParse(filename, out var layerIndex)) continue;
            layerCount = Math.Max(layerCount, layerIndex);
        }

        if (layerCount == 0)
        {
            Clear();
            throw new FileLoadException("Unable to detect layer images in the file", FileFullPath);
        }

        Init(layerCount, DecodeType == FileDecodeType.Partial);
        DecodeLayersFromZip(inputFile, IndexStartNumber.One, progress);
            
        entry = inputFile.GetEntry("preview.png");
        if (entry is not null)
        {
            Thumbnails[0] = new Mat();
            CvInvoke.Imdecode(entry.Open().ToArray(), ImreadModes.AnyColor, Thumbnails[0]);
        }

        entry = inputFile.GetEntry("preview_cropping.png");
        if (entry is not null)
        {
            var count = CreatedThumbnailsCount;
            Thumbnails[count] = new Mat();
            CvInvoke.Imdecode(entry.Open().ToArray(), ImreadModes.AnyColor, Thumbnails[count]);
        }
    }

    protected override void PartialSaveInternally(OperationProgress progress)
    {
        using var outputFile = ZipFile.Open(TemporaryOutputFileFullPath, ZipArchiveMode.Update);
        bool deleted;

        do
        {
            deleted = false;
            foreach (var zipEntry in outputFile.Entries)
            {
                if (zipEntry.Name != ManifestFileName) continue;
                zipEntry.Delete();
                deleted = true;
                break;
            }
        } while (deleted);

        ManifestFile.Update();
            
        var entry = outputFile.CreateEntry(ManifestFileName);
        using var stream = entry.Open();

        XmlExtensions.Serialize(ManifestFile, stream, XmlExtensions.SettingsIndent, true);
    }
    #endregion
}