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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
|
/*
* 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 System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Serialization;
using UVtools.Core.Extensions;
using UVtools.Core.FileFormats;
using UVtools.Core.Layers;
using UVtools.Core.Objects;
namespace UVtools.Core.Operations;
[Serializable]
public abstract class Operation : BindableBase, IDisposable
{
#region Constants
public const string NotSupportedMessage = "The current printer and/or file format is not compatible with this tool.";
public string NotSupportedTitle => $"{Title} - Unable to run";
#endregion
#region Enums
public enum OperationImportFrom : byte
{
None,
Profile,
Session,
Undo,
}
#endregion
#region Members
private FileFormat _slicerFile = null!;
private Rectangle _originalBoundingRectangle;
private OperationImportFrom _importedFrom = OperationImportFrom.None;
private Rectangle _roi = Rectangle.Empty;
private Point[][]? _maskPoints;
private uint _layerIndexEnd;
private uint _layerIndexStart;
private string? _profileName;
private bool _profileIsDefault;
private LayerRangeSelection _layerRangeSelection = LayerRangeSelection.All;
public const byte ClassNameLength = 9;
#endregion
#region Properties
/// <summary>
/// Gets or sets from where this option got loaded/imported
/// </summary>
[XmlIgnore]
public OperationImportFrom ImportedFrom
{
get => _importedFrom;
set => RaiseAndSetIfChanged(ref _importedFrom, value);
}
[XmlIgnore]
public FileFormat SlicerFile
{
get => _slicerFile;
set
{
if(!RaiseAndSetIfChanged(ref _slicerFile, value)) return;
OriginalBoundingRectangle = _slicerFile.BoundingRectangle;
InitWithSlicerFile();
}
}
[XmlIgnore]
public Rectangle OriginalBoundingRectangle
{
get => _originalBoundingRectangle;
private set => RaiseAndSetIfChanged(ref _originalBoundingRectangle, value);
}
[XmlIgnore]
public object? Tag { get; set; }
/// <summary>
/// Gets the ID name of this operation, this comes from class name with "Operation" removed
/// </summary>
public string Id => GetType().Name.Remove(0, ClassNameLength);
public virtual LayerRangeSelection StartLayerRangeSelection => LayerRangeSelection.All;
/// <summary>
/// Gets the last used layer range selection, returns none if custom
/// </summary>
public LayerRangeSelection LayerRangeSelection
{
get => _layerRangeSelection;
set => RaiseAndSetIfChanged(ref _layerRangeSelection, value);
}
public virtual string LayerRangeString
{
get
{
if (LayerRangeSelection == LayerRangeSelection.None)
{
return $" [Layers: {LayerIndexStart}-{LayerIndexEnd}]";
}
return $" [Layers: {LayerRangeSelection}]";
}
}
/// <summary>
/// Gets if the LayerIndexEnd selector is enabled
/// </summary>
public virtual bool LayerIndexEndEnabled => true;
/// <summary>
/// Gets if this operation should set layer range to the actual layer index on layer preview
/// </summary>
public virtual bool PassActualLayerIndex => false;
/// <summary>
/// Gets if this operation can run in a file open as partial mode
/// </summary>
public virtual bool CanRunInPartialMode => false;
/// <summary>
/// Gets if this operation can make use of ROI
/// </summary>
public virtual bool CanROI => true;
/// <summary>
/// Gets if this operation can make use maskable areas
/// </summary>
public virtual bool CanMask => CanROI;
/// <summary>
/// Gets if this operation can store profiles
/// </summary>
public virtual bool CanHaveProfiles => true;
/// <summary>
/// Gets if this operation supports cancellation
/// </summary>
public virtual bool CanCancel => true;
/// <summary>
/// Gets the icon class to show on the UI
/// </summary>
public virtual string IconClass => null!;
/// <summary>
/// Gets the title of this operation
/// </summary>
public virtual string Title => Id;
/// <summary>
/// Gets a descriptive text of this operation
/// </summary>
public virtual string Description => Id;
/// <summary>
/// Gets the Ok button text
/// </summary>
public virtual string ButtonOkText => Title;
/// <summary>
/// Gets the confirmation text for the operation
/// </summary>
public virtual string ConfirmationText => $"Are you sure you want to {Id}";
/// <summary>
/// Gets the progress window title
/// </summary>
public virtual string ProgressTitle => "Processing items";
/// <summary>
/// Gets the progress action name
/// </summary>
public virtual string ProgressAction => Id;
/// <summary>
/// Gets if this operation have a action text
/// </summary>
public bool HaveAction => !string.IsNullOrEmpty(ProgressAction);
/// <summary>
/// Gets the start layer index where operation will starts in
/// </summary>
public virtual uint LayerIndexStart
{
get => _layerIndexStart;
set
{
if (SlicerFile is not null)
{
value = Math.Min(value, SlicerFile.LastLayerIndex);
}
if (!RaiseAndSetIfChanged(ref _layerIndexStart, value)) return;
RaisePropertyChanged(nameof(LayerRangeCount));
RaisePropertyChanged(nameof(LayerRangeHaveBottoms));
}
}
/// <summary>
/// Gets the end layer index where operation will ends in
/// </summary>
public virtual uint LayerIndexEnd
{
get => _layerIndexEnd;
set
{
if (SlicerFile is not null)
{
value = Math.Min(value, SlicerFile.LastLayerIndex);
}
if(!RaiseAndSetIfChanged(ref _layerIndexEnd, value)) return;
RaisePropertyChanged(nameof(LayerRangeCount));
RaisePropertyChanged(nameof(LayerRangeHaveNormals));
}
}
public bool LayerRangeHaveBottoms => LayerIndexStart < (SlicerFile.FirstNormalLayer?.Index ?? 0);
public bool LayerRangeHaveNormals => LayerIndexEnd >= (SlicerFile.FirstNormalLayer?.Index ?? 0);
public uint LayerRangeCount => (uint)Math.Max(0, (int)LayerIndexEnd - LayerIndexStart + 1);
/// <summary>
/// Gets the name for this profile
/// </summary>
public string? ProfileName
{
get => _profileName;
set => RaiseAndSetIfChanged(ref _profileName, value);
}
public bool ProfileIsDefault
{
get => _profileIsDefault;
set => RaiseAndSetIfChanged(ref _profileIsDefault, value);
}
/// <summary>
/// Gets or sets an ROI to process this operation
/// </summary>
[XmlIgnore]
public Rectangle ROI
{
get => _roi;
set
{
if (!CanROI) return;
RaiseAndSetIfChanged(ref _roi, value);
}
}
public bool HaveROI => !ROI.IsEmpty;
/// <summary>
/// Gets or sets an Mask to process this operation
/// </summary>
[XmlIgnore]
public Point[][]? MaskPoints
{
get => _maskPoints;
set
{
if (!CanMask) return;
if(!RaiseAndSetIfChanged(ref _maskPoints, value)) return;
//if(HaveMask) ROI = Rectangle.Empty;
}
}
public bool HaveMask => _maskPoints is not null && _maskPoints.Length > 0;
public bool HaveROIorMask => HaveROI || HaveMask;
/// <summary>
/// Gets if this operation have been executed once
/// </summary>
[XmlIgnore]
public bool HaveExecuted { get; private set; }
/// <summary>
/// Gets if this operation have validated at least once
/// </summary>
[XmlIgnore]
public bool IsValidated { get; private set; }
#endregion
#region Constructor
protected Operation() { }
protected Operation(FileFormat slicerFile) : this()
{
_slicerFile = slicerFile;
OriginalBoundingRectangle = _slicerFile.BoundingRectangle;
SelectAllLayers();
InitWithSlicerFile();
}
#endregion
#region Methods
public bool CanSpawn => string.IsNullOrWhiteSpace(ValidateSpawn());
/// <summary>
/// Gets if this operation can spawn under the <see cref="SlicerFile"/>
/// </summary>
public virtual string? ValidateSpawn() => null;
/// <summary>
/// Gets if this operation can spawn under the <see cref="SlicerFile"/>
/// </summary>
public bool ValidateSpawn(out string? message)
{
message = ValidateSpawn();
return string.IsNullOrWhiteSpace(message);
}
public virtual string? ValidateInternally()
{
if (!ValidateSpawn(out var message))
{
return message;
}
return null;
}
/// <summary>
/// Validates the operation
/// </summary>
/// <returns>null or empty if validates, otherwise return a string with error message</returns>
public string? Validate()
{
IsValidated = true;
return ValidateInternally();
}
public bool CanValidate()
{
return string.IsNullOrWhiteSpace(Validate());
}
public void SelectAllLayers()
{
LayerIndexStart = 0;
LayerIndexEnd = SlicerFile.LastLayerIndex;
LayerRangeSelection = LayerRangeSelection.All;
}
public void SelectCurrentLayer(uint layerIndex)
{
LayerIndexStart = LayerIndexEnd = layerIndex;
LayerRangeSelection = LayerRangeSelection.Current;
}
public void SelectBottomLayers()
{
LayerIndexStart = 0;
LayerIndexEnd = Math.Max(1, SlicerFile.FirstNormalLayer?.Index ?? 1) - 1u;
LayerRangeSelection = LayerRangeSelection.Bottom;
}
public void SelectNormalLayers()
{
LayerIndexStart = SlicerFile.FirstNormalLayer?.Index ?? 0;
LayerIndexEnd = SlicerFile.LastLayerIndex;
LayerRangeSelection = LayerRangeSelection.Normal;
}
public void SelectFirstLayer()
{
LayerIndexStart = LayerIndexEnd = 0;
LayerRangeSelection = LayerRangeSelection.First;
}
public void SelectLastLayer()
{
LayerIndexStart = LayerIndexEnd = SlicerFile.LastLayerIndex;
LayerRangeSelection = LayerRangeSelection.Last;
}
public void SelectFirstToCurrentLayer(uint currentLayerIndex)
{
LayerIndexStart = 0;
LayerIndexEnd = Math.Min(currentLayerIndex, SlicerFile.LastLayerIndex);
}
public void SelectCurrentToLastLayer(uint currentLayerIndex)
{
LayerIndexStart = Math.Min(currentLayerIndex, SlicerFile.LastLayerIndex);
LayerIndexEnd = SlicerFile.LastLayerIndex;
}
public void SelectLayers(LayerRangeSelection range)
{
switch (range)
{
case LayerRangeSelection.None:
break;
case LayerRangeSelection.All:
SelectAllLayers();
break;
case LayerRangeSelection.Current:
//SelectCurrentLayer();
break;
case LayerRangeSelection.Bottom:
SelectBottomLayers();
break;
case LayerRangeSelection.Normal:
SelectNormalLayers();
break;
case LayerRangeSelection.First:
SelectFirstLayer();
break;
case LayerRangeSelection.Last:
SelectLastLayer();
break;
default:
throw new NotImplementedException();
}
}
/// <summary>
/// Called to init the object when <see cref="SlicerFile"/> changes
/// </summary>
public virtual void InitWithSlicerFile() { }
public void ClearROI()
{
ROI = Rectangle.Empty;
}
public void ClearROIandMasks()
{
ClearROI();
ClearMasks();
}
public void SetROIIfEmpty(Rectangle roi)
{
if (HaveROI) return;
ROI = roi;
}
public Size GetRoiSizeOrDefault() => GetRoiSizeOrDefault(SlicerFile.Resolution);
public Size GetRoiSizeOrDefault(Mat? defaultMat) => defaultMat is null ? GetRoiSizeOrDefault() : GetRoiSizeOrDefault(defaultMat.Size);
public Size GetRoiSizeOrDefault(Rectangle fallbackRectangle) => GetRoiSizeOrDefault(fallbackRectangle.Size);
public Size GetRoiSizeOrDefault(Size fallbackSize)
{
return HaveROI ? _roi.Size : fallbackSize;
}
public Size GetRoiSizeOrVolumeSize() => GetRoiSizeOrVolumeSize(_originalBoundingRectangle.Size);
public Size GetRoiSizeOrVolumeSize(Size fallbackSize)
{
return HaveROI ? _roi.Size : fallbackSize;
}
public Mat GetRoiOrDefault(Mat defaultMat)
{
return HaveROI && defaultMat.Size != _roi.Size ? defaultMat.Roi(_roi) : defaultMat;
}
public Mat GetRoiOrDefault(Mat defaultMat, Rectangle fallbackRoi)
{
if (HaveROI && defaultMat.Size != _roi.Size) return defaultMat.Roi(_roi);
if (fallbackRoi.IsEmpty) return defaultMat;
return defaultMat.Size != fallbackRoi.Size ? defaultMat.Roi(fallbackRoi) : defaultMat;
}
public Mat GetRoiOrVolumeBounds(Mat defaultMat)
{
return GetRoiOrDefault(defaultMat, _originalBoundingRectangle);
}
public void ClearMasks()
{
MaskPoints = null;
}
public void SetMasksIfEmpty(Point[][] points)
{
if (HaveMask) return;
MaskPoints = points;
}
public Mat? GetMask(Mat mat) => GetMask(_maskPoints, mat);
public Mat? GetMask(Point[][]? points, Mat mat)
{
if (!HaveMask) return null;
var mask = mat.CreateMask(points!);
return GetRoiOrDefault(mask);
}
public void ApplyMask(Mat original, Mat result, Mat? mask)
{
if (mask is null) return;
var originalRoi = GetRoiOrDefault(original);
var resultRoi = result;
if (originalRoi.Size != result.Size) // Accept a ROI mat
{
resultRoi = GetRoiOrDefault(result);
}
if (mask.Size != resultRoi.Size) // Accept a full size mask
{
mask = GetRoiOrDefault(mask);
}
using var tempMat = originalRoi.Clone();
resultRoi.CopyTo(tempMat, mask);
tempMat.CopyTo(resultRoi);
}
/// <summary>
/// Gets a mask and apply it
/// </summary>
/// <param name="original">Original unmodified image</param>
/// <param name="result">Result image which will also be modified</param>
public void ApplyMask(Mat original, Mat result)
{
using var mask = GetMask(original);
ApplyMask(original, result, mask);
}
protected virtual bool ExecuteInternally(OperationProgress progress)
{
throw new NotImplementedException();
}
public bool Execute(OperationProgress? progress = null)
{
if (_slicerFile is null) throw new InvalidOperationException($"{Title} can't execute due the lacking of a file parent.");
if (_slicerFile.DecodeType == FileFormat.FileDecodeType.Partial && !CanRunInPartialMode) throw new InvalidOperationException($"The file was open in partial mode and the tool \"{Title}\" is unable to run in this mode.\nPlease reload the file in full mode in order to use this tool.");
if (!IsValidated)
{
var msg = Validate();
if(!string.IsNullOrWhiteSpace(msg)) throw new InvalidOperationException($"{Title} can't execute due some errors:\n{msg}");
}
progress ??= new OperationProgress();
progress.Reset(ProgressAction, LayerRangeCount);
HaveExecuted = true;
var result = ExecuteInternally(progress);
progress.ThrowIfCancellationRequested();
return result;
}
public Task<bool> ExecuteAsync(OperationProgress? progress = null) => Task.Run(() => Execute(progress), progress?.Token ?? default);
public virtual bool Execute(Mat mat, params object[]? arguments)
{
throw new NotImplementedException();
}
public Task<bool> ExecuteAsync(Mat mat, params object[]? arguments) => Task.Run(() => Execute(mat, arguments));
/// <summary>
/// Get the selected layer range in a new array, array index will not match layer index when a range is selected
/// </summary>
/// <returns></returns>
public Layer[] GetSelectedLayerRange()
{
return LayerRangeCount == SlicerFile.LayerCount
? SlicerFile.ToArray()
: SlicerFile.Where((_, layerIndex) => layerIndex >= _layerIndexStart && layerIndex <= _layerIndexEnd).ToArray();
}
/// <summary>
/// Copy this operation base configuration to another operation.
/// Layer range, ROI, Masks
/// </summary>
/// <param name="operation"></param>
public void CopyConfigurationTo(Operation operation)
{
operation.LayerIndexStart = LayerIndexStart;
operation.LayerIndexEnd = LayerIndexEnd;
operation.ROI = ROI;
operation.MaskPoints = MaskPoints;
}
public void Serialize(string path)
{
XmlExtensions.SerializeToFile(this, path);
}
public virtual Operation Clone()
{
var operation = MemberwiseClone() as Operation;
operation!.SlicerFile = _slicerFile;
return operation;
}
public override string ToString()
{
if (!string.IsNullOrEmpty(ProfileName)) return ProfileName;
var result = $"{Title}: {LayerRangeString}";
return result;
}
public virtual void Dispose() { GC.SuppressFinalize(this); }
#endregion
#region Static Methods
public static Operation? Deserialize(string path)
{
if (!File.Exists(path)) return null;
var fileText = File.ReadAllText(path);
var match = Regex.Match(fileText, @"(?:<\/\s*Operation)([a-zA-Z0-9_]+)(?:\s*>)");
if (!match.Success) return null;
if (match.Groups.Count < 1) return null;
var operationName = match.Groups[1].Value;
var baseType = typeof(Operation).FullName;
if (string.IsNullOrWhiteSpace(baseType)) return null;
var classname = baseType + operationName + ", UVtools.Core";
var type = Type.GetType(classname);
if (type is null) return null;
return Deserialize(path, type);
}
public static Operation Deserialize(string path, Type type)
{
var serializer = new XmlSerializer(type);
using var stream = File.OpenRead(path);
var operation = serializer.Deserialize(stream) as Operation;
operation!.ImportedFrom = OperationImportFrom.Session;
return operation;
}
public static Operation Deserialize(string path, Operation operation) => Deserialize(path, operation.GetType());
#endregion
}
|