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

MainWindow.PixelEditor.cs « UVtools.WPF - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: deb32e5f30dcb9dd07afb2ef5cd501c93c3d6aac (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
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
/*
 *                     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 System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media.Imaging;
using Avalonia.Threading;
using DynamicData;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using MessageBox.Avalonia.Enums;
using SkiaSharp;
using UVtools.Core;
using UVtools.Core.Extensions;
using UVtools.Core.PixelEditor;
using UVtools.WPF.Extensions;

namespace UVtools.WPF
{
    public partial class MainWindow
    {
        public ObservableCollection<PixelOperation> Drawings { get; } = new ObservableCollection<PixelOperation>();
        public DataGrid DrawingsGrid;
        private int _selectedPixelOperationTabIndex;

        public PixelDrawing DrawingPixelDrawing { get; } = new PixelDrawing();
        public PixelText DrawingPixelText { get; } = new PixelText();
        public PixelEraser DrawingPixelEraser { get; } = new PixelEraser();
        public PixelSupport DrawingPixelSupport { get; } = new PixelSupport();
        public PixelDrainHole DrawingPixelDrainHole { get; } = new PixelDrainHole();

        public int SelectedPixelOperationTabIndex
        {
            get => _selectedPixelOperationTabIndex;
            set => RaiseAndSetIfChanged(ref _selectedPixelOperationTabIndex, value);
        }

        public void InitPixelEditor()
        {
            DrawingsGrid = this.FindControl<DataGrid>("DrawingsGrid");
            DrawingsGrid.KeyUp += DrawingsGridOnKeyUp;
            DrawingsGrid.SelectionChanged += DrawingsGridOnSelectionChanged;
            DrawingsGrid.CellPointerPressed += DrawingsGridOnCellPointerPressed;
        }

        private void DrawingsGridOnSelectionChanged(object? sender, SelectionChangedEventArgs e)
        {
            if (!(DrawingsGrid.SelectedItem is PixelOperation operation))
            {
                ShowLayer();
                return;
            }

            Point location = GetTransposedPoint(operation.Location, false);

            if (Settings.LayerPreview.ZoomIssues ^ (_globalModifiers & KeyModifiers.Alt) != 0)
            {
                CenterLayerAt(new Rectangle(location, operation.Size), AppSettings.LockedZoomLevel);
            }
            else
            {
                CenterLayerAt(location);
            }


            ForceUpdateActualLayer(operation.LayerIndex);
        }

        private void DrawingsGridOnCellPointerPressed(object? sender, DataGridCellPointerPressedEventArgs e)
        {
            if (e.PointerPressedEventArgs.ClickCount == 2) return;
            if (!(DrawingsGrid.SelectedItem is LayerIssue issue)) return;
            // Double clicking an issue will center and zoom into the 
            // selected issue. Left click on an issue will zoom to fit.

            var pointer = e.PointerPressedEventArgs.GetCurrentPoint(DrawingsGrid);

            if (pointer.Properties.IsRightButtonPressed)
            {
                ZoomToFit();
                return;
            }

        }

        private void DrawingsGridOnKeyUp(object? sender, KeyEventArgs e)
        {
            
            switch (e.Key)
            {
                case Key.Escape:
                    DrawingsGrid.SelectedItems.Clear();
                    break;
                case Key.Multiply:
                    var selectedItems = DrawingsGrid.SelectedItems.OfType<PixelOperation>().ToList();
                    DrawingsGrid.SelectedItems.Clear();
                    foreach (PixelOperation item in Drawings)
                    {
                        if (!selectedItems.Contains(item))
                            DrawingsGrid.SelectedItems.Add(item);
                    }


                    break;
                case Key.Delete:
                    OnClickDrawingRemove();
                    break;
            }
        }

        public void OnClickDrawingRemove()
        {
            if (DrawingsGrid.SelectedItems.Count == 0) return;
            Drawings.RemoveMany(DrawingsGrid.SelectedItems.Cast<PixelOperation>());
            ShowLayer();
        }

        public async void OnClickDrawingClear()
        {
            if (Drawings.Count == 0) return;
            if (await this.MessageBoxQuestion($"Are you sure you want to clear {Drawings.Count} operations?",
                "Clear pixel editor operations?") != ButtonResult.Yes) return;
            Drawings.Clear();
            ShowLayer();
        }

        void DrawPixel(bool isAdd, Point location, KeyModifiers keyModifiers)
        {
            //Stopwatch sw = Stopwatch.StartNew();
            //var point = pbLayer.PointToImage(location);

            Point realLocation = GetTransposedPoint(location);

            if ((keyModifiers & KeyModifiers.Control) != 0)
            {
                var removeItems = Drawings.Where(item =>
                {
                    Rectangle rect = new Rectangle(item.Location, item.Size);
                    rect.X -= item.Size.Width / 2;
                    rect.Y -= item.Size.Height / 2;
                    return rect.Contains(realLocation);
                });
                if (removeItems.Any())
                {
                    Drawings.RemoveMany(removeItems);
                    ShowLayer();
                }
                
                return;
            }

            WriteableBitmap bitmap = (WriteableBitmap)LayerImageBox.Image;
            //var context = CreateRenderTarget().CreateDrawingContext(bitmap);


            //Bitmap bmp = pbLayer.Image as Bitmap;
            if (SelectedPixelOperationTabIndex == (byte)PixelOperation.PixelOperationType.Drawing)
            {
                uint minLayer = Math.Max(0, _actualLayer - DrawingPixelDrawing.LayersBelow);
                uint maxLayer = Math.Min(SlicerFile.LayerCount - 1, _actualLayer + DrawingPixelDrawing.LayersAbove);
                for (uint layerIndex = minLayer; layerIndex <= maxLayer; layerIndex++)
                {
                    var operationDrawing = new PixelDrawing(layerIndex, realLocation, DrawingPixelDrawing.LineType,
                        DrawingPixelDrawing.BrushShape, DrawingPixelDrawing.BrushSize, DrawingPixelDrawing.Thickness, DrawingPixelDrawing.RemovePixelBrightness, DrawingPixelDrawing.PixelBrightness, isAdd);

                    //if (PixelHistory.Contains(operation)) continue;
                    Drawings.Add(operationDrawing);

                    if (layerIndex == _actualLayer)
                    {
                        var color = isAdd
                            ? Settings.PixelEditor.AddPixelColor
                            : Settings.PixelEditor.RemovePixelColor;

                        if (operationDrawing.BrushSize == 1)
                        {
                            unsafe
                            {
                                using var framebuffer = bitmap.Lock();
                                var data = (uint*)framebuffer.Address.ToPointer();
                                data[bitmap.GetPixelPos(location)] =
                                    color.ToUint32();
                            }
                            
                            LayerImageBox.InvalidateArrange();
                               // LayerCache.ImageBgr.SetByte(operationDrawing.Location.X, operationDrawing.Location.Y,
                                 //   new[] { color.B, color.G, color.R });
                            continue;
                        }

                        switch (operationDrawing.BrushShape)
                        {
                            case PixelDrawing.BrushShapeType.Rectangle:

                                int shiftPos = operationDrawing.BrushSize / 2;
                                LayerCache.Canvas.DrawRect(location.X - shiftPos, location.Y - shiftPos, 
                                    operationDrawing.BrushSize, 
                                    operationDrawing.BrushSize,
                                    new SKPaint
                                    {
                                        IsAntialias = operationDrawing.LineType == LineType.AntiAlias,
                                        Color = new SKColor(color.ToUint32()),
                                        IsStroke = operationDrawing.Thickness >= 0,
                                        StrokeWidth = operationDrawing.Thickness
                                    } );
                                /*CvInvoke.Rectangle(LayerCache.ImageBgr, GetTransposedRectangle(operationDrawing.Rectangle),
                                    new MCvScalar(color.B, color.G, color.R), operationDrawing.Thickness,
                                    operationDrawing.LineType);*/
                                break;
                            case PixelDrawing.BrushShapeType.Circle:

                               
                                LayerCache.Canvas.DrawCircle(location.X, location.Y, operationDrawing.BrushSize / 2f,
                                    new SKPaint
                                    {
                                        IsAntialias = operationDrawing.LineType == LineType.AntiAlias,
                                        Color = new SKColor(color.ToUint32()),
                                        IsStroke = operationDrawing.Thickness >= 0,
                                        StrokeWidth = operationDrawing.Thickness
                                    });

                                /*CvInvoke.Circle(LayerCache.ImageBgr, location, operationDrawing.BrushSize / 2,
                                    new MCvScalar(color.B, color.G, color.R), operationDrawing.Thickness,
                                    operationDrawing.LineType);*/
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }
                        LayerImageBox.InvalidateVisual();
                        //RefreshLayerImage();
                    }
                }
            }
            else if (SelectedPixelOperationTabIndex == (byte)PixelOperation.PixelOperationType.Text)
            {
                if (string.IsNullOrEmpty(DrawingPixelText.Text) || DrawingPixelText.FontScale < 0.2) return;

                uint minLayer = Math.Max(0, ActualLayer - DrawingPixelText.LayersBelow);
                uint maxLayer = Math.Min(SlicerFile.LayerCount - 1,
                    ActualLayer + DrawingPixelText.LayersAbove);
                for (uint layerIndex = minLayer; layerIndex <= maxLayer; layerIndex++)
                {
                    var operationText = new PixelText(layerIndex, realLocation, DrawingPixelText.LineType,
                        DrawingPixelText.Font, DrawingPixelText.FontScale, DrawingPixelText.Thickness,
                        DrawingPixelText.Text, DrawingPixelText.Mirror, DrawingPixelText.RemovePixelBrightness, DrawingPixelText.PixelBrightness, isAdd);

                    //if (PixelHistory.Contains(operation)) continue;
                    //PixelHistory.Add(operation);
                    Drawings.Add(operationText);
                    
                    /*var color = isAdd
                        ? Settings.PixelEditor.AddPixelColor : Settings.PixelEditor.RemovePixelColor;

                    if (layerIndex == _actualLayer)
                    {
                        CvInvoke.PutText(LayerCache.ImageBgr, operationText.Text, location,
                            operationText.Font, operationText.FontScale, new MCvScalar(color.B, color.G, color.R),
                            operationText.Thickness, operationText.LineType, operationText.Mirror);
                        RefreshLayerImage();
                    }*/
                }

                ShowLayer();
                return;
            }
            else if (SelectedPixelOperationTabIndex == (byte)PixelOperation.PixelOperationType.Eraser)
            {
                if (LayerCache.Image.GetByte(realLocation) < 10) return;
                uint minLayer = Math.Max(0, ActualLayer - DrawingPixelEraser.LayersBelow);
                uint maxLayer = Math.Min(SlicerFile.LayerCount - 1,
                    ActualLayer + DrawingPixelEraser.LayersAbove);
                for (uint layerIndex = minLayer; layerIndex <= maxLayer; layerIndex++)
                {
                    var operationEraser = new PixelEraser(layerIndex, realLocation, DrawingPixelEraser.PixelBrightness);

                    //if (PixelHistory.Contains(operation)) continue;
                    Drawings.Add(operationEraser);

                    /*if (layerIndex == _actualLayer)
                    {
                        for (int i = 0; i < LayerCache.LayerContours.Size; i++)
                        {
                            if (CvInvoke.PointPolygonTest(LayerCache.LayerContours[i], operationEraser.Location, false) >= 0)
                            {
                                CvInvoke.DrawContours(LayerCache.ImageBgr, LayerCache.LayerContours, i,
                                    new MCvScalar(Settings.PixelEditor.RemovePixelColor.B, Settings.PixelEditor.RemovePixelColor.G, Settings.PixelEditor.RemovePixelColor.R), -1);
                                RefreshLayerImage();
                                break;
                            }
                        }
                    }*/
                }

                ShowLayer();
                return;
            }
            else if (SelectedPixelOperationTabIndex == (byte)PixelOperation.PixelOperationType.Supports)
            {
                if (_actualLayer == 0) return;
                var operationSupport = new PixelSupport(ActualLayer, realLocation,
                    DrawingPixelSupport.TipDiameter, DrawingPixelSupport.PillarDiameter,
                    DrawingPixelSupport.BaseDiameter, DrawingPixelSupport.PixelBrightness);

                //if (PixelHistory.Contains(operation)) return;
                Drawings.Add(operationSupport);

                CvInvoke.Circle(LayerCache.ImageBgr, location, operationSupport.TipDiameter / 2,
                    new MCvScalar(Settings.PixelEditor.SupportsColor.B, Settings.PixelEditor.SupportsColor.G, Settings.PixelEditor.SupportsColor.R), -1);
                RefreshLayerImage();
            }
            else if (SelectedPixelOperationTabIndex == (byte)PixelOperation.PixelOperationType.DrainHole)
            {
                if (_actualLayer == 0) return;
                var operationDrainHole = new PixelDrainHole(ActualLayer, realLocation, DrawingPixelDrainHole.Diameter);

                //if (PixelHistory.Contains(operation)) return;
                Drawings.Add(operationDrainHole);

                CvInvoke.Circle(LayerCache.ImageBgr, location, operationDrainHole.Diameter / 2,
                    new MCvScalar(Settings.PixelEditor.DrainHoleColor.B, Settings.PixelEditor.DrainHoleColor.G, Settings.PixelEditor.DrainHoleColor.R), -1);
                RefreshLayerImage();
            }
            else
            {
                throw new NotImplementedException("Missing pixel operation");
            }
        }

        public async void DrawModifications(bool exitEditor)
        {
            if (Drawings.Count == 0)
            {
                if (exitEditor && !ReferenceEquals(LastSelectedTabItem, TabPixelEditor))
                {
                    SelectedTabItem = LastSelectedTabItem;
                }

                return;
            }

            ButtonResult result;

            if (exitEditor)
            {
                result = await this.MessageBoxQuestion(
                    "There are edit operations that have not been applied.  " +
                    "Would you like to apply all operations before closing the editor?",
                    "Closing image editor?", ButtonEnum.YesNoCancel);
            }
            else
            {

                result = await this.MessageBoxQuestion(
                    "Are you sure you want to apply all operations?",
                    "Apply image editor changes?");

                // For the "apply" case, We aren't exiting the editor, so map "No" to "Cancel" here
                // in order to prevent pixel history from being cleared.
                result = result == ButtonResult.No ? ButtonResult.Cancel : ButtonResult.Yes;
            }

            if (result == ButtonResult.Cancel)
            {
                IsPixelEditorActive = true;
                return;
            }

            if (result == ButtonResult.Yes)
            {
                IsGUIEnabled = false;

                Clipboard.Snapshot();

                var task = await Task.Factory.StartNew(async () =>
                {
                    ShowProgressWindow("Drawing pixels");
                    try
                    {
                        SlicerFile.LayerManager.DrawModifications(Drawings, ProgressWindow.RestartProgress());
                    }
                    catch (OperationCanceledException)
                    {

                    }
                    catch (Exception ex)
                    {
                        await Dispatcher.UIThread.InvokeAsync(async () =>
                        {
                            await this.MessageBoxError(ex.ToString(), "Drawing operation failed!");
                        });
                    }

                    return false;
                });

                IsGUIEnabled = true;

                Clipboard.Clip($"Draw {Drawings.Count} modifications");

                if (Settings.PixelEditor.PartialUpdateIslandsOnEditing)
                {
                    List<uint> whiteListLayers = new List<uint>();
                    foreach (var item in Drawings)
                    {
                        /*if (item.OperationType != PixelOperation.PixelOperationType.Drawing &&
                            item.OperationType != PixelOperation.PixelOperationType.Text &&
                            item.OperationType != PixelOperation.PixelOperationType.Eraser &&
                            item.OperationType != PixelOperation.PixelOperationType.Supports) continue;*/
                        if (!whiteListLayers.Contains(item.LayerIndex))
                            whiteListLayers.Add(item.LayerIndex);

                        uint nextLayer = item.LayerIndex + 1;
                        if (nextLayer < SlicerFile.LayerCount &&
                            !whiteListLayers.Contains(nextLayer))
                        {
                            whiteListLayers.Add(nextLayer);
                        }
                    }

                    await UpdateIslandsOverhangs(whiteListLayers);
                }
            }

            Drawings.Clear();
            ShowLayer();

            if (exitEditor || (Settings.PixelEditor.CloseEditorOnApply && result == ButtonResult.Yes))
            {
                IsPixelEditorActive = false;
                if (!ReferenceEquals(LastSelectedTabItem, TabPixelEditor))
                {
                    SelectedTabItem = LastSelectedTabItem;
                }
            }

            CanSave = true;
        }
    }
}