瀏覽代碼

Fixed warnings after the merge

ArtemK123 4 年之前
父節點
當前提交
00dac5a2a6

+ 1 - 0
Custom.ruleset

@@ -8,5 +8,6 @@
     <Rule Id="SA1101" Action="None" />
     <Rule Id="SA1101" Action="None" />
     <Rule Id="SA1413" Action="None" />
     <Rule Id="SA1413" Action="None" />
     <Rule Id="SA1633" Action="None" />
     <Rule Id="SA1633" Action="None" />
+    <Rule Id="SA1310" Action="None" />
   </Rules>
   </Rules>
 </RuleSet>
 </RuleSet>

+ 15 - 15
PixiEditor.UpdateInstaller/ViewModelMain.cs

@@ -5,15 +5,27 @@ using PixiEditor.UpdateModule;
 namespace PixiEditor.UpdateInstaller
 namespace PixiEditor.UpdateInstaller
 {
 {
     public class ViewModelMain : ViewModelBase
     public class ViewModelMain : ViewModelBase
-    {
+    {
+        private float progressValue;
+
+        public ViewModelMain()
+        {
+            Current = this;
+
+            string updateDirectory = Path.GetDirectoryName(Extensions.GetExecutablePath());
+
+#if DEBUG
+            updateDirectory = Environment.GetCommandLineArgs()[1];
+#endif
+            UpdateDirectory = updateDirectory;
+        }
+
         public ViewModelMain Current { get; private set; }
         public ViewModelMain Current { get; private set; }
 
 
         public UpdateModule.UpdateInstaller Installer { get; set; }
         public UpdateModule.UpdateInstaller Installer { get; set; }
 
 
         public string UpdateDirectory { get; private set; }
         public string UpdateDirectory { get; private set; }
 
 
-        private float progressValue;
-
         public float ProgressValue
         public float ProgressValue
         {
         {
             get => progressValue;
             get => progressValue;
@@ -24,18 +36,6 @@ namespace PixiEditor.UpdateInstaller
             }
             }
         }
         }
 
 
-        public ViewModelMain()
-        {
-            Current = this;
-
-            string updateDirectory = Path.GetDirectoryName(Extensions.GetExecutablePath());
-
-#if DEBUG
-            updateDirectory = Environment.GetCommandLineArgs()[1];
-#endif
-            UpdateDirectory = updateDirectory;
-        }
-
         public void InstallUpdate()
         public void InstallUpdate()
         {
         {
             string[] files = Directory.GetFiles(UpdateDownloader.DownloadLocation, "update-*.zip");
             string[] files = Directory.GetFiles(UpdateDownloader.DownloadLocation, "update-*.zip");

+ 11 - 10
PixiEditor.UpdateModule/UpdateInstaller.cs

@@ -8,11 +8,18 @@ namespace PixiEditor.UpdateModule
     public class UpdateInstaller
     public class UpdateInstaller
     {
     {
         public const string TargetDirectoryName = "UpdateFiles";
         public const string TargetDirectoryName = "UpdateFiles";
-        public static string UpdateFilesPath = Path.Join(UpdateDownloader.DownloadLocation, TargetDirectoryName);
 
 
+        private float progress = 0;
+
+        public UpdateInstaller(string archiveFileName, string targetDirectory)
+        {
+            ArchiveFileName = archiveFileName;
+            TargetDirectory = targetDirectory;
+        }
+
         public event EventHandler<UpdateProgressChangedEventArgs> ProgressChanged;
         public event EventHandler<UpdateProgressChangedEventArgs> ProgressChanged;
 
 
-        private float progress = 0;
+        public static string UpdateFilesPath { get; set; } = Path.Join(UpdateDownloader.DownloadLocation, TargetDirectoryName);
 
 
         public float Progress
         public float Progress
         {
         {
@@ -28,12 +35,6 @@ namespace PixiEditor.UpdateModule
 
 
         public string TargetDirectory { get; set; }
         public string TargetDirectory { get; set; }
 
 
-        public UpdateInstaller(string archiveFileName, string targetDirectory)
-        {
-            ArchiveFileName = archiveFileName;
-            TargetDirectory = targetDirectory;
-        }
-
         public void Install()
         public void Install()
         {
         {
             var processes = Process.GetProcessesByName("PixiEditor");
             var processes = Process.GetProcessesByName("PixiEditor");
@@ -43,7 +44,7 @@ namespace PixiEditor.UpdateModule
             }
             }
 
 
             ZipFile.ExtractToDirectory(ArchiveFileName, UpdateFilesPath, true);
             ZipFile.ExtractToDirectory(ArchiveFileName, UpdateFilesPath, true);
-            Progress = 25; //25% for unzip
+            Progress = 25; // 25% for unzip
             string dirWithFiles = Directory.GetDirectories(UpdateFilesPath)[0];
             string dirWithFiles = Directory.GetDirectories(UpdateFilesPath)[0];
             string[] files = Directory.GetFiles(dirWithFiles);
             string[] files = Directory.GetFiles(dirWithFiles);
             CopyFilesToDestination(files);
             CopyFilesToDestination(files);
@@ -59,7 +60,7 @@ namespace PixiEditor.UpdateModule
 
 
         private void CopyFilesToDestination(string[] files)
         private void CopyFilesToDestination(string[] files)
         {
         {
-            float fileCopiedVal = 74f / files.Length; //74% is reserved for copying
+            float fileCopiedVal = 74f / files.Length; // 74% is reserved for copying
             string destinationDir = TargetDirectory;
             string destinationDir = TargetDirectory;
             foreach (string file in files)
             foreach (string file in files)
             {
             {

+ 31 - 30
PixiEditor/Helpers/GlobalMouseHook.cs

@@ -8,16 +8,21 @@ using System.Windows.Input;
 
 
 namespace PixiEditor.Helpers
 namespace PixiEditor.Helpers
 {
 {
+    public delegate void MouseUpEventHandler(object sender, Point p, MouseButton button);
+
     // see https://stackoverflow.com/questions/22659925/how-to-capture-mouseup-event-outside-the-wpf-window
     // see https://stackoverflow.com/questions/22659925/how-to-capture-mouseup-event-outside-the-wpf-window
     [ExcludeFromCodeCoverage]
     [ExcludeFromCodeCoverage]
     public static class GlobalMouseHook
     public static class GlobalMouseHook
-    {
-        private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
-
+    {
+        private const int WH_MOUSE_LL = 14;
+        private const int WM_LBUTTONUP = 0x0202;
+        private const int WM_MBUTTONUP = 0x0208;
+        private const int WM_RBUTTONUP = 0x0205;
+
         private static int mouseHookHandle;
         private static int mouseHookHandle;
         private static HookProc mouseDelegate;
         private static HookProc mouseDelegate;
 
 
-        private static event MouseUpEventHandler MouseUp;
+        private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
 
 
         public static event MouseUpEventHandler OnMouseUp
         public static event MouseUpEventHandler OnMouseUp
         {
         {
@@ -34,6 +39,8 @@ namespace PixiEditor.Helpers
             }
             }
         }
         }
 
 
+        private static event MouseUpEventHandler MouseUp;
+
         public static void RaiseMouseUp()
         public static void RaiseMouseUp()
         {
         {
             MouseUp?.Invoke(default, default, default);
             MouseUp?.Invoke(default, default, default);
@@ -91,29 +98,8 @@ namespace PixiEditor.Helpers
             return CallNextHookEx(mouseHookHandle, nCode, wParam, lParam);
             return CallNextHookEx(mouseHookHandle, nCode, wParam, lParam);
         }
         }
 
 
-        private const int WH_MOUSE_LL = 14;
-        private const int WM_LBUTTONUP = 0x0202;
-        private const int WM_MBUTTONUP = 0x0208;
-        private const int WM_RBUTTONUP = 0x0205;
-
-        [StructLayout(LayoutKind.Sequential)]
-        private struct POINT
-        {
-            public int X;
-            public int Y;
-        }
-
-        [StructLayout(LayoutKind.Sequential)]
-        private struct MSLLHOOKSTRUCT
-        {
-            public POINT Pt;
-            public uint MouseData;
-            public uint Flags;
-            public uint Time;
-            public IntPtr DwExtraInfo;
-        }
-
-        [DllImport("user32.dll",
+        [DllImport(
+            "user32.dll",
             CharSet = CharSet.Auto,
             CharSet = CharSet.Auto,
             CallingConvention = CallingConvention.StdCall,
             CallingConvention = CallingConvention.StdCall,
             SetLastError = true)]
             SetLastError = true)]
@@ -133,8 +119,23 @@ namespace PixiEditor.Helpers
         private static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);
         private static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);
 
 
         [DllImport("kernel32.dll")]
         [DllImport("kernel32.dll")]
-        private static extern IntPtr GetModuleHandle(string name);
-    }
+        private static extern IntPtr GetModuleHandle(string name);
+
+        [StructLayout(LayoutKind.Sequential)]
+        private struct POINT
+        {
+            public int X;
+            public int Y;
+        }
 
 
-    public delegate void MouseUpEventHandler(object sender, Point p, MouseButton button);
+        [StructLayout(LayoutKind.Sequential)]
+        private struct MSLLHOOKSTRUCT
+        {
+            public POINT Pt;
+            public uint MouseData;
+            public uint Flags;
+            public uint Time;
+            public IntPtr DwExtraInfo;
+        }
+    }
 }
 }

+ 74 - 76
PixiEditor/Models/Controllers/BitmapManager.cs

@@ -18,7 +18,27 @@ using PixiEditor.Models.Tools.ToolSettings.Settings;
 namespace PixiEditor.Models.Controllers
 namespace PixiEditor.Models.Controllers
 {
 {
     public class BitmapManager : NotifyableObject
     public class BitmapManager : NotifyableObject
-    {
+    {
+        private Document activeDocument;
+        private Layer previewLayer;
+        private Tool selectedTool;
+
+        public BitmapManager()
+        {
+            MouseController = new MouseMovementController();
+            MouseController.StartedRecordingChanges += MouseController_StartedRecordingChanges;
+            MouseController.MousePositionChanged += Controller_MousePositionChanged;
+            MouseController.StoppedRecordingChanges += MouseController_StoppedRecordingChanges;
+            MouseController.OnMouseDown += MouseController_OnMouseDown;
+            MouseController.OnMouseUp += MouseController_OnMouseUp;
+            BitmapOperations = new BitmapOperationsUtility(this);
+            ReadonlyToolUtility = new ReadonlyToolUtility();
+        }
+
+        public event EventHandler<LayersChangedEventArgs> LayersChanged;
+
+        public event EventHandler<DocumentChangedEventArgs> DocumentChanged;
+
         public MouseMovementController MouseController { get; set; }
         public MouseMovementController MouseController { get; set; }
 
 
         public Tool SelectedTool
         public Tool SelectedTool
@@ -73,37 +93,14 @@ namespace PixiEditor.Models.Controllers
                 RaisePropertyChanged("ActiveDocument");
                 RaisePropertyChanged("ActiveDocument");
                 DocumentChanged?.Invoke(this, new DocumentChangedEventArgs(value));
                 DocumentChanged?.Invoke(this, new DocumentChangedEventArgs(value));
             }
             }
-        }
-
-        private Document activeDocument;
-
-        private Layer previewLayer;
-        private Tool selectedTool;
-
-        public BitmapManager()
-        {
-            MouseController = new MouseMovementController();
-            MouseController.StartedRecordingChanges += MouseController_StartedRecordingChanges;
-            MouseController.MousePositionChanged += Controller_MousePositionChanged;
-            MouseController.StoppedRecordingChanges += MouseController_StoppedRecordingChanges;
-            MouseController.OnMouseDown += MouseController_OnMouseDown;
-            MouseController.OnMouseUp += MouseController_OnMouseUp;
-            BitmapOperations = new BitmapOperationsUtility(this);
-            ReadonlyToolUtility = new ReadonlyToolUtility();
-        }
-
-        public event EventHandler<LayersChangedEventArgs> LayersChanged;
+        }
 
 
-        public event EventHandler<DocumentChangedEventArgs> DocumentChanged;
-
-        private void MouseController_OnMouseDown(object sender, MouseEventArgs e)
-        {
-            SelectedTool.OnMouseDown(e);
-        }
-
-        private void MouseController_OnMouseUp(object sender, MouseEventArgs e)
+        /// <summary>
+        ///     Returns if tool is BitmapOperationTool.
+        /// </summary>
+        public static bool IsOperationTool(Tool tool)
         {
         {
-            SelectedTool.OnMouseUp(e);
+            return tool is BitmapOperationTool;
         }
         }
 
 
         public void SetActiveTool(Tool tool)
         public void SetActiveTool(Tool tool)
@@ -171,6 +168,46 @@ namespace PixiEditor.Models.Controllers
             }
             }
         }
         }
 
 
+        public void ExecuteTool(Coordinates newPosition, bool clickedOnCanvas)
+        {
+            if (SelectedTool.CanStartOutsideCanvas || clickedOnCanvas)
+            {
+                if (IsOperationTool(SelectedTool))
+                {
+                    BitmapOperations.ExecuteTool(newPosition, MouseController.LastMouseMoveCoordinates.ToList(), (BitmapOperationTool)SelectedTool);
+                }
+                else
+                {
+                    ReadonlyToolUtility.ExecuteTool(MouseController.LastMouseMoveCoordinates.ToArray(), (ReadonlyTool)SelectedTool);
+                }
+            }
+        }
+
+        public void GeneratePreviewLayer()
+        {
+            if (ActiveDocument != null)
+            {
+                PreviewLayer = new Layer("_previewLayer")
+                {
+                    MaxWidth = ActiveDocument.Width,
+                    MaxHeight = ActiveDocument.Height
+                };
+            }
+        }
+
+        public WriteableBitmap GetCombinedLayersBitmap()
+        {
+            return BitmapUtils.CombineLayers(ActiveDocument.Layers.Where(x => x.IsVisible).ToArray(), ActiveDocument.Width, ActiveDocument.Height);
+        }
+
+        /// <summary>
+        ///     Returns if selected tool is BitmapOperationTool.
+        /// </summary>
+        public bool IsOperationTool()
+        {
+            return IsOperationTool(SelectedTool);
+        }
+
         private void Controller_MousePositionChanged(object sender, MouseMovementEventArgs e)
         private void Controller_MousePositionChanged(object sender, MouseMovementEventArgs e)
         {
         {
             SelectedTool.OnMouseMove(new MouseEventArgs(Mouse.PrimaryDevice, (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds()));
             SelectedTool.OnMouseMove(new MouseEventArgs(Mouse.PrimaryDevice, (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds()));
@@ -182,23 +219,16 @@ namespace PixiEditor.Models.Controllers
             {
             {
                 HighlightPixels(e.NewPosition);
                 HighlightPixels(e.NewPosition);
             }
             }
+        }
+
+        private void MouseController_OnMouseDown(object sender, MouseEventArgs e)
+        {
+            SelectedTool.OnMouseDown(e);
         }
         }
 
 
-        public void ExecuteTool(Coordinates newPosition, bool clickedOnCanvas)
+        private void MouseController_OnMouseUp(object sender, MouseEventArgs e)
         {
         {
-            if (SelectedTool.CanStartOutsideCanvas || clickedOnCanvas)
-            {
-                if (IsOperationTool(SelectedTool))
-                {
-                    BitmapOperations.ExecuteTool(newPosition,
-                        MouseController.LastMouseMoveCoordinates.ToList(), (BitmapOperationTool)SelectedTool);
-                }
-                else
-                {
-                    ReadonlyToolUtility.ExecuteTool(MouseController.LastMouseMoveCoordinates.ToArray(),
-                        (ReadonlyTool)SelectedTool);
-                }
-            }
+            SelectedTool.OnMouseUp(e);
         }
         }
 
 
         private bool IsDraggingViewport()
         private bool IsDraggingViewport()
@@ -221,16 +251,6 @@ namespace PixiEditor.Models.Controllers
             }
             }
         }
         }
 
 
-        public void GeneratePreviewLayer()
-        {
-            if (ActiveDocument != null)
-                PreviewLayer = new Layer("_previewLayer")
-                {
-                    MaxWidth = ActiveDocument.Width,
-                    MaxHeight = ActiveDocument.Height
-                };
-        }
-
         private void HighlightPixels(Coordinates newPosition)
         private void HighlightPixels(Coordinates newPosition)
         {
         {
             if (ActiveDocument == null || ActiveDocument.Layers.Count == 0 || SelectedTool.HideHighlight)
             if (ActiveDocument == null || ActiveDocument.Layers.Count == 0 || SelectedTool.HideHighlight)
@@ -268,27 +288,5 @@ namespace PixiEditor.Models.Controllers
                     highlightArea[0].Y <= ActiveDocument.Height - 1 &&
                     highlightArea[0].Y <= ActiveDocument.Height - 1 &&
                    highlightArea[^1].X >= 0 && highlightArea[^1].Y >= 0;
                    highlightArea[^1].X >= 0 && highlightArea[^1].Y >= 0;
         }
         }
-
-        public WriteableBitmap GetCombinedLayersBitmap()
-        {
-            return BitmapUtils.CombineLayers(ActiveDocument.Layers.Where(x => x.IsVisible).ToArray(), ActiveDocument.Width, ActiveDocument.Height);
-        }
-
-        /// <summary>
-        ///     Returns if selected tool is BitmapOperationTool.
-        /// </summary>
-        /// <returns></returns>
-        public bool IsOperationTool()
-        {
-            return IsOperationTool(SelectedTool);
-        }
-
-        /// <summary>
-        ///     Returns if tool is BitmapOperationTool.
-        /// </summary>
-        public static bool IsOperationTool(Tool tool)
-        {
-            return tool is BitmapOperationTool;
-        }
     }
     }
 }
 }

+ 2 - 2
PixiEditor/Models/Controllers/ClipboardController.cs

@@ -68,11 +68,11 @@ namespace PixiEditor.Models.Controllers
             }
             }
             else if (dao.GetDataPresent(DataFormats.Dib))
             else if (dao.GetDataPresent(DataFormats.Dib))
             {
             {
-                finalImage = new WriteableBitmap(Clipboard.GetImage()!);
+                finalImage = new WriteableBitmap(Clipboard.GetImage() !);
             }
             }
             else if (dao.GetDataPresent(DataFormats.Bitmap))
             else if (dao.GetDataPresent(DataFormats.Bitmap))
             {
             {
-                finalImage = new WriteableBitmap((dao.GetData(DataFormats.Bitmap) as BitmapSource)!);
+                finalImage = new WriteableBitmap((dao.GetData(DataFormats.Bitmap) as BitmapSource) !);
             }
             }
 
 
             return finalImage;
             return finalImage;

+ 8 - 7
PixiEditor/Models/Controllers/MouseMovementController.cs

@@ -7,12 +7,6 @@ namespace PixiEditor.Models.Controllers
 {
 {
     public class MouseMovementController
     public class MouseMovementController
     {
     {
-        public List<Coordinates> LastMouseMoveCoordinates { get; } = new List<Coordinates>();
-
-        public bool IsRecordingChanges { get; private set; }
-
-        public bool ClickedOnCanvas { get; set; }
-
         public event EventHandler StartedRecordingChanges;
         public event EventHandler StartedRecordingChanges;
 
 
         public event EventHandler<MouseEventArgs> OnMouseDown;
         public event EventHandler<MouseEventArgs> OnMouseDown;
@@ -23,6 +17,12 @@ namespace PixiEditor.Models.Controllers
 
 
         public event EventHandler StoppedRecordingChanges;
         public event EventHandler StoppedRecordingChanges;
 
 
+        public List<Coordinates> LastMouseMoveCoordinates { get; set; } = new List<Coordinates>();
+
+        public bool IsRecordingChanges { get; private set; }
+
+        public bool ClickedOnCanvas { get; set; }
+
         public void StartRecordingMouseMovementChanges(bool clickedOnCanvas)
         public void StartRecordingMouseMovementChanges(bool clickedOnCanvas)
         {
         {
             if (IsRecordingChanges == false)
             if (IsRecordingChanges == false)
@@ -37,17 +37,18 @@ namespace PixiEditor.Models.Controllers
         public void RecordMouseMovementChange(Coordinates mouseCoordinates)
         public void RecordMouseMovementChange(Coordinates mouseCoordinates)
         {
         {
             if (IsRecordingChanges)
             if (IsRecordingChanges)
+            {
                 if (LastMouseMoveCoordinates.Count == 0 || mouseCoordinates != LastMouseMoveCoordinates[^1])
                 if (LastMouseMoveCoordinates.Count == 0 || mouseCoordinates != LastMouseMoveCoordinates[^1])
                 {
                 {
                     LastMouseMoveCoordinates.Add(mouseCoordinates);
                     LastMouseMoveCoordinates.Add(mouseCoordinates);
                     MousePositionChanged?.Invoke(this, new MouseMovementEventArgs(mouseCoordinates));
                     MousePositionChanged?.Invoke(this, new MouseMovementEventArgs(mouseCoordinates));
                 }
                 }
+            }
         }
         }
 
 
         /// <summary>
         /// <summary>
         ///     Plain mouse move, does not affect mouse drag recordings.
         ///     Plain mouse move, does not affect mouse drag recordings.
         /// </summary>
         /// </summary>
-        /// <param name="mouseCoordinates"></param>
         public void MouseMoved(Coordinates mouseCoordinates)
         public void MouseMoved(Coordinates mouseCoordinates)
         {
         {
             MousePositionChanged?.Invoke(this, new MouseMovementEventArgs(mouseCoordinates));
             MousePositionChanged?.Invoke(this, new MouseMovementEventArgs(mouseCoordinates));

+ 8 - 6
PixiEditor/Models/ImageManipulation/BitmapUtils.cs

@@ -15,8 +15,7 @@ namespace PixiEditor.Models.ImageManipulation
         /// <param name="currentBitmapHeight">Height of bitmap.</param>
         /// <param name="currentBitmapHeight">Height of bitmap.</param>
         /// <param name="byteArray">Bitmap byte array.</param>
         /// <param name="byteArray">Bitmap byte array.</param>
         /// <returns>WriteableBitmap.</returns>
         /// <returns>WriteableBitmap.</returns>
-        public static WriteableBitmap BytesToWriteableBitmap(int currentBitmapWidth, int currentBitmapHeight,
-            byte[] byteArray)
+        public static WriteableBitmap BytesToWriteableBitmap(int currentBitmapWidth, int currentBitmapHeight, byte[] byteArray)
         {
         {
             WriteableBitmap bitmap = BitmapFactory.New(currentBitmapWidth, currentBitmapHeight);
             WriteableBitmap bitmap = BitmapFactory.New(currentBitmapWidth, currentBitmapHeight);
             bitmap.FromByteArray(byteArray);
             bitmap.FromByteArray(byteArray);
@@ -36,8 +35,10 @@ namespace PixiEditor.Models.ImageManipulation
 
 
             using (finalBitmap.GetBitmapContext())
             using (finalBitmap.GetBitmapContext())
             {
             {
-                for (int i = 0; i < layers.Length; i++)
-                    for (int y = 0; y < finalBitmap.Height; y++)
+                for (int i = 0; i < layers.Length; i++)
+                {
+                    for (int y = 0; y < finalBitmap.Height; y++)
+                    {
                         for (int x = 0; x < finalBitmap.Width; x++)
                         for (int x = 0; x < finalBitmap.Width; x++)
                         {
                         {
                             Color color = layers[i].GetPixelWithOffset(x, y);
                             Color color = layers[i].GetPixelWithOffset(x, y);
@@ -59,7 +60,9 @@ namespace PixiEditor.Models.ImageManipulation
                             {
                             {
                                 finalBitmap.SetPixel(x, y, color);
                                 finalBitmap.SetPixel(x, y, color);
                             }
                             }
-                        }
+                        }
+                    }
+                }
             }
             }
 
 
             return finalBitmap;
             return finalBitmap;
@@ -75,7 +78,6 @@ namespace PixiEditor.Models.ImageManipulation
 
 
                 using (layers[i].LayerBitmap.GetBitmapContext())
                 using (layers[i].LayerBitmap.GetBitmapContext())
                 {
                 {
-
                     for (int j = 0; j < pixels.Length; j++)
                     for (int j = 0; j < pixels.Length; j++)
                     {
                     {
                         Coordinates position = layers[i].GetRelativePosition(selection[j]);
                         Coordinates position = layers[i].GetRelativePosition(selection[j]);

+ 2 - 2
PixiEditor/Models/Tools/Tool.cs

@@ -7,6 +7,8 @@ namespace PixiEditor.Models.Tools
 {
 {
     public abstract class Tool : NotifyableObject
     public abstract class Tool : NotifyableObject
     {
     {
+        private bool isActive;
+
         public abstract ToolType ToolType { get; }
         public abstract ToolType ToolType { get; }
 
 
         public string ImagePath => $"/Images/{ToolType}Image.png";
         public string ImagePath => $"/Images/{ToolType}Image.png";
@@ -29,8 +31,6 @@ namespace PixiEditor.Models.Tools
 
 
         public Toolbar Toolbar { get; set; } = new EmptyToolbar();
         public Toolbar Toolbar { get; set; } = new EmptyToolbar();
 
 
-        private bool isActive;
-
         public bool CanStartOutsideCanvas { get; set; } = false;
         public bool CanStartOutsideCanvas { get; set; } = false;
 
 
         public virtual void OnMouseDown(MouseEventArgs e)
         public virtual void OnMouseDown(MouseEventArgs e)

+ 24 - 18
PixiEditor/Models/Tools/Tools/BrightnessTool.cs

@@ -15,20 +15,20 @@ namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class BrightnessTool : BitmapOperationTool
     public class BrightnessTool : BitmapOperationTool
     {
     {
-        private const float CorrectionFactor = 5f; //Initial correction factor
+        private const float CorrectionFactor = 5f; // Initial correction factor
 
 
-        public override ToolType ToolType => ToolType.Brightness;
+        private List<Coordinates> pixelsVisited = new List<Coordinates>();
 
 
-        public BrightnessMode Mode { get; set; } = BrightnessMode.Default;
-
-        private List<Coordinates> pixelsVisited = new List<Coordinates>();
-
         public BrightnessTool()
         public BrightnessTool()
         {
         {
             Tooltip = "Makes pixel brighter or darker pixel (U). Hold Ctrl to make pixel darker.";
             Tooltip = "Makes pixel brighter or darker pixel (U). Hold Ctrl to make pixel darker.";
             Toolbar = new BrightnessToolToolbar(CorrectionFactor);
             Toolbar = new BrightnessToolToolbar(CorrectionFactor);
         }
         }
 
 
+        public override ToolType ToolType => ToolType.Brightness;
+
+        public BrightnessMode Mode { get; set; } = BrightnessMode.Default;
+
         public override void OnRecordingLeftMouseDown(MouseEventArgs e)
         public override void OnRecordingLeftMouseDown(MouseEventArgs e)
         {
         {
             pixelsVisited.Clear();
             pixelsVisited.Clear();
@@ -42,22 +42,26 @@ namespace PixiEditor.Models.Tools.Tools
             Mode = mode;
             Mode = mode;
 
 
             LayerChange[] layersChanges = new LayerChange[1];
             LayerChange[] layersChanges = new LayerChange[1];
-            if (Keyboard.IsKeyDown(Key.LeftCtrl))
-                layersChanges[0] = new LayerChange(ChangeBrightness(layer, coordinates[0], toolSize, -correctionFactor),
-                    layer);
-            else
-                layersChanges[0] = new LayerChange(ChangeBrightness(layer, coordinates[0], toolSize, correctionFactor),
-                    layer);
+            if (Keyboard.IsKeyDown(Key.LeftCtrl))
+            {
+                layersChanges[0] = new LayerChange(ChangeBrightness(layer, coordinates[0], toolSize, -correctionFactor), layer);
+            }
+            else
+            {
+                layersChanges[0] = new LayerChange(ChangeBrightness(layer, coordinates[0], toolSize, correctionFactor), layer);
+            }
+
             return layersChanges;
             return layersChanges;
         }
         }
 
 
-        public BitmapPixelChanges ChangeBrightness(Layer layer, Coordinates coordinates, int toolSize,
-            float correctionFactor)
+        public BitmapPixelChanges ChangeBrightness(Layer layer, Coordinates coordinates, int toolSize, float correctionFactor)
         {
         {
             DoubleCords centeredCoords = CoordinatesCalculator.CalculateThicknessCenter(coordinates, toolSize);
             DoubleCords centeredCoords = CoordinatesCalculator.CalculateThicknessCenter(coordinates, toolSize);
-            Coordinates[] rectangleCoordinates = CoordinatesCalculator.RectangleToCoordinates(centeredCoords.Coords1.X,
+            Coordinates[] rectangleCoordinates = CoordinatesCalculator.RectangleToCoordinates(
+                centeredCoords.Coords1.X,
                 centeredCoords.Coords1.Y,
                 centeredCoords.Coords1.Y,
-                centeredCoords.Coords2.X, centeredCoords.Coords2.Y);
+                centeredCoords.Coords2.X,
+                centeredCoords.Coords2.Y);
             BitmapPixelChanges changes = new BitmapPixelChanges(new Dictionary<Coordinates, Color>());
             BitmapPixelChanges changes = new BitmapPixelChanges(new Dictionary<Coordinates, Color>());
 
 
             for (int i = 0; i < rectangleCoordinates.Length; i++)
             for (int i = 0; i < rectangleCoordinates.Length; i++)
@@ -73,9 +77,11 @@ namespace PixiEditor.Models.Tools.Tools
                 }
                 }
 
 
                 Color pixel = layer.GetPixelWithOffset(rectangleCoordinates[i].X, rectangleCoordinates[i].Y);
                 Color pixel = layer.GetPixelWithOffset(rectangleCoordinates[i].X, rectangleCoordinates[i].Y);
-                Color newColor = ExColor.ChangeColorBrightness(Color.FromArgb(pixel.A, pixel.R, pixel.G, pixel.B),
+                Color newColor = ExColor.ChangeColorBrightness(
+                    Color.FromArgb(pixel.A, pixel.R, pixel.G, pixel.B),
                     correctionFactor);
                     correctionFactor);
-                changes.ChangedPixels.Add(new Coordinates(rectangleCoordinates[i].X, rectangleCoordinates[i].Y),
+                changes.ChangedPixels.Add(
+                    new Coordinates(rectangleCoordinates[i].X, rectangleCoordinates[i].Y),
                     newColor);
                     newColor);
             }
             }
 
 

+ 3 - 3
PixiEditor/Models/Tools/Tools/FloodFill.cs

@@ -8,14 +8,14 @@ using PixiEditor.ViewModels;
 namespace PixiEditor.Models.Tools.Tools
 namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class FloodFill : BitmapOperationTool
     public class FloodFill : BitmapOperationTool
-    {
-        public override ToolType ToolType => ToolType.Bucket;
-
+    {
         public FloodFill()
         public FloodFill()
         {
         {
             Tooltip = "Fills area with color (G)";
             Tooltip = "Fills area with color (G)";
         }
         }
 
 
+        public override ToolType ToolType => ToolType.Bucket;
+
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         {
         {
             return Only(ForestFire(layer, coordinates[0], color), layer);
             return Only(ForestFire(layer, coordinates[0], color), layer);

+ 82 - 70
PixiEditor/Models/Tools/Tools/MoveTool.cs

@@ -18,20 +18,16 @@ namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class MoveTool : BitmapOperationTool
     public class MoveTool : BitmapOperationTool
     {
     {
-        public bool MoveAll { get; set; } = false;
-
-        public override ToolType ToolType => ToolType.Move;
-
         private Layer[] affectedLayers;
         private Layer[] affectedLayers;
-        private Dictionary<Layer, bool> _clearedPixels = new Dictionary<Layer, bool>();
-        private Coordinates[] _currentSelection;
-        private Coordinates _lastMouseMove;
-        private Coordinates _lastStartMousePos;
-        private Dictionary<Layer, Color[]> _startPixelColors;
-        private Dictionary<Layer, Thickness> _startingOffsets;
-        private Coordinates[] _startSelection;
-        private bool _updateViewModelSelection = true;
-
+        private Dictionary<Layer, bool> clearedPixels = new Dictionary<Layer, bool>();
+        private Coordinates[] currentSelection;
+        private Coordinates lastMouseMove;
+        private Coordinates lastStartMousePos;
+        private Dictionary<Layer, Color[]> startPixelColors;
+        private Dictionary<Layer, Thickness> startingOffsets;
+        private Coordinates[] startSelection;
+        private bool updateViewModelSelection = true;
+
         public MoveTool()
         public MoveTool()
         {
         {
             Tooltip = "Moves selected pixels (V). Hold Ctrl to move all layers";
             Tooltip = "Moves selected pixels (V). Hold Ctrl to move all layers";
@@ -39,16 +35,20 @@ namespace PixiEditor.Models.Tools.Tools
             HideHighlight = true;
             HideHighlight = true;
             RequiresPreviewLayer = true;
             RequiresPreviewLayer = true;
             UseDefaultUndoMethod = true;
             UseDefaultUndoMethod = true;
-        }
+        }
+
+        public bool MoveAll { get; set; } = false;
+
+        public override ToolType ToolType => ToolType.Move;
 
 
         public override void AfterAddedUndo()
         public override void AfterAddedUndo()
         {
         {
-            if (_currentSelection != null && _currentSelection.Length != 0)
+            if (currentSelection != null && currentSelection.Length != 0)
             {
             {
-                //Inject to default undo system change custom changes made by this tool
-                foreach (var item in _startPixelColors)
+                // Inject to default undo system change custom changes made by this tool
+                foreach (var item in startPixelColors)
                 {
                 {
-                    BitmapPixelChanges beforeMovePixels = BitmapPixelChanges.FromArrays(_startSelection, item.Value);
+                    BitmapPixelChanges beforeMovePixels = BitmapPixelChanges.FromArrays(startSelection, item.Value);
                     Change changes = UndoManager.UndoStack.Peek();
                     Change changes = UndoManager.UndoStack.Peek();
                     int layerIndex = ViewModelMain.Current.BitmapManager.ActiveDocument.Layers.IndexOf(item.Key);
                     int layerIndex = ViewModelMain.Current.BitmapManager.ActiveDocument.Layers.IndexOf(item.Key);
 
 
@@ -57,63 +57,66 @@ namespace PixiEditor.Models.Tools.Tools
 
 
                     ((LayerChange[])changes.NewValue).First(x => x.LayerIndex == layerIndex).PixelChanges.ChangedPixels
                     ((LayerChange[])changes.NewValue).First(x => x.LayerIndex == layerIndex).PixelChanges.ChangedPixels
                         .AddRangeNewOnly(BitmapPixelChanges
                         .AddRangeNewOnly(BitmapPixelChanges
-                            .FromSingleColoredArray(_startSelection, System.Windows.Media.Colors.Transparent)
+                            .FromSingleColoredArray(startSelection, System.Windows.Media.Colors.Transparent)
                             .ChangedPixels);
                             .ChangedPixels);
                 }
                 }
             }
             }
         }
         }
 
 
-        public override void OnStoppedRecordingMouseUp(MouseEventArgs e) //This adds undo if there is no selection, reason why this isn't in AfterUndoAdded,
-        {   //is because it doesn't fire if no pixel changes were made.
-            if (_currentSelection != null && _currentSelection.Length == 0)
-            {
-                UndoManager.AddUndoChange(new Change(ApplyOffsets, new object[] { _startingOffsets },
-                    ApplyOffsets, new object[] { GetOffsets(affectedLayers) }, "Move layers"));
-            }
-        }
-
-        private void ApplyOffsets(object[] parameters)
+        // This adds undo if there is no selection, reason why this isn't in AfterUndoAdded,
+        // is because it doesn't fire if no pixel changes were made.
+        public override void OnStoppedRecordingMouseUp(MouseEventArgs e)
         {
         {
-            Dictionary<Layer, Thickness> offsets = (Dictionary<Layer, Thickness>)parameters[0];
-            foreach (var offset in offsets)
+            if (currentSelection != null && currentSelection.Length == 0)
             {
             {
-                offset.Key.Offset = offset.Value;
+                UndoManager.AddUndoChange(new Change(
+                    ApplyOffsets,
+                    new object[] { startingOffsets },
+                    ApplyOffsets,
+                    new object[] { GetOffsets(affectedLayers) },
+                    "Move layers"));
             }
             }
         }
         }
 
 
         public override LayerChange[] Use(Layer layer, Coordinates[] mouseMove, Color color)
         public override LayerChange[] Use(Layer layer, Coordinates[] mouseMove, Color color)
         {
         {
             Coordinates start = mouseMove[^1];
             Coordinates start = mouseMove[^1];
-            if (_lastStartMousePos != start) //I am aware that this could be moved to OnMouseDown, but it is executed before Use, so I didn't want to complicate for now
+
+            // I am aware that this could be moved to OnMouseDown, but it is executed before Use, so I didn't want to complicate for now
+            if (lastStartMousePos != start)
             {
             {
                 ResetSelectionValues(start);
                 ResetSelectionValues(start);
-                if (ViewModelMain.Current.ActiveSelection != null && ViewModelMain.Current.ActiveSelection.SelectedPoints.Count > 0) //Move offset if no selection
+
+                // Move offset if no selection
+                if (ViewModelMain.Current.ActiveSelection != null && ViewModelMain.Current.ActiveSelection.SelectedPoints.Count > 0)
                 {
                 {
-                    _currentSelection = ViewModelMain.Current.ActiveSelection.SelectedPoints.ToArray();
+                    currentSelection = ViewModelMain.Current.ActiveSelection.SelectedPoints.ToArray();
                 }
                 }
                 else
                 else
                 {
                 {
-                    _currentSelection = Array.Empty<Coordinates>();
+                    currentSelection = Array.Empty<Coordinates>();
                 }
                 }
 
 
-                if (Keyboard.IsKeyDown(Key.LeftCtrl) || MoveAll)
+                if (Keyboard.IsKeyDown(Key.LeftCtrl) || MoveAll)
+                {
                     affectedLayers = ViewModelMain.Current.BitmapManager.ActiveDocument.Layers.Where(x => x.IsVisible)
                     affectedLayers = ViewModelMain.Current.BitmapManager.ActiveDocument.Layers.Where(x => x.IsVisible)
-                        .ToArray();
+                        .ToArray();
+                }
                 else
                 else
                 {
                 {
                     affectedLayers = new[] { layer };
                     affectedLayers = new[] { layer };
                 }
                 }
 
 
-                _startSelection = _currentSelection;
-                _startPixelColors = BitmapUtils.GetPixelsForSelection(affectedLayers, _startSelection);
-                _startingOffsets = GetOffsets(affectedLayers);
+                startSelection = currentSelection;
+                startPixelColors = BitmapUtils.GetPixelsForSelection(affectedLayers, startSelection);
+                startingOffsets = GetOffsets(affectedLayers);
             }
             }
 
 
             LayerChange[] result = new LayerChange[affectedLayers.Length];
             LayerChange[] result = new LayerChange[affectedLayers.Length];
             var end = mouseMove[0];
             var end = mouseMove[0];
             for (int i = 0; i < affectedLayers.Length; i++)
             for (int i = 0; i < affectedLayers.Length; i++)
             {
             {
-                if (_currentSelection.Length > 0)
+                if (currentSelection.Length > 0)
                 {
                 {
                     var changes = MoveSelection(affectedLayers[i], mouseMove);
                     var changes = MoveSelection(affectedLayers[i], mouseMove);
                     changes = RemoveTransparentPixels(changes);
                     changes = RemoveTransparentPixels(changes);
@@ -122,15 +125,40 @@ namespace PixiEditor.Models.Tools.Tools
                 }
                 }
                 else
                 else
                 {
                 {
-                    var vector = Transform.GetTranslation(_lastMouseMove, end);
+                    var vector = Transform.GetTranslation(lastMouseMove, end);
                     affectedLayers[i].Offset = new Thickness(affectedLayers[i].OffsetX + vector.X, affectedLayers[i].OffsetY + vector.Y, 0, 0);
                     affectedLayers[i].Offset = new Thickness(affectedLayers[i].OffsetX + vector.X, affectedLayers[i].OffsetY + vector.Y, 0, 0);
                     result[i] = new LayerChange(BitmapPixelChanges.Empty, affectedLayers[i]);
                     result[i] = new LayerChange(BitmapPixelChanges.Empty, affectedLayers[i]);
                 }
                 }
             }
             }
 
 
-            _lastMouseMove = end;
+            lastMouseMove = end;
 
 
             return result;
             return result;
+        }
+
+        public BitmapPixelChanges MoveSelection(Layer layer, Coordinates[] mouseMove)
+        {
+            Coordinates end = mouseMove[0];
+
+            currentSelection = TranslateSelection(end, out Coordinates[] previousSelection);
+            if (updateViewModelSelection)
+            {
+                ViewModelMain.Current.ActiveSelection.SetSelection(currentSelection, SelectionType.New);
+            }
+
+            ClearSelectedPixels(layer, previousSelection);
+
+            lastMouseMove = end;
+            return BitmapPixelChanges.FromArrays(currentSelection, startPixelColors[layer]);
+        }
+
+        private void ApplyOffsets(object[] parameters)
+        {
+            Dictionary<Layer, Thickness> offsets = (Dictionary<Layer, Thickness>)parameters[0];
+            foreach (var offset in offsets)
+            {
+                offset.Key.Offset = offset.Value;
+            }
         }
         }
 
 
         private Dictionary<Layer, Thickness> GetOffsets(Layer[] layers)
         private Dictionary<Layer, Thickness> GetOffsets(Layer[] layers)
@@ -154,47 +182,31 @@ namespace PixiEditor.Models.Tools.Tools
             return pixels;
             return pixels;
         }
         }
 
 
-        public BitmapPixelChanges MoveSelection(Layer layer, Coordinates[] mouseMove)
-        {
-            Coordinates end = mouseMove[0];
-
-            _currentSelection = TranslateSelection(end, out Coordinates[] previousSelection);
-            if (_updateViewModelSelection)
-            {
-                ViewModelMain.Current.ActiveSelection.SetSelection(_currentSelection, SelectionType.New);
-            }
-
-            ClearSelectedPixels(layer, previousSelection);
-
-            _lastMouseMove = end;
-            return BitmapPixelChanges.FromArrays(_currentSelection, _startPixelColors[layer]);
-        }
-
         private void ResetSelectionValues(Coordinates start)
         private void ResetSelectionValues(Coordinates start)
         {
         {
-            _lastStartMousePos = start;
-            _lastMouseMove = start;
-            _clearedPixels = new Dictionary<Layer, bool>();
-            _updateViewModelSelection = true;
-            _startPixelColors = null;
-            _startSelection = null;
+            lastStartMousePos = start;
+            lastMouseMove = start;
+            clearedPixels = new Dictionary<Layer, bool>();
+            updateViewModelSelection = true;
+            startPixelColors = null;
+            startSelection = null;
         }
         }
 
 
         private Coordinates[] TranslateSelection(Coordinates end, out Coordinates[] previousSelection)
         private Coordinates[] TranslateSelection(Coordinates end, out Coordinates[] previousSelection)
         {
         {
-            Coordinates translation = Transform.GetTranslation(_lastMouseMove, end);
-            previousSelection = _currentSelection.ToArray();
+            Coordinates translation = Transform.GetTranslation(lastMouseMove, end);
+            previousSelection = currentSelection.ToArray();
             return Transform.Translate(previousSelection, translation);
             return Transform.Translate(previousSelection, translation);
         }
         }
 
 
         private void ClearSelectedPixels(Layer layer, Coordinates[] selection)
         private void ClearSelectedPixels(Layer layer, Coordinates[] selection)
         {
         {
-            if (!_clearedPixels.ContainsKey(layer) || _clearedPixels[layer] == false)
+            if (!clearedPixels.ContainsKey(layer) || clearedPixels[layer] == false)
             {
             {
                 ViewModelMain.Current.BitmapManager.ActiveDocument.Layers.First(x => x == layer)
                 ViewModelMain.Current.BitmapManager.ActiveDocument.Layers.First(x => x == layer)
                     .SetPixels(BitmapPixelChanges.FromSingleColoredArray(selection, System.Windows.Media.Colors.Transparent));
                     .SetPixels(BitmapPixelChanges.FromSingleColoredArray(selection, System.Windows.Media.Colors.Transparent));
 
 
-                _clearedPixels[layer] = true;
+                clearedPixels[layer] = true;
             }
             }
         }
         }
     }
     }

+ 5 - 4
PixiEditor/Models/Tools/Tools/MoveViewportTool.cs

@@ -7,10 +7,8 @@ namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class MoveViewportTool : ReadonlyTool
     public class MoveViewportTool : ReadonlyTool
     {
     {
-        public override ToolType ToolType => ToolType.MoveViewport;
+        private Point clickPoint;
 
 
-        private Point clickPoint;
-
         public MoveViewportTool()
         public MoveViewportTool()
         {
         {
             HideHighlight = true;
             HideHighlight = true;
@@ -18,6 +16,8 @@ namespace PixiEditor.Models.Tools.Tools
             Tooltip = "Move viewport. (H)";
             Tooltip = "Move viewport. (H)";
         }
         }
 
 
+        public override ToolType ToolType => ToolType.MoveViewport;
+
         public override void OnMouseDown(MouseEventArgs e)
         public override void OnMouseDown(MouseEventArgs e)
         {
         {
             if (e.LeftButton == MouseButtonState.Pressed || e.MiddleButton == MouseButtonState.Pressed)
             if (e.LeftButton == MouseButtonState.Pressed || e.MiddleButton == MouseButtonState.Pressed)
@@ -31,7 +31,8 @@ namespace PixiEditor.Models.Tools.Tools
             if (e.LeftButton == MouseButtonState.Pressed || e.MiddleButton == MouseButtonState.Pressed)
             if (e.LeftButton == MouseButtonState.Pressed || e.MiddleButton == MouseButtonState.Pressed)
             {
             {
                 var point = MousePositionConverter.GetCursorPosition();
                 var point = MousePositionConverter.GetCursorPosition();
-                ViewModelMain.Current.ViewportPosition = new System.Windows.Point(point.X - clickPoint.X,
+                ViewModelMain.Current.ViewportPosition = new System.Windows.Point(
+                    point.X - clickPoint.X,
                     point.Y - clickPoint.Y);
                     point.Y - clickPoint.Y);
             }
             }
         }
         }

+ 17 - 16
PixiEditor/Models/Tools/Tools/SelectTool.cs

@@ -15,20 +15,22 @@ namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class SelectTool : ReadonlyTool
     public class SelectTool : ReadonlyTool
     {
     {
-        public override ToolType ToolType => ToolType.Select;
+        private Selection oldSelection;
 
 
-        private Selection oldSelection;
-        public SelectionType SelectionType = SelectionType.Add;
-
         public SelectTool()
         public SelectTool()
         {
         {
             Tooltip = "Selects area. (M)";
             Tooltip = "Selects area. (M)";
             Toolbar = new SelectToolToolbar();
             Toolbar = new SelectToolToolbar();
-        }
+        }
+
+        public SelectionType SelectionType { get; set; } = SelectionType.Add;
+
+        public override ToolType ToolType => ToolType.Select;
 
 
         public override void OnRecordingLeftMouseDown(MouseEventArgs e)
         public override void OnRecordingLeftMouseDown(MouseEventArgs e)
         {
         {
-            Enum.TryParse((Toolbar.GetSetting<DropdownSetting>("Mode")?.Value as ComboBoxItem)?.Content as string, out SelectionType);
+            Enum.TryParse((Toolbar.GetSetting<DropdownSetting>("Mode")?.Value as ComboBoxItem)?.Content as string, out SelectionType selectionType);
+            SelectionType = selectionType;
 
 
             oldSelection = null;
             oldSelection = null;
             if (ViewModelMain.Current.ActiveSelection != null &&
             if (ViewModelMain.Current.ActiveSelection != null &&
@@ -46,21 +48,14 @@ namespace PixiEditor.Models.Tools.Tools
                 ViewModelMain.Current.ActiveSelection.Clear();
                 ViewModelMain.Current.ActiveSelection.Clear();
             }
             }
 
 
-            UndoManager.AddUndoChange(new Change("ActiveSelection", oldSelection,
-                ViewModelMain.Current.ActiveSelection, "Select pixels"));
+            UndoManager.AddUndoChange(new Change("ActiveSelection", oldSelection, ViewModelMain.Current.ActiveSelection, "Select pixels"));
         }
         }
 
 
         public override void Use(Coordinates[] pixels)
         public override void Use(Coordinates[] pixels)
         {
         {
             Select(pixels);
             Select(pixels);
-        }
-
-        private void Select(Coordinates[] pixels)
-        {
-            IEnumerable<Coordinates> selection = GetRectangleSelectionForPoints(pixels[^1], pixels[0]);
-            ViewModelMain.Current.ActiveSelection.SetSelection(selection, SelectionType);
-        }
-
+        }
+
         public IEnumerable<Coordinates> GetRectangleSelectionForPoints(Coordinates start, Coordinates end)
         public IEnumerable<Coordinates> GetRectangleSelectionForPoints(Coordinates start, Coordinates end)
         {
         {
             RectangleTool rectangleTool = new RectangleTool();
             RectangleTool rectangleTool = new RectangleTool();
@@ -85,6 +80,12 @@ namespace PixiEditor.Models.Tools.Tools
         public IEnumerable<Coordinates> GetAllSelection(Document document)
         public IEnumerable<Coordinates> GetAllSelection(Document document)
         {
         {
             return GetRectangleSelectionForPoints(new Coordinates(0, 0), new Coordinates(document.Width - 1, document.Height - 1));
             return GetRectangleSelectionForPoints(new Coordinates(0, 0), new Coordinates(document.Width - 1, document.Height - 1));
+        }
+
+        private void Select(Coordinates[] pixels)
+        {
+            IEnumerable<Coordinates> selection = GetRectangleSelectionForPoints(pixels[^1], pixels[0]);
+            ViewModelMain.Current.ActiveSelection.SetSelection(selection, SelectionType);
         }
         }
     }
     }
 }
 }

+ 9 - 8
PixiEditor/Models/Tools/Tools/ZoomTool.cs

@@ -10,11 +10,10 @@ namespace PixiEditor.Models.Tools.Tools
     {
     {
         public const float ZoomSensitivityMultiplier = 30f;
         public const float ZoomSensitivityMultiplier = 30f;
 
 
-        public override ToolType ToolType => ToolType.Zoom;
+        private double startingX;
 
 
-        private double startingX;
         private double workAreaWidth = SystemParameters.WorkArea.Width;
         private double workAreaWidth = SystemParameters.WorkArea.Width;
-        private double pixelsPerZoomMultiplier;
+        private double pixelsPerZoomMultiplier;
 
 
         public ZoomTool()
         public ZoomTool()
         {
         {
@@ -22,12 +21,14 @@ namespace PixiEditor.Models.Tools.Tools
             CanStartOutsideCanvas = true;
             CanStartOutsideCanvas = true;
             Tooltip = "Zooms viewport (Z). Click to zoom in, hold alt and click to zoom out.";
             Tooltip = "Zooms viewport (Z). Click to zoom in, hold alt and click to zoom out.";
             pixelsPerZoomMultiplier = workAreaWidth / ZoomSensitivityMultiplier;
             pixelsPerZoomMultiplier = workAreaWidth / ZoomSensitivityMultiplier;
-        }
-
+        }
+
+        public override ToolType ToolType => ToolType.Zoom;
+
         public override void OnRecordingLeftMouseDown(MouseEventArgs e)
         public override void OnRecordingLeftMouseDown(MouseEventArgs e)
         {
         {
             startingX = MousePositionConverter.GetCursorPosition().X;
             startingX = MousePositionConverter.GetCursorPosition().X;
-            ViewModelMain.Current.ZoomPercentage = 100; //This resest the value, so callback in MainDrawingPanel can fire again later
+            ViewModelMain.Current.ZoomPercentage = 100; // This resest the value, so callback in MainDrawingPanel can fire again later
         }
         }
 
 
         public override void OnMouseMove(MouseEventArgs e)
         public override void OnMouseMove(MouseEventArgs e)
@@ -36,8 +37,8 @@ namespace PixiEditor.Models.Tools.Tools
             {
             {
                 double xPos = MousePositionConverter.GetCursorPosition().X;
                 double xPos = MousePositionConverter.GetCursorPosition().X;
 
 
-                double rawPercentDifference = (xPos - startingX) / pixelsPerZoomMultiplier; //negative - zoom out, positive - zoom in, linear
-                double finalPercentDifference = Math.Pow(2, rawPercentDifference) * 100.0; //less than 100 - zoom out, greater than 100 - zoom in
+                double rawPercentDifference = (xPos - startingX) / pixelsPerZoomMultiplier; // negative - zoom out, positive - zoom in, linear
+                double finalPercentDifference = Math.Pow(2, rawPercentDifference) * 100.0; // less than 100 - zoom out, greater than 100 - zoom in
                 Zoom(finalPercentDifference);
                 Zoom(finalPercentDifference);
             }
             }
         }
         }

+ 19 - 17
PixiEditor/Properties/AssemblyInfo.cs

@@ -17,24 +17,27 @@ using System.Windows;
 // Setting ComVisible to false makes the types in this assembly not visible
 // Setting ComVisible to false makes the types in this assembly not visible
 // to COM components.  If you need to access a type in this assembly from
 // to COM components.  If you need to access a type in this assembly from
 // COM, set the ComVisible attribute to true on that type.
 // COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-//In order to begin building localizable applications, set
-//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
-//inside a <PropertyGroup>.  For example, if you are using US english
-//in your source files, set the <UICulture> to en-US.  Then uncomment
-//the NeutralResourceLanguage attribute below.  Update the "en-US" in
-//the line below to match the UICulture setting in the project file.
-
-//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+[assembly: ComVisible(false)]
+
+// In order to begin building localizable applications, set
+// <UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
+// inside a <PropertyGroup>.  For example, if you are using US english
+// in your source files, set the <UICulture> to en-US.  Then uncomment
+// the NeutralResourceLanguage attribute below.  Update the "en-US" in
+// the line below to match the UICulture setting in the project file.
 
 
+// [assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+// ResourceDictionaryLocation.None where theme specific resource dictionaries are located
+// (used if a resource is not found in the page,
+// or application resource dictionaries)
+
+// ResourceDictionaryLocation.SourceAssembly where the generic resource dictionary is located
+// (used if a resource is not found in the page,
+// app, or any theme specific resource dictionaries)
 [assembly: ThemeInfo(
 [assembly: ThemeInfo(
-    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
-                                     //(used if a resource is not found in the page,
-                                     // or application resource dictionaries)
-    ResourceDictionaryLocation.SourceAssembly) //where the generic resource dictionary is located
-                                               //(used if a resource is not found in the page,
-                                               // app, or any theme specific resource dictionaries)
+    ResourceDictionaryLocation.None,
+    ResourceDictionaryLocation.SourceAssembly)
 ]
 ]
 
 
 // Version information for an assembly consists of the following four values:
 // Version information for an assembly consists of the following four values:
@@ -47,6 +50,5 @@ using System.Windows;
 // You can specify all the values or you can default the Build and Revision Numbers
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
 // [assembly: AssemblyVersion("1.0.*")]
-
 [assembly: AssemblyVersion("0.1.3.2")]
 [assembly: AssemblyVersion("0.1.3.2")]
 [assembly: AssemblyFileVersion("0.1.3.2")]
 [assembly: AssemblyFileVersion("0.1.3.2")]

文件差異過大導致無法顯示
+ 408 - 407
PixiEditor/ViewModels/ViewModelMain.cs


+ 39 - 42
PixiEditor/Views/MainDrawingPanel.xaml.cs

@@ -16,8 +16,7 @@ namespace PixiEditor.Views
     {
     {
         // Using a DependencyProperty as the backing store for Center.  This enables animation, styling, binding, etc...
         // Using a DependencyProperty as the backing store for Center.  This enables animation, styling, binding, etc...
         public static readonly DependencyProperty CenterProperty =
         public static readonly DependencyProperty CenterProperty =
-            DependencyProperty.Register("Center", typeof(bool), typeof(MainDrawingPanel),
-                new PropertyMetadata(true, OnCenterChanged));
+            DependencyProperty.Register("Center", typeof(bool), typeof(MainDrawingPanel), new PropertyMetadata(true, OnCenterChanged));
 
 
         // Using a DependencyProperty as the backing store for MouseX.  This enables animation, styling, binding, etc...
         // Using a DependencyProperty as the backing store for MouseX.  This enables animation, styling, binding, etc...
         public static readonly DependencyProperty MouseXProperty =
         public static readonly DependencyProperty MouseXProperty =
@@ -29,13 +28,11 @@ namespace PixiEditor.Views
 
 
         // Using a DependencyProperty as the backing store for MouseMoveCommand.  This enables animation, styling, binding, etc...
         // Using a DependencyProperty as the backing store for MouseMoveCommand.  This enables animation, styling, binding, etc...
         public static readonly DependencyProperty MouseMoveCommandProperty =
         public static readonly DependencyProperty MouseMoveCommandProperty =
-            DependencyProperty.Register("MouseMoveCommand", typeof(ICommand), typeof(MainDrawingPanel),
-                new PropertyMetadata(null));
+            DependencyProperty.Register("MouseMoveCommand", typeof(ICommand), typeof(MainDrawingPanel), new PropertyMetadata(null));
 
 
         // Using a DependencyProperty as the backing store for CenterOnStart.  This enables animation, styling, binding, etc...
         // Using a DependencyProperty as the backing store for CenterOnStart.  This enables animation, styling, binding, etc...
         public static readonly DependencyProperty CenterOnStartProperty =
         public static readonly DependencyProperty CenterOnStartProperty =
-            DependencyProperty.Register("CenterOnStart", typeof(bool), typeof(MainDrawingPanel),
-                new PropertyMetadata(false));
+            DependencyProperty.Register("CenterOnStart", typeof(bool), typeof(MainDrawingPanel), new PropertyMetadata(false));
 
 
         // Using a DependencyProperty as the backing store for Item.  This enables animation, styling, binding, etc...
         // Using a DependencyProperty as the backing store for Item.  This enables animation, styling, binding, etc...
         public static readonly DependencyProperty ItemProperty =
         public static readonly DependencyProperty ItemProperty =
@@ -43,17 +40,39 @@ namespace PixiEditor.Views
 
 
         // Using a DependencyProperty as the backing store for Item.  This enables animation, styling, binding, etc...
         // Using a DependencyProperty as the backing store for Item.  This enables animation, styling, binding, etc...
         public static readonly DependencyProperty IsUsingZoomToolProperty =
         public static readonly DependencyProperty IsUsingZoomToolProperty =
-            DependencyProperty.Register("IsUsingZoomTool", typeof(bool), typeof(MainDrawingPanel), new PropertyMetadata(false));
+            DependencyProperty.Register("IsUsingZoomTool", typeof(bool), typeof(MainDrawingPanel), new PropertyMetadata(false));
+
+        // Using a DependencyProperty as the backing store for ZoomPercentage.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty ZoomPercentageProperty =
+            DependencyProperty.Register("ZoomPercentage", typeof(double), typeof(MainDrawingPanel), new PropertyMetadata(0.0, ZoomPercentegeChanged));
+
+        // Using a DependencyProperty as the backing store for ViewportPosition.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty ViewportPositionProperty =
+            DependencyProperty.Register("ViewportPosition", typeof(Point), typeof(MainDrawingPanel), new PropertyMetadata(default(Point), ViewportPosCallback));
+
+        // Using a DependencyProperty as the backing store for MiddleMouseClickedCommand.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty MiddleMouseClickedCommandProperty =
+            DependencyProperty.Register("MiddleMouseClickedCommand", typeof(ICommand), typeof(MainDrawingPanel), new PropertyMetadata(default(ICommand)));
+
+        // Using a DependencyProperty as the backing store for MiddleMouseClickedCommandParameter.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty MiddleMouseClickedCommandParameterProperty =
+            DependencyProperty.Register("MiddleMouseClickedCommandParameter", typeof(object), typeof(MainDrawingPanel), new PropertyMetadata(default(object)));
+
+        public MainDrawingPanel()
+        {
+            InitializeComponent();
+            Zoombox.ZoomToSelectionModifiers = new KeyModifierCollection() { KeyModifier.RightAlt };
+        }
+
+        public double ClickScale { get; set; }
+
+        public Point ClickPosition { get; set; }
 
 
         public double ZoomPercentage
         public double ZoomPercentage
         {
         {
             get { return (double)GetValue(ZoomPercentageProperty); }
             get { return (double)GetValue(ZoomPercentageProperty); }
             set { SetValue(ZoomPercentageProperty, value); }
             set { SetValue(ZoomPercentageProperty, value); }
         }
         }
-
-        // Using a DependencyProperty as the backing store for ZoomPercentage.  This enables animation, styling, binding, etc...
-        public static readonly DependencyProperty ZoomPercentageProperty =
-            DependencyProperty.Register("ZoomPercentage", typeof(double), typeof(MainDrawingPanel), new PropertyMetadata(0.0, ZoomPercentegeChanged));
 
 
         public Point ViewportPosition
         public Point ViewportPosition
         {
         {
@@ -61,11 +80,6 @@ namespace PixiEditor.Views
             set { SetValue(ViewportPositionProperty, value); }
             set { SetValue(ViewportPositionProperty, value); }
         }
         }
 
 
-        // Using a DependencyProperty as the backing store for ViewportPosition.  This enables animation, styling, binding, etc...
-        public static readonly DependencyProperty ViewportPositionProperty =
-            DependencyProperty.Register("ViewportPosition", typeof(Point),
-                typeof(MainDrawingPanel), new PropertyMetadata(default(Point), ViewportPosCallback));
-
         public bool Center
         public bool Center
         {
         {
             get => (bool)GetValue(CenterProperty);
             get => (bool)GetValue(CenterProperty);
@@ -113,21 +127,12 @@ namespace PixiEditor.Views
             get { return (ICommand)GetValue(MiddleMouseClickedCommandProperty); }
             get { return (ICommand)GetValue(MiddleMouseClickedCommandProperty); }
             set { SetValue(MiddleMouseClickedCommandProperty, value); }
             set { SetValue(MiddleMouseClickedCommandProperty, value); }
         }
         }
-
-        // Using a DependencyProperty as the backing store for MiddleMouseClickedCommand.  This enables animation, styling, binding, etc...
-        public static readonly DependencyProperty MiddleMouseClickedCommandProperty =
-            DependencyProperty.Register("MiddleMouseClickedCommand", typeof(ICommand), typeof(MainDrawingPanel), new PropertyMetadata(default(ICommand)));
 
 
         public object MiddleMouseClickedCommandParameter
         public object MiddleMouseClickedCommandParameter
         {
         {
             get { return (object)GetValue(MiddleMouseClickedCommandParameterProperty); }
             get { return (object)GetValue(MiddleMouseClickedCommandParameterProperty); }
             set { SetValue(MiddleMouseClickedCommandParameterProperty, value); }
             set { SetValue(MiddleMouseClickedCommandParameterProperty, value); }
-        }
-
-        // Using a DependencyProperty as the backing store for MiddleMouseClickedCommandParameter.  This enables animation, styling, binding, etc...
-        public static readonly DependencyProperty MiddleMouseClickedCommandParameterProperty =
-            DependencyProperty.Register("MiddleMouseClickedCommandParameter", typeof(object), typeof(MainDrawingPanel),
-                new PropertyMetadata(default(object)));
+        }
 
 
         private static void ZoomPercentegeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
         private static void ZoomPercentegeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
         {
         {
@@ -141,15 +146,6 @@ namespace PixiEditor.Views
             panel.Zoombox.ZoomTo(panel.ClickScale * ((double)e.NewValue / 100.0));
             panel.Zoombox.ZoomTo(panel.ClickScale * ((double)e.NewValue / 100.0));
         }
         }
 
 
-        public double ClickScale { get; set; }
-        public Point ClickPosition { get; set; }
-
-        public MainDrawingPanel()
-        {
-            InitializeComponent();
-            Zoombox.ZoomToSelectionModifiers = new KeyModifierCollection() { KeyModifier.RightAlt };
-        }
-
         private static void ViewportPosCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
         private static void ViewportPosCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
         {
         {
             MainDrawingPanel panel = (MainDrawingPanel)d;
             MainDrawingPanel panel = (MainDrawingPanel)d;
@@ -164,9 +160,16 @@ namespace PixiEditor.Views
 
 
         private static void TranslateZoombox(MainDrawingPanel panel, Point vector)
         private static void TranslateZoombox(MainDrawingPanel panel, Point vector)
         {
         {
-            var newPos = new Point(panel.ClickPosition.X + vector.X,
+            var newPos = new Point(
+                panel.ClickPosition.X + vector.X,
                 panel.ClickPosition.Y + vector.Y);
                 panel.ClickPosition.Y + vector.Y);
             panel.Zoombox.Position = newPos;
             panel.Zoombox.Position = newPos;
+        }
+
+        private static void OnCenterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+        {
+            MainDrawingPanel panel = (MainDrawingPanel)d;
+            panel.Zoombox.CenterContent();
         }
         }
 
 
         private void Zoombox_CurrentViewChanged(object sender, ZoomboxViewChangedEventArgs e)
         private void Zoombox_CurrentViewChanged(object sender, ZoomboxViewChangedEventArgs e)
@@ -206,12 +209,6 @@ namespace PixiEditor.Views
             Zoombox.ZoomOrigin = new Point(Math.Clamp(mousePos.X / item.Width, 0, 1), Math.Clamp(mousePos.Y / item.Height, 0, 1));
             Zoombox.ZoomOrigin = new Point(Math.Clamp(mousePos.X / item.Width, 0, 1), Math.Clamp(mousePos.Y / item.Height, 0, 1));
         }
         }
 
 
-        private static void OnCenterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
-        {
-            MainDrawingPanel panel = (MainDrawingPanel)d;
-            panel.Zoombox.CenterContent();
-        }
-
         private void Zoombox_Loaded(object sender, RoutedEventArgs e)
         private void Zoombox_Loaded(object sender, RoutedEventArgs e)
         {
         {
             if (CenterOnStart)
             if (CenterOnStart)

+ 2 - 3
PixiEditor/Views/MainWindow.xaml.cs

@@ -14,7 +14,7 @@ namespace PixiEditor
     /// </summary>
     /// </summary>
     public partial class MainWindow : Window
     public partial class MainWindow : Window
     {
     {
-        ViewModelMain viewModel;
+        private ViewModelMain viewModel;
 
 
         public MainWindow()
         public MainWindow()
         {
         {
@@ -79,8 +79,7 @@ namespace PixiEditor
                 }
                 }
                 catch (Win32Exception)
                 catch (Win32Exception)
                 {
                 {
-                    MessageBox.Show("Couldn't update without administrator rights.", "Insufficient permissions",
-                        MessageBoxButton.OK, MessageBoxImage.Error);
+                    MessageBox.Show("Couldn't update without administrator rights.", "Insufficient permissions", MessageBoxButton.OK, MessageBoxImage.Error);
                 }
                 }
             }
             }
         }
         }

+ 1 - 2
PixiEditorTests/ModelsTests/ControllersTests/MockedSinglePixelPen.cs

@@ -12,8 +12,7 @@ namespace PixiEditorTests.ModelsTests.ControllersTests
 
 
         public override LayerChange[] Use(Layer layer, Coordinates[] mouseMove, Color color)
         public override LayerChange[] Use(Layer layer, Coordinates[] mouseMove, Color color)
         {
         {
-            return Only(
-                BitmapPixelChanges.FromSingleColoredArray(new[] { mouseMove[0] }, color), 0);
+            return Only(BitmapPixelChanges.FromSingleColoredArray(new[] { mouseMove[0] }, color), 0);
         }
         }
     }
     }
 }
 }

部分文件因文件數量過多而無法顯示