Browse Source

Used Code cleanup feature in Rider IDE

ArtemK123 4 years ago
parent
commit
7d76209776
100 changed files with 1374 additions and 1511 deletions
  1. 1 0
      Custom.ruleset
  2. 2 3
      PixiEditor.UpdateInstaller/App.xaml
  3. 3 9
      PixiEditor.UpdateInstaller/App.xaml.cs
  4. 5 5
      PixiEditor.UpdateInstaller/AssemblyInfo.cs
  5. 22 19
      PixiEditor.UpdateInstaller/Extensions.cs
  6. 7 8
      PixiEditor.UpdateInstaller/MainWindow.xaml
  7. 5 6
      PixiEditor.UpdateInstaller/MainWindow.xaml.cs
  8. 0 3
      PixiEditor.UpdateInstaller/ViewModelBase.cs
  9. 21 27
      PixiEditor.UpdateInstaller/ViewModelMain.cs
  10. 4 5
      PixiEditor.UpdateModule/Asset.cs
  11. 15 11
      PixiEditor.UpdateModule/ReleaseInfo.cs
  12. 34 29
      PixiEditor.UpdateModule/UpdateChecker.cs
  13. 8 8
      PixiEditor.UpdateModule/UpdateDownloader.cs
  14. 21 18
      PixiEditor.UpdateModule/UpdateInstaller.cs
  15. 2 2
      PixiEditor.UpdateModule/UpdateProgressChangedEventArgs.cs
  16. 2 2
      PixiEditor/Helpers/Behaviours/AllowableCharactersTextBoxBehavior.cs
  17. 3 3
      PixiEditor/Helpers/Behaviours/HintTextBehavior.cs
  18. 8 8
      PixiEditor/Helpers/Behaviours/TextBoxFocusBehavior.cs
  19. 2 4
      PixiEditor/Helpers/Converters/DoubleToIntConverter.cs
  20. 9 7
      PixiEditor/Helpers/Converters/FloatNormalizeConverter.cs
  21. 1 1
      PixiEditor/Helpers/Converters/ToolSizeToIntConverter.cs
  22. 44 46
      PixiEditor/Helpers/GlobalMouseHook.cs
  23. 6 6
      PixiEditor/Helpers/RelayCommand.cs
  24. 3 3
      PixiEditor/Helpers/UI/ReversedOrderStackPanel.cs
  25. 17 17
      PixiEditor/Models/Colors/ExColor.cs
  26. 38 47
      PixiEditor/Models/Controllers/BitmapManager.cs
  27. 31 32
      PixiEditor/Models/Controllers/BitmapOperationsUtility.cs
  28. 12 13
      PixiEditor/Models/Controllers/ClipboardController.cs
  29. 2 3
      PixiEditor/Models/Controllers/MouseMovementController.cs
  30. 4 7
      PixiEditor/Models/Controllers/PixelChangesController.cs
  31. 5 5
      PixiEditor/Models/Controllers/Shortcuts/Shortcut.cs
  32. 7 7
      PixiEditor/Models/Controllers/Shortcuts/ShortcutController.cs
  33. 11 12
      PixiEditor/Models/Controllers/UndoManager.cs
  34. 6 10
      PixiEditor/Models/DataHolders/BitmapPixelChanges.cs
  35. 12 11
      PixiEditor/Models/DataHolders/Change.cs
  36. 77 87
      PixiEditor/Models/DataHolders/Document.cs
  37. 3 4
      PixiEditor/Models/DataHolders/LayerChange.cs
  38. 13 15
      PixiEditor/Models/DataHolders/Selection.cs
  39. 11 11
      PixiEditor/Models/DataHolders/SerializableDocument.cs
  40. 1 1
      PixiEditor/Models/Dialogs/ConfirmationDialog.cs
  41. 23 23
      PixiEditor/Models/Dialogs/ExportFileDialog.cs
  42. 16 16
      PixiEditor/Models/Dialogs/ImportFileDialog.cs
  43. 10 10
      PixiEditor/Models/Dialogs/NewFileDialog.cs
  44. 18 18
      PixiEditor/Models/Dialogs/ResizeDocumentDialog.cs
  45. 4 7
      PixiEditor/Models/Enums/BrightnessMode.cs
  46. 4 7
      PixiEditor/Models/Enums/CapType.cs
  47. 1 1
      PixiEditor/Models/Enums/FileType.cs
  48. 2 2
      PixiEditor/Models/Events/DocumentChangedEventArgs.cs
  49. 2 2
      PixiEditor/Models/IO/BinarySerialization.cs
  50. 5 5
      PixiEditor/Models/IO/Exporter.cs
  51. 3 6
      PixiEditor/Models/IO/Importer.cs
  52. 14 19
      PixiEditor/Models/ImageManipulation/BitmapUtils.cs
  53. 26 25
      PixiEditor/Models/ImageManipulation/Morphology.cs
  54. 4 4
      PixiEditor/Models/ImageManipulation/Transform.cs
  55. 8 8
      PixiEditor/Models/Layers/BasicLayer.cs
  56. 108 123
      PixiEditor/Models/Layers/Layer.cs
  57. 16 15
      PixiEditor/Models/Layers/SerializableLayer.cs
  58. 1 4
      PixiEditor/Models/Position/Coordinates.cs
  59. 17 19
      PixiEditor/Models/Position/CoordinatesCalculator.cs
  60. 5 7
      PixiEditor/Models/Position/MousePositionConverter.cs
  61. 2 2
      PixiEditor/Models/Tools/BitmapOperationTool.cs
  62. 5 6
      PixiEditor/Models/Tools/ShapeTool.cs
  63. 15 8
      PixiEditor/Models/Tools/Tool.cs
  64. 2 2
      PixiEditor/Models/Tools/ToolSettings/Settings/BoolSetting.cs
  65. 2 2
      PixiEditor/Models/Tools/ToolSettings/Settings/ColorSetting.cs
  66. 6 6
      PixiEditor/Models/Tools/ToolSettings/Settings/DropdownSetting.cs
  67. 5 5
      PixiEditor/Models/Tools/ToolSettings/Settings/FloatSetting.cs
  68. 5 5
      PixiEditor/Models/Tools/ToolSettings/Settings/Setting.cs
  69. 4 7
      PixiEditor/Models/Tools/ToolSettings/Settings/SizeSetting.cs
  70. 4 4
      PixiEditor/Models/Tools/ToolSettings/Toolbars/Toolbar.cs
  71. 16 16
      PixiEditor/Models/Tools/Tools/BrightnessTool.cs
  72. 43 45
      PixiEditor/Models/Tools/Tools/CircleTool.cs
  73. 2 2
      PixiEditor/Models/Tools/Tools/ColorPickerTool.cs
  74. 4 4
      PixiEditor/Models/Tools/Tools/EraserTool.cs
  75. 11 12
      PixiEditor/Models/Tools/Tools/FloodFill.cs
  76. 12 16
      PixiEditor/Models/Tools/Tools/LineTool.cs
  77. 64 77
      PixiEditor/Models/Tools/Tools/MoveTool.cs
  78. 7 6
      PixiEditor/Models/Tools/Tools/PenTool.cs
  79. 23 23
      PixiEditor/Models/Tools/Tools/RectangleTool.cs
  80. 9 10
      PixiEditor/Models/Tools/Tools/SelectTool.cs
  81. 15 21
      PixiEditor/Models/Tools/Tools/ZoomTool.cs
  82. 1 2
      PixiEditor/Styles/AnchorPointToggleButtonStyle.xaml
  83. 0 1
      PixiEditor/Styles/ComboBoxDarkStyle.xaml
  84. 1 4
      PixiEditor/Styles/DockingManagerStyle.xaml
  85. 1 2
      PixiEditor/Styles/ThemeColors.xaml
  86. 1 1
      PixiEditor/Styles/ThemeStyle.xaml
  87. 8 8
      PixiEditor/ViewModels/FeedbackDialogViewModel.cs
  88. 23 23
      PixiEditor/ViewModels/ImportFilePopupViewModel.cs
  89. 3 3
      PixiEditor/ViewModels/MenuButtonViewModel.cs
  90. 13 13
      PixiEditor/ViewModels/SaveFilePopupViewModel.cs
  91. 1 1
      PixiEditor/ViewModels/ViewModelBase.cs
  92. 205 220
      PixiEditor/ViewModels/ViewModelMain.cs
  93. 4 4
      PixiEditor/Views/AnchorPointPicker.xaml.cs
  94. 1 1
      PixiEditor/Views/ConfirmationPopup.xaml.cs
  95. 1 2
      PixiEditor/Views/EditableTextBlock.xaml.cs
  96. 1 4
      PixiEditor/Views/ImportFilePopup.xaml
  97. 19 17
      PixiEditor/Views/LayerItem.xaml
  98. 44 55
      PixiEditor/Views/LayerItem.xaml.cs
  99. 0 2
      PixiEditor/Views/MainDrawingPanel.xaml
  100. 26 33
      PixiEditor/Views/MainDrawingPanel.xaml.cs

+ 1 - 0
Custom.ruleset

@@ -2,5 +2,6 @@
 <RuleSet Name="Name" Description="Description" ToolsVersion="16.0">
 <RuleSet Name="Name" Description="Description" ToolsVersion="16.0">
     <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
     <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
         <Rule Id="SA1101" Action="None" />
         <Rule Id="SA1101" Action="None" />
+        <Rule Id="SA1633" Action="None" />
     </Rules>
     </Rules>
 </RuleSet>
 </RuleSet>

+ 2 - 3
PixiEditor.UpdateInstaller/App.xaml

@@ -1,9 +1,8 @@
 <Application x:Class="PixiEditor.UpdateInstaller.App"
 <Application x:Class="PixiEditor.UpdateInstaller.App"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-             xmlns:local="clr-namespace:PixiEditor.UpdateInstaller"
              StartupUri="MainWindow.xaml">
              StartupUri="MainWindow.xaml">
     <Application.Resources>
     <Application.Resources>
-         
+
     </Application.Resources>
     </Application.Resources>
-</Application>
+</Application>

+ 3 - 9
PixiEditor.UpdateInstaller/App.xaml.cs

@@ -1,17 +1,11 @@
-using System;
-using System.Collections.Generic;
-using System.Configuration;
-using System.Data;
-using System.Linq;
-using System.Threading.Tasks;
-using System.Windows;
+using System.Windows;
 
 
 namespace PixiEditor.UpdateInstaller
 namespace PixiEditor.UpdateInstaller
 {
 {
     /// <summary>
     /// <summary>
-    /// Interaction logic for App.xaml
+    ///     Interaction logic for App.xaml
     /// </summary>
     /// </summary>
     public partial class App : Application
     public partial class App : Application
     {
     {
     }
     }
-}
+}

+ 5 - 5
PixiEditor.UpdateInstaller/AssemblyInfo.cs

@@ -2,9 +2,9 @@ using System.Windows;
 
 
 [assembly: ThemeInfo(
 [assembly: ThemeInfo(
     ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
     ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
-                                     //(used if a resource is not found in the page,
-                                     // or application resource dictionaries)
+    //(used if a resource is not found in the page,
+    // or application resource dictionaries)
     ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
     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)
-)]
+    //(used if a resource is not found in the page,
+    // app, or any theme specific resource dictionaries)
+)]

+ 22 - 19
PixiEditor.UpdateInstaller/Extensions.cs

@@ -1,24 +1,27 @@
 using System;
 using System;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Text;
 
 
 namespace PixiEditor.UpdateInstaller
 namespace PixiEditor.UpdateInstaller
 {
 {
     public static class Extensions
     public static class Extensions
-	{
-		[System.Runtime.InteropServices.DllImport("kernel32.dll")]
-		static extern uint GetModuleFileName(IntPtr hModule, System.Text.StringBuilder lpFilename, int nSize);
-		static readonly int MAX_PATH = 255;
-		public static string GetExecutablePath()
-		{
-			if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
-			{
-				var sb = new System.Text.StringBuilder(MAX_PATH);
-				GetModuleFileName(IntPtr.Zero, sb, MAX_PATH);
-				return sb.ToString();
-			}
-			else
-			{
-				return System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
-			}
-		}
-	}
-}
+    {
+        private static readonly int MaxPath = 255;
+
+        [DllImport("kernel32.dll")]
+        private static extern uint GetModuleFileName(IntPtr hModule, StringBuilder lpFilename, int nSize);
+
+        public static string GetExecutablePath()
+        {
+            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+            {
+                var sb = new StringBuilder(MaxPath);
+                GetModuleFileName(IntPtr.Zero, sb, MaxPath);
+                return sb.ToString();
+            }
+
+            return Process.GetCurrentProcess().MainModule.FileName;
+        }
+    }
+}

+ 7 - 8
PixiEditor.UpdateInstaller/MainWindow.xaml

@@ -3,23 +3,22 @@
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
-        xmlns:local="clr-namespace:PixiEditor.UpdateInstaller"
         mc:Ignorable="d"
         mc:Ignorable="d"
         Title="MainWindow" Height="350" Width="250" Background="#2D2D30" ResizeMode="NoResize"
         Title="MainWindow" Height="350" Width="250" Background="#2D2D30" ResizeMode="NoResize"
         WindowStyle="None" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
         WindowStyle="None" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
     <WindowChrome.WindowChrome>
     <WindowChrome.WindowChrome>
         <WindowChrome ResizeBorderThickness="6"
         <WindowChrome ResizeBorderThickness="6"
-            CaptionHeight="30"/>
+                      CaptionHeight="30" />
     </WindowChrome.WindowChrome>
     </WindowChrome.WindowChrome>
     <Grid>
     <Grid>
         <Grid.RowDefinitions>
         <Grid.RowDefinitions>
-            <RowDefinition Height="130"/>
-            <RowDefinition/>
+            <RowDefinition Height="130" />
+            <RowDefinition />
         </Grid.RowDefinitions>
         </Grid.RowDefinitions>
-        <Image Source="Images/PixiEditorLogo.png" Width="75" Height="75" Grid.Row="0"/>
+        <Image Source="Images/PixiEditorLogo.png" Width="75" Height="75" Grid.Row="0" />
         <StackPanel Grid.Row="1" Margin="0,20,0,0">
         <StackPanel Grid.Row="1" Margin="0,20,0,0">
-            <Label Content="Installing update" HorizontalAlignment="Center" Foreground="White" FontSize="20"/>
-            <ProgressBar Margin="0,20,0,0" Height="20" Width="200" Value="{Binding ProgressValue}"/>
+            <Label Content="Installing update" HorizontalAlignment="Center" Foreground="White" FontSize="20" />
+            <ProgressBar Margin="0,20,0,0" Height="20" Width="200" Value="{Binding ProgressValue}" />
         </StackPanel>
         </StackPanel>
     </Grid>
     </Grid>
-</Window>
+</Window>

+ 5 - 6
PixiEditor.UpdateInstaller/MainWindow.xaml.cs

@@ -1,14 +1,13 @@
 using System;
 using System;
 using System.Diagnostics;
 using System.Diagnostics;
 using System.IO;
 using System.IO;
-using System.Reflection;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using System.Windows;
 using System.Windows;
 
 
 namespace PixiEditor.UpdateInstaller
 namespace PixiEditor.UpdateInstaller
 {
 {
     /// <summary>
     /// <summary>
-    /// Interaction logic for MainWindow.xaml
+    ///     Interaction logic for MainWindow.xaml
     /// </summary>
     /// </summary>
     public partial class MainWindow : Window
     public partial class MainWindow : Window
     {
     {
@@ -20,25 +19,25 @@ namespace PixiEditor.UpdateInstaller
 
 
         private async void Window_Loaded(object sender, RoutedEventArgs e)
         private async void Window_Loaded(object sender, RoutedEventArgs e)
         {
         {
-            ViewModelMain vmm = ((ViewModelMain)DataContext);
+            var vmm = (ViewModelMain) DataContext;
             await Task.Run(() =>
             await Task.Run(() =>
             {
             {
                 try
                 try
                 {
                 {
                     vmm.InstallUpdate();
                     vmm.InstallUpdate();
                 }
                 }
-                catch(Exception ex)
+                catch (Exception ex)
                 {
                 {
                     MessageBox.Show(ex.Message, "Update error", MessageBoxButton.OK, MessageBoxImage.Error);
                     MessageBox.Show(ex.Message, "Update error", MessageBoxButton.OK, MessageBoxImage.Error);
                     File.AppendAllText("ErrorLog.txt", $"Error PixiEditor.UpdateInstaller: {DateTime.Now}\n{ex.Message}\n{ex.StackTrace}\n-----\n");
                     File.AppendAllText("ErrorLog.txt", $"Error PixiEditor.UpdateInstaller: {DateTime.Now}\n{ex.Message}\n{ex.StackTrace}\n-----\n");
                 }
                 }
                 finally
                 finally
                 {
                 {
-                    string pixiEditorExecutablePath = Directory.GetFiles(vmm.UpdateDirectory, "PixiEditor.exe")[0];
+                    var pixiEditorExecutablePath = Directory.GetFiles(vmm.UpdateDirectory, "PixiEditor.exe")[0];
                     Process.Start(pixiEditorExecutablePath);
                     Process.Start(pixiEditorExecutablePath);
                 }
                 }
             });
             });
             Close();
             Close();
         }
         }
     }
     }
-}
+}

+ 0 - 3
PixiEditor.UpdateInstaller/ViewModelBase.cs

@@ -1,7 +1,4 @@
 using System.ComponentModel;
 using System.ComponentModel;
-using System.Linq;
-using System.Windows;
-using System.Windows.Input;
 
 
 namespace PixiEditor.UpdateInstaller
 namespace PixiEditor.UpdateInstaller
 {
 {

+ 21 - 27
PixiEditor.UpdateInstaller/ViewModelMain.cs

@@ -1,39 +1,18 @@
 using System;
 using System;
-using System.Collections.Generic;
-using System.Diagnostics;
 using System.IO;
 using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows;
+using PixiEditor.UpdateModule;
 
 
 namespace PixiEditor.UpdateInstaller
 namespace PixiEditor.UpdateInstaller
 {
 {
     public class ViewModelMain : ViewModelBase
     public class ViewModelMain : ViewModelBase
     {
     {
-        public ViewModelMain Current { get; private set; }
-        public UpdateModule.UpdateInstaller Installer { get; set; }
-
-        public string UpdateDirectory { get; private set; }
-
-        private float _progressValue;
-
-        public float ProgressValue
-        {
-            get => _progressValue;
-            set 
-            { 
-                _progressValue = value;
-                RaisePropertyChanged(nameof(ProgressValue));
-            }
-        }
+        private float progressValue;
 
 
         public ViewModelMain()
         public ViewModelMain()
         {
         {
             Current = this;
             Current = this;
 
 
-            string updateDirectory = Path.GetDirectoryName(Extensions.GetExecutablePath());
+            var updateDirectory = Path.GetDirectoryName(Extensions.GetExecutablePath());
 
 
 #if DEBUG
 #if DEBUG
             updateDirectory = Environment.GetCommandLineArgs()[1];
             updateDirectory = Environment.GetCommandLineArgs()[1];
@@ -41,9 +20,24 @@ namespace PixiEditor.UpdateInstaller
             UpdateDirectory = updateDirectory;
             UpdateDirectory = updateDirectory;
         }
         }
 
 
+        public ViewModelMain Current { get; }
+        public UpdateModule.UpdateInstaller Installer { get; set; }
+
+        public string UpdateDirectory { get; }
+
+        public float ProgressValue
+        {
+            get => progressValue;
+            set
+            {
+                progressValue = value;
+                RaisePropertyChanged(nameof(ProgressValue));
+            }
+        }
+
         public void InstallUpdate()
         public void InstallUpdate()
         {
         {
-            string[] files = Directory.GetFiles(UpdateDirectory, "update-*.zip");
+            var files = Directory.GetFiles(UpdateDirectory, "update-*.zip");
 
 
             if (files.Length > 0)
             if (files.Length > 0)
             {
             {
@@ -57,9 +51,9 @@ namespace PixiEditor.UpdateInstaller
             }
             }
         }
         }
 
 
-        private void Installer_ProgressChanged(object sender, UpdateModule.UpdateProgressChangedEventArgs e)
+        private void Installer_ProgressChanged(object sender, UpdateProgressChangedEventArgs e)
         {
         {
             ProgressValue = e.Progress;
             ProgressValue = e.Progress;
         }
         }
     }
     }
-}
+}

+ 4 - 5
PixiEditor.UpdateModule/Asset.cs

@@ -1,7 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Text.Json.Serialization;
+using System.Text.Json.Serialization;
 
 
 namespace PixiEditor.UpdateModule
 namespace PixiEditor.UpdateModule
 {
 {
@@ -9,9 +6,11 @@ namespace PixiEditor.UpdateModule
     {
     {
         [JsonPropertyName("url")]
         [JsonPropertyName("url")]
         public string Url { get; set; }
         public string Url { get; set; }
+
         [JsonPropertyName("name")]
         [JsonPropertyName("name")]
         public string Name { get; set; }
         public string Name { get; set; }
+
         [JsonPropertyName("content_type")]
         [JsonPropertyName("content_type")]
         public string ContentType { get; set; }
         public string ContentType { get; set; }
     }
     }
-}
+}

+ 15 - 11
PixiEditor.UpdateModule/ReleaseInfo.cs

@@ -1,26 +1,30 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Text.Json.Serialization;
+using System.Text.Json.Serialization;
 
 
 namespace PixiEditor.UpdateModule
 namespace PixiEditor.UpdateModule
 {
 {
     public class ReleaseInfo
     public class ReleaseInfo
     {
     {
+        public ReleaseInfo()
+        {
+        }
+
+        public ReleaseInfo(bool dataFetchSuccessful)
+        {
+            WasDataFetchSuccessful = dataFetchSuccessful;
+        }
+
         [JsonPropertyName("tag_name")]
         [JsonPropertyName("tag_name")]
         public string TagName { get; set; }
         public string TagName { get; set; }
+
         [JsonPropertyName("draft")]
         [JsonPropertyName("draft")]
         public bool IsDraft { get; set; }
         public bool IsDraft { get; set; }
+
         [JsonPropertyName("prerelease")]
         [JsonPropertyName("prerelease")]
         public bool IsPrerelease { get; set; }
         public bool IsPrerelease { get; set; }
+
         [JsonPropertyName("assets")]
         [JsonPropertyName("assets")]
         public Asset[] Assets { get; set; }
         public Asset[] Assets { get; set; }
-        public bool WasDataFetchSuccessfull { get; set; } = true;
 
 
-        public ReleaseInfo() { }
-        public ReleaseInfo(bool dataFetchSuccessfull)
-        {
-            WasDataFetchSuccessfull = dataFetchSuccessfull;
-        }
+        public bool WasDataFetchSuccessful { get; set; } = true;
     }
     }
-}
+}

+ 34 - 29
PixiEditor.UpdateModule/UpdateChecker.cs

@@ -1,5 +1,5 @@
-using System;
-using System.Globalization;
+using System.Globalization;
+using System.Net;
 using System.Net.Http;
 using System.Net.Http;
 using System.Text.Json;
 using System.Text.Json;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
@@ -8,63 +8,68 @@ namespace PixiEditor.UpdateModule
 {
 {
     public class UpdateChecker
     public class UpdateChecker
     {
     {
-        public const string ReleaseApiUrl = "https://api.github.com/repos/PixiEditor/PixiEditor/releases/latest";
-        public string CurrentVersionTag { get; set; }
-
-        public ReleaseInfo LatestReleaseInfo { get; set; }
+        private const string ReleaseApiUrl = "https://api.github.com/repos/PixiEditor/PixiEditor/releases/latest";
 
 
         public UpdateChecker(string currentVersionTag)
         public UpdateChecker(string currentVersionTag)
         {
         {
             CurrentVersionTag = currentVersionTag;
             CurrentVersionTag = currentVersionTag;
         }
         }
 
 
-        public async Task<bool> CheckUpdateAvailable()
-        {
-            LatestReleaseInfo = await GetLatestReleaseInfo();
-            return CheckUpdateAvailable(LatestReleaseInfo);
-        }
+        public ReleaseInfo LatestReleaseInfo { get; private set; }
 
 
-        public bool CheckUpdateAvailable(ReleaseInfo latestRelease)
-        {          
-            return latestRelease.WasDataFetchSuccessfull && VersionBigger(CurrentVersionTag, latestRelease.TagName);
-        }
+        private string CurrentVersionTag { get; }
 
 
         /// <summary>
         /// <summary>
-        /// Compares version strings and returns true if newVer > originalVer
+        ///     Compares version strings and returns true if newVer > originalVer.
         /// </summary>
         /// </summary>
-        /// <param name="originalVer"></param>
+        /// <param name="originalVer" />
         /// <param name="newVer"></param>
         /// <param name="newVer"></param>
         /// <returns></returns>
         /// <returns></returns>
         public static bool VersionBigger(string originalVer, string newVer)
         public static bool VersionBigger(string originalVer, string newVer)
         {
         {
-            if(ParseVersionString(originalVer, out float ver1))
+            if (!ParseVersionString(originalVer, out var ver1))
             {
             {
-                if (ParseVersionString(newVer, out float ver2))
-                {
-                    return ver2 > ver1;
-                }
+                return false;
+            }
+
+            if (ParseVersionString(newVer, out var ver2))
+            {
+                return ver2 > ver1;
             }
             }
+
             return false;
             return false;
         }
         }
 
 
-        private static bool ParseVersionString(string versionString, out float version)
+        public async Task<bool> CheckUpdateAvailable()
+        {
+            LatestReleaseInfo = await GetLatestReleaseInfo_Async();
+            return CheckUpdateAvailable(LatestReleaseInfo);
+        }
+
+        public bool CheckUpdateAvailable(ReleaseInfo latestRelease)
         {
         {
-            return float.TryParse(versionString.Replace(".", "").Insert(1, "."), NumberStyles.Any, CultureInfo.InvariantCulture, out version);
+            return latestRelease.WasDataFetchSuccessful && VersionBigger(CurrentVersionTag, latestRelease.TagName);
         }
         }
 
 
-        public async Task<ReleaseInfo> GetLatestReleaseInfo()
+        private static async Task<ReleaseInfo> GetLatestReleaseInfo_Async()
         {
         {
-            using(HttpClient client = new HttpClient())
+            using (var client = new HttpClient())
             {
             {
                 client.DefaultRequestHeaders.Add("User-Agent", "PixiEditor");
                 client.DefaultRequestHeaders.Add("User-Agent", "PixiEditor");
                 var response = await client.GetAsync(ReleaseApiUrl);
                 var response = await client.GetAsync(ReleaseApiUrl);
-                if(response.StatusCode == System.Net.HttpStatusCode.OK)
+                if (response.StatusCode == HttpStatusCode.OK)
                 {
                 {
-                    string content = await response.Content.ReadAsStringAsync();
+                    var content = await response.Content.ReadAsStringAsync();
                     return JsonSerializer.Deserialize<ReleaseInfo>(content);
                     return JsonSerializer.Deserialize<ReleaseInfo>(content);
                 }
                 }
             }
             }
+
             return new ReleaseInfo(false);
             return new ReleaseInfo(false);
         }
         }
+
+        private static bool ParseVersionString(string versionString, out float version)
+        {
+            return float.TryParse(versionString.Replace(".", string.Empty).Insert(1, "."), NumberStyles.Any, CultureInfo.InvariantCulture, out version);
+        }
     }
     }
-}
+}

+ 8 - 8
PixiEditor.UpdateModule/UpdateDownloader.cs

@@ -3,26 +3,26 @@ using System.IO;
 using System.Linq;
 using System.Linq;
 using System.Net;
 using System.Net;
 using System.Net.Http;
 using System.Net.Http;
-using System.Text;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 
 
 namespace PixiEditor.UpdateModule
 namespace PixiEditor.UpdateModule
 {
 {
     public static class UpdateDownloader
     public static class UpdateDownloader
     {
     {
-        public static string DownloadLocation = AppDomain.CurrentDomain.BaseDirectory;
+        public static readonly string DownloadLocation = AppDomain.CurrentDomain.BaseDirectory;
+
         public static async Task DownloadReleaseZip(ReleaseInfo release)
         public static async Task DownloadReleaseZip(ReleaseInfo release)
         {
         {
-            Asset matchingAsset = GetMatchingAsset(release);
+            var matchingAsset = GetMatchingAsset(release);
 
 
-            using (HttpClient client = new HttpClient())
+            using (var client = new HttpClient())
             {
             {
                 client.DefaultRequestHeaders.Add("User-Agent", "PixiEditor");
                 client.DefaultRequestHeaders.Add("User-Agent", "PixiEditor");
                 client.DefaultRequestHeaders.Add("Accept", "application/octet-stream");
                 client.DefaultRequestHeaders.Add("Accept", "application/octet-stream");
                 var response = await client.GetAsync(matchingAsset.Url);
                 var response = await client.GetAsync(matchingAsset.Url);
                 if (response.StatusCode == HttpStatusCode.OK)
                 if (response.StatusCode == HttpStatusCode.OK)
                 {
                 {
-                    byte[] bytes = await response.Content.ReadAsByteArrayAsync();
+                    var bytes = await response.Content.ReadAsByteArrayAsync();
                     File.WriteAllBytes(Path.Join(DownloadLocation, $"update-{release.TagName}.zip"), bytes);
                     File.WriteAllBytes(Path.Join(DownloadLocation, $"update-{release.TagName}.zip"), bytes);
                 }
                 }
             }
             }
@@ -30,9 +30,9 @@ namespace PixiEditor.UpdateModule
 
 
         private static Asset GetMatchingAsset(ReleaseInfo release)
         private static Asset GetMatchingAsset(ReleaseInfo release)
         {
         {
-            string arch = IntPtr.Size == 8 ? "x64" : "x86";
+            var arch = IntPtr.Size == 8 ? "x64" : "x86";
             return release.Assets.First(x => x.ContentType == "application/x-zip-compressed"
             return release.Assets.First(x => x.ContentType == "application/x-zip-compressed"
-            && x.Name.Contains(arch));
+                                             && x.Name.Contains(arch));
         }
         }
     }
     }
-}
+}

+ 21 - 18
PixiEditor.UpdateModule/UpdateInstaller.cs

@@ -8,36 +8,39 @@ namespace PixiEditor.UpdateModule
     public class UpdateInstaller
     public class UpdateInstaller
     {
     {
         public const string TargetDirectoryName = "UpdateFiles";
         public const string TargetDirectoryName = "UpdateFiles";
+        private float progress;
+
+        public UpdateInstaller(string archiveFileName)
+        {
+            ArchiveFileName = archiveFileName;
+        }
 
 
         public event EventHandler<UpdateProgressChangedEventArgs> ProgressChanged;
         public event EventHandler<UpdateProgressChangedEventArgs> ProgressChanged;
-        private float _progress = 0;
-        public float Progress 
+
+        public float Progress
         {
         {
-            get => _progress;
+            get => progress;
             set
             set
             {
             {
-                _progress = value;
+                progress = value;
                 ProgressChanged?.Invoke(this, new UpdateProgressChangedEventArgs(value));
                 ProgressChanged?.Invoke(this, new UpdateProgressChangedEventArgs(value));
             }
             }
         }
         }
-        public string ArchiveFileName { get; set; }
 
 
-        public UpdateInstaller(string archiveFileName)
-        {
-            ArchiveFileName = archiveFileName;
-        }
+        public string ArchiveFileName { get; set; }
 
 
         public void Install()
         public void Install()
         {
         {
             var processes = Process.GetProcessesByName("PixiEditor");
             var processes = Process.GetProcessesByName("PixiEditor");
-            if(processes.Length > 0)
+            if (processes.Length > 0)
             {
             {
                 processes[0].WaitForExit();
                 processes[0].WaitForExit();
             }
             }
+
             ZipFile.ExtractToDirectory(ArchiveFileName, TargetDirectoryName, true);
             ZipFile.ExtractToDirectory(ArchiveFileName, TargetDirectoryName, true);
-            Progress = 25; //25% for unzip
-            string dirWithFiles = Directory.GetDirectories(TargetDirectoryName)[0];
-            string[] files = Directory.GetFiles(dirWithFiles);
+            Progress = 25; // 25% for unzip
+            var dirWithFiles = Directory.GetDirectories(TargetDirectoryName)[0];
+            var files = Directory.GetFiles(dirWithFiles);
             CopyFilesToDestination(files);
             CopyFilesToDestination(files);
             DeleteArchive();
             DeleteArchive();
             Progress = 100;
             Progress = 100;
@@ -50,14 +53,14 @@ namespace PixiEditor.UpdateModule
 
 
         private void CopyFilesToDestination(string[] files)
         private void CopyFilesToDestination(string[] files)
         {
         {
-            float fileCopiedVal = 74f / files.Length; //74% is reserved for copying
-            string destinationDir = Path.GetDirectoryName(ArchiveFileName);
-            foreach (string file in files)
+            var fileCopiedVal = 74f / files.Length; // 74% is reserved for copying
+            var destinationDir = Path.GetDirectoryName(ArchiveFileName);
+            foreach (var file in files)
             {
             {
-                string targetFileName = Path.GetFileName(file);
+                var targetFileName = Path.GetFileName(file);
                 File.Copy(file, Path.Join(destinationDir, targetFileName), true);
                 File.Copy(file, Path.Join(destinationDir, targetFileName), true);
                 Progress += fileCopiedVal;
                 Progress += fileCopiedVal;
             }
             }
         }
         }
     }
     }
-}
+}

+ 2 - 2
PixiEditor.UpdateModule/UpdateProgressChangedEventArgs.cs

@@ -4,11 +4,11 @@ namespace PixiEditor.UpdateModule
 {
 {
     public class UpdateProgressChangedEventArgs : EventArgs
     public class UpdateProgressChangedEventArgs : EventArgs
     {
     {
-        public float Progress { get; set; }
-
         public UpdateProgressChangedEventArgs(float progress)
         public UpdateProgressChangedEventArgs(float progress)
         {
         {
             Progress = progress;
             Progress = progress;
         }
         }
+
+        public float Progress { get; set; }
     }
     }
 }
 }

+ 2 - 2
PixiEditor/Helpers/Behaviours/AllowableCharactersTextBoxBehavior.cs

@@ -40,7 +40,7 @@ namespace PixiEditor.Helpers.Behaviours
         {
         {
             if (e.DataObject.GetDataPresent(DataFormats.Text))
             if (e.DataObject.GetDataPresent(DataFormats.Text))
             {
             {
-                string text = Convert.ToString(e.DataObject.GetData(DataFormats.Text));
+                var text = Convert.ToString(e.DataObject.GetData(DataFormats.Text));
 
 
                 if (!IsValid(text, true)) e.CancelCommand();
                 if (!IsValid(text, true)) e.CancelCommand();
             }
             }
@@ -78,7 +78,7 @@ namespace PixiEditor.Helpers.Behaviours
         {
         {
             var countOfSelectedChars = AssociatedObject.SelectedText.Length;
             var countOfSelectedChars = AssociatedObject.SelectedText.Length;
             var caretIndex = AssociatedObject.CaretIndex;
             var caretIndex = AssociatedObject.CaretIndex;
-            string text = AssociatedObject.Text;
+            var text = AssociatedObject.Text;
 
 
             if (countOfSelectedChars > 0 || paste)
             if (countOfSelectedChars > 0 || paste)
             {
             {

+ 3 - 3
PixiEditor/Helpers/Behaviours/HintTextBehavior.cs

@@ -12,7 +12,7 @@ namespace PixiEditor.Helpers.Behaviours
             DependencyProperty.Register("Hint", typeof(string), typeof(HintTextBehavior),
             DependencyProperty.Register("Hint", typeof(string), typeof(HintTextBehavior),
                 new PropertyMetadata(string.Empty));
                 new PropertyMetadata(string.Empty));
 
 
-        private Brush _textColor;
+        private Brush textColor;
 
 
         public string Hint
         public string Hint
         {
         {
@@ -26,7 +26,7 @@ namespace PixiEditor.Helpers.Behaviours
             base.OnAttached();
             base.OnAttached();
             AssociatedObject.GotFocus += AssociatedObject_GotFocus;
             AssociatedObject.GotFocus += AssociatedObject_GotFocus;
             AssociatedObject.LostFocus += AssociatedObject_LostFocus;
             AssociatedObject.LostFocus += AssociatedObject_LostFocus;
-            _textColor = AssociatedObject.Foreground;
+            textColor = AssociatedObject.Foreground;
             SetHint(true);
             SetHint(true);
         }
         }
 
 
@@ -50,7 +50,7 @@ namespace PixiEditor.Helpers.Behaviours
             else
             else
             {
             {
                 AssociatedObject.Text = string.Empty;
                 AssociatedObject.Text = string.Empty;
-                AssociatedObject.Foreground = _textColor;
+                AssociatedObject.Foreground = textColor;
             }
             }
         }
         }
 
 

+ 8 - 8
PixiEditor/Helpers/Behaviours/TextBoxFocusBehavior.cs

@@ -14,8 +14,8 @@ namespace PixiEditor.Helpers.Behaviours
                 new PropertyMetadata(false));
                 new PropertyMetadata(false));
 
 
 
 
-        private string _oldText; //Value of textbox before editing
-        private bool _valueConverted; //This bool is used to avoid double convertion if enter is hitted
+        private string oldText; //Value of textbox before editing
+        private bool valueConverted; //This bool is used to avoid double convertion if enter is hitted
 
 
         public bool FillSize
         public bool FillSize
         {
         {
@@ -58,8 +58,8 @@ namespace PixiEditor.Helpers.Behaviours
             AssociatedObject.SelectAll();
             AssociatedObject.SelectAll();
             if (FillSize)
             if (FillSize)
             {
             {
-                _valueConverted = false;
-                _oldText = AssociatedObject.Text; //Sets old value when keyboard is focused on object
+                valueConverted = false;
+                oldText = AssociatedObject.Text; //Sets old value when keyboard is focused on object
             }
             }
         }
         }
 
 
@@ -88,13 +88,13 @@ namespace PixiEditor.Helpers.Behaviours
         /// </summary>
         /// </summary>
         private void ConvertValue()
         private void ConvertValue()
         {
         {
-            if (_valueConverted || FillSize == false) return;
+            if (valueConverted || FillSize == false) return;
 
 
-            if (int.TryParse(Regex.Replace(AssociatedObject.Text, "\\p{L}", ""), out int result) && result > 0)
+            if (int.TryParse(Regex.Replace(AssociatedObject.Text, "\\p{L}", ""), out var result) && result > 0)
                 AssociatedObject.Text = $"{AssociatedObject.Text} px";
                 AssociatedObject.Text = $"{AssociatedObject.Text} px";
             else //If text in textbox isn't number, set it to old value
             else //If text in textbox isn't number, set it to old value
-                AssociatedObject.Text = _oldText;
-            _valueConverted = true;
+                AssociatedObject.Text = oldText;
+            valueConverted = true;
         }
         }
     }
     }
 }
 }

+ 2 - 4
PixiEditor/Helpers/Converters/DoubleToIntConverter.cs

@@ -1,7 +1,5 @@
 using System;
 using System;
-using System.Collections.Generic;
 using System.Globalization;
 using System.Globalization;
-using System.Text;
 using System.Windows.Data;
 using System.Windows.Data;
 
 
 namespace PixiEditor.Helpers.Converters
 namespace PixiEditor.Helpers.Converters
@@ -12,7 +10,7 @@ namespace PixiEditor.Helpers.Converters
         {
         {
             if (value is double || value is float)
             if (value is double || value is float)
             {
             {
-                double val = (double) value;
+                var val = (double) value;
                 return (int) val;
                 return (int) val;
             }
             }
 
 
@@ -24,4 +22,4 @@ namespace PixiEditor.Helpers.Converters
             throw new NotImplementedException();
             throw new NotImplementedException();
         }
         }
     }
     }
-}
+}

+ 9 - 7
PixiEditor/Helpers/Converters/FloatNormalizeConverter.cs

@@ -1,17 +1,19 @@
 using System;
 using System;
-using System.Collections.Generic;
 using System.Globalization;
 using System.Globalization;
-using System.Text;
 using System.Windows.Data;
 using System.Windows.Data;
 
 
 namespace PixiEditor.Helpers.Converters
 namespace PixiEditor.Helpers.Converters
 {
 {
     public class FloatNormalizeConverter : IValueConverter
     public class FloatNormalizeConverter : IValueConverter
     {
     {
-        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => 
-            (float)value * 100;
+        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+        {
+            return (float) value * 100;
+        }
 
 
-        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => 
-            (float) value / 100;
+        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+        {
+            return (float) value / 100;
+        }
     }
     }
-}
+}

+ 1 - 1
PixiEditor/Helpers/Converters/ToolSizeToIntConverter.cs

@@ -17,7 +17,7 @@ namespace PixiEditor.Helpers
         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
         {
         {
             if (string.IsNullOrWhiteSpace(value as string)) return null;
             if (string.IsNullOrWhiteSpace(value as string)) return null;
-            string slicedString = value.ToString().Split(' ').First();
+            var slicedString = value.ToString().Split(' ').First();
             slicedString = Regex.Replace(slicedString, "\\p{L}", "");
             slicedString = Regex.Replace(slicedString, "\\p{L}", "");
             if (slicedString == "") return null;
             if (slicedString == "") return null;
             return int.Parse(slicedString);
             return int.Parse(slicedString);

+ 44 - 46
PixiEditor/Helpers/GlobalMouseHook.cs

@@ -11,11 +11,13 @@ namespace PixiEditor.Helpers
     [ExcludeFromCodeCoverage]
     [ExcludeFromCodeCoverage]
     public static class GlobalMouseHook
     public static class GlobalMouseHook
     {
     {
-        private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
-        private static int _mouseHookHandle;
-        private static HookProc _mouseDelegate;
+        private const int WhMouseLl = 14;
+        private const int WmLbuttonup = 0x0202;
+        private static int mouseHookHandle;
+        private static HookProc mouseDelegate;
 
 
         private static event MouseUpEventHandler MouseUp;
         private static event MouseUpEventHandler MouseUp;
+
         public static event MouseUpEventHandler OnMouseUp
         public static event MouseUpEventHandler OnMouseUp
         {
         {
             add
             add
@@ -37,14 +39,14 @@ namespace PixiEditor.Helpers
 
 
         private static void Unsubscribe()
         private static void Unsubscribe()
         {
         {
-            if (_mouseHookHandle != 0)
+            if (mouseHookHandle != 0)
             {
             {
-                int result = UnhookWindowsHookEx(_mouseHookHandle);
-                _mouseHookHandle = 0;
-                _mouseDelegate = null;
+                var result = UnhookWindowsHookEx(mouseHookHandle);
+                mouseHookHandle = 0;
+                mouseDelegate = null;
                 if (result == 0)
                 if (result == 0)
                 {
                 {
-                    int errorCode = Marshal.GetLastWin32Error();
+                    var errorCode = Marshal.GetLastWin32Error();
                     throw new Win32Exception(errorCode);
                     throw new Win32Exception(errorCode);
                 }
                 }
             }
             }
@@ -52,17 +54,17 @@ namespace PixiEditor.Helpers
 
 
         private static void Subscribe()
         private static void Subscribe()
         {
         {
-            if (_mouseHookHandle == 0)
+            if (mouseHookHandle == 0)
             {
             {
-                _mouseDelegate = MouseHookProc;
-                _mouseHookHandle = SetWindowsHookEx(
-                    WH_MOUSE_LL,
-                    _mouseDelegate,
+                mouseDelegate = MouseHookProc;
+                mouseHookHandle = SetWindowsHookEx(
+                    WhMouseLl,
+                    mouseDelegate,
                     GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName),
                     GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName),
                     0);
                     0);
-                if (_mouseHookHandle == 0)
+                if (mouseHookHandle == 0)
                 {
                 {
-                    int errorCode = Marshal.GetLastWin32Error();
+                    var errorCode = Marshal.GetLastWin32Error();
                     throw new Win32Exception(errorCode);
                     throw new Win32Exception(errorCode);
                 }
                 }
             }
             }
@@ -72,41 +74,18 @@ namespace PixiEditor.Helpers
         {
         {
             if (nCode >= 0)
             if (nCode >= 0)
             {
             {
-                MSLLHOOKSTRUCT mouseHookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
-                if (wParam == WM_LBUTTONUP)
-                {
+                var mouseHookStruct = (Msllhookstruct) Marshal.PtrToStructure(lParam, typeof(Msllhookstruct));
+                if (wParam == WmLbuttonup)
                     if (MouseUp != null)
                     if (MouseUp != null)
-                    {
-                        MouseUp.Invoke(null, new Point(mouseHookStruct.pt.x, mouseHookStruct.pt.y));
-                    }
-                }
+                        MouseUp.Invoke(null, new System.Windows.Point(mouseHookStruct.pt.x, mouseHookStruct.pt.y));
             }
             }
-            return CallNextHookEx(_mouseHookHandle, nCode, wParam, lParam);
-        }
-
-        private const int WH_MOUSE_LL = 14;
-        private const int WM_LBUTTONUP = 0x0202;
 
 
-        [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;
+            return CallNextHookEx(mouseHookHandle, nCode, wParam, lParam);
         }
         }
 
 
-        [DllImport("user32.dll", 
+        [DllImport("user32.dll",
             CharSet = CharSet.Auto,
             CharSet = CharSet.Auto,
-            CallingConvention = CallingConvention.StdCall, 
+            CallingConvention = CallingConvention.StdCall,
             SetLastError = true)]
             SetLastError = true)]
         private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
         private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
 
 
@@ -118,14 +97,33 @@ namespace PixiEditor.Helpers
         private static extern int UnhookWindowsHookEx(int idHook);
         private static extern int UnhookWindowsHookEx(int idHook);
 
 
         [DllImport(
         [DllImport(
-            "user32.dll", 
+            "user32.dll",
             CharSet = CharSet.Auto,
             CharSet = CharSet.Auto,
             CallingConvention = CallingConvention.StdCall)]
             CallingConvention = CallingConvention.StdCall)]
         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);
+
+        private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
+
+        [StructLayout(LayoutKind.Sequential)]
+        private struct Point
+        {
+            public readonly int x;
+            public readonly int y;
+        }
+
+        [StructLayout(LayoutKind.Sequential)]
+        private struct Msllhookstruct
+        {
+            public readonly Point pt;
+            public readonly uint mouseData;
+            public readonly uint flags;
+            public readonly uint time;
+            public readonly IntPtr dwExtraInfo;
+        }
     }
     }
 
 
     public delegate void MouseUpEventHandler(object sender, Point p);
     public delegate void MouseUpEventHandler(object sender, Point p);
-}
+}

+ 6 - 6
PixiEditor/Helpers/RelayCommand.cs

@@ -7,8 +7,8 @@ namespace PixiEditor.Helpers
     {
     {
         #region Fields
         #region Fields
 
 
-        private readonly Action<object> _execute;
-        private readonly Predicate<object> _canExecute;
+        private readonly Action<object> execute;
+        private readonly Predicate<object> canExecute;
 
 
         #endregion // Fields
         #endregion // Fields
 
 
@@ -24,8 +24,8 @@ namespace PixiEditor.Helpers
             if (execute == null)
             if (execute == null)
                 throw new ArgumentNullException("execute");
                 throw new ArgumentNullException("execute");
 
 
-            _execute = execute;
-            _canExecute = canExecute;
+            this.execute = execute;
+            this.canExecute = canExecute;
         }
         }
 
 
         #endregion // Constructors
         #endregion // Constructors
@@ -34,7 +34,7 @@ namespace PixiEditor.Helpers
 
 
         public bool CanExecute(object parameter)
         public bool CanExecute(object parameter)
         {
         {
-            return _canExecute == null ? true : _canExecute(parameter);
+            return canExecute == null ? true : canExecute(parameter);
         }
         }
 
 
         public event EventHandler CanExecuteChanged
         public event EventHandler CanExecuteChanged
@@ -45,7 +45,7 @@ namespace PixiEditor.Helpers
 
 
         public void Execute(object parameter)
         public void Execute(object parameter)
         {
         {
-            _execute(parameter);
+            execute(parameter);
         }
         }
 
 
         #endregion // ICommand Members
         #endregion // ICommand Members

+ 3 - 3
PixiEditor/Helpers/UI/ReversedOrderStackPanel.cs

@@ -9,12 +9,12 @@ namespace PixiEditor.Helpers.UI
     {
     {
         protected override Size ArrangeOverride(Size arrangeSize)
         protected override Size ArrangeOverride(Size arrangeSize)
         {
         {
-            bool fHorizontal = Orientation == Orientation.Horizontal;
+            var fHorizontal = Orientation == Orientation.Horizontal;
             var rcChild = new Rect(arrangeSize);
             var rcChild = new Rect(arrangeSize);
-            double previousChildSize = 0.0;
+            var previousChildSize = 0.0;
 
 
             var children = InternalChildren.Cast<UIElement>().Reverse();
             var children = InternalChildren.Cast<UIElement>().Reverse();
-            foreach (UIElement child in children)
+            foreach (var child in children)
             {
             {
                 if (child == null)
                 if (child == null)
                     continue;
                     continue;

+ 17 - 17
PixiEditor/Models/Colors/ExColor.cs

@@ -18,13 +18,13 @@ namespace PixiEditor.Models.Colors
         /// </returns>
         /// </returns>
         public static Color ChangeColorBrightness(Color color, float correctionFactor)
         public static Color ChangeColorBrightness(Color color, float correctionFactor)
         {
         {
-            Tuple<int, float, float> hsl = RgbToHsl(color.R, color.G, color.B);
-            int h = hsl.Item1;
-            float s = hsl.Item2;
-            float l = hsl.Item3;
+            var hsl = RgbToHsl(color.R, color.G, color.B);
+            var h = hsl.Item1;
+            var s = hsl.Item2;
+            var l = hsl.Item3;
 
 
             l = Math.Clamp(l + correctionFactor, 0, 100);
             l = Math.Clamp(l + correctionFactor, 0, 100);
-            Color rgb = HslToRGB(h, s, l);
+            var rgb = HslToRgb(h, s, l);
 
 
             return Color.FromArgb(color.A, rgb.R, rgb.G, rgb.B);
             return Color.FromArgb(color.A, rgb.R, rgb.G, rgb.B);
         }
         }
@@ -41,13 +41,13 @@ namespace PixiEditor.Models.Colors
         {
         {
             int h;
             int h;
             float s, l;
             float s, l;
-            float dR = r / 255.0f;
-            float dG = g / 255.0f;
-            float dB = b / 255.0f;
+            var dR = r / 255.0f;
+            var dG = g / 255.0f;
+            var dB = b / 255.0f;
 
 
-            float min = Math.Min(Math.Min(dR, dG), dB);
-            float max = Math.Max(Math.Max(dR, dG), dB);
-            float delta = max - min;
+            var min = Math.Min(Math.Min(dR, dG), dB);
+            var max = Math.Max(Math.Max(dR, dG), dB);
+            var delta = max - min;
 
 
             l = (max + min) / 2;
             l = (max + min) / 2;
 
 
@@ -87,7 +87,7 @@ namespace PixiEditor.Models.Colors
         /// <param name="s"></param>
         /// <param name="s"></param>
         /// <param name="l"></param>
         /// <param name="l"></param>
         /// <returns>RGB Color</returns>
         /// <returns>RGB Color</returns>
-        public static Color HslToRGB(int h, float s, float l)
+        public static Color HslToRgb(int h, float s, float l)
         {
         {
             s /= 100;
             s /= 100;
             l /= 100;
             l /= 100;
@@ -102,20 +102,20 @@ namespace PixiEditor.Models.Colors
             else
             else
             {
             {
                 float v1, v2;
                 float v1, v2;
-                float hue = (float) h / 360;
+                var hue = (float) h / 360;
 
 
                 v2 = l < 0.5 ? l * (1 + s) : l + s - l * s;
                 v2 = l < 0.5 ? l * (1 + s) : l + s - l * s;
                 v1 = 2 * l - v2;
                 v1 = 2 * l - v2;
 
 
-                r = (byte) (255 * HueToRGB(v1, v2, hue + 1.0f / 3));
-                g = (byte) (255 * HueToRGB(v1, v2, hue));
-                b = (byte) (255 * HueToRGB(v1, v2, hue - 1.0f / 3));
+                r = (byte) (255 * HueToRgb(v1, v2, hue + 1.0f / 3));
+                g = (byte) (255 * HueToRgb(v1, v2, hue));
+                b = (byte) (255 * HueToRgb(v1, v2, hue - 1.0f / 3));
             }
             }
 
 
             return Color.FromRgb(r, g, b);
             return Color.FromRgb(r, g, b);
         }
         }
 
 
-        private static float HueToRGB(float v1, float v2, float hue)
+        private static float HueToRgb(float v1, float v2, float hue)
         {
         {
             if (hue < 0)
             if (hue < 0)
                 hue += 1;
                 hue += 1;

+ 38 - 47
PixiEditor/Models/Controllers/BitmapManager.cs

@@ -18,24 +18,39 @@ 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;
+            BitmapOperations = new BitmapOperationsUtility(this);
+            ReadonlyToolUtility = new ReadonlyToolUtility();
+        }
+
         public MouseMovementController MouseController { get; set; }
         public MouseMovementController MouseController { get; set; }
 
 
         public Tool SelectedTool
         public Tool SelectedTool
         {
         {
-            get => _selectedTool;
+            get => selectedTool;
             private set
             private set
             {
             {
-                _selectedTool = value;
+                selectedTool = value;
                 RaisePropertyChanged("SelectedTool");
                 RaisePropertyChanged("SelectedTool");
             }
             }
         }
         }
 
 
         public Layer PreviewLayer
         public Layer PreviewLayer
         {
         {
-            get => _previewLayer;
+            get => previewLayer;
             set
             set
             {
             {
-                _previewLayer = value;
+                previewLayer = value;
                 RaisePropertyChanged("PreviewLayer");
                 RaisePropertyChanged("PreviewLayer");
             }
             }
         }
         }
@@ -47,8 +62,8 @@ namespace PixiEditor.Models.Controllers
         public int ToolSize
         public int ToolSize
         {
         {
             get => SelectedTool.Toolbar.GetSetting<SizeSetting>("ToolSize") != null
             get => SelectedTool.Toolbar.GetSetting<SizeSetting>("ToolSize") != null
-            ? SelectedTool.Toolbar.GetSetting<SizeSetting>("ToolSize").Value
-            : 1;
+                ? SelectedTool.Toolbar.GetSetting<SizeSetting>("ToolSize").Value
+                : 1;
             set
             set
             {
             {
                 if (SelectedTool.Toolbar.GetSetting<SizeSetting>("ToolSize") is var toolSize)
                 if (SelectedTool.Toolbar.GetSetting<SizeSetting>("ToolSize") is var toolSize)
@@ -64,30 +79,15 @@ namespace PixiEditor.Models.Controllers
 
 
         public Document ActiveDocument
         public Document ActiveDocument
         {
         {
-            get => _activeDocument;
+            get => activeDocument;
             set
             set
             {
             {
-                _activeDocument = value;
+                activeDocument = value;
                 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;
-            BitmapOperations = new BitmapOperationsUtility(this);
-            ReadonlyToolUtility = new ReadonlyToolUtility();
-        }
-
         public event EventHandler<LayersChangedEventArgs> LayersChanged;
         public event EventHandler<LayersChangedEventArgs> LayersChanged;
         public event EventHandler<DocumentChangedEventArgs> DocumentChanged;
         public event EventHandler<DocumentChangedEventArgs> DocumentChanged;
 
 
@@ -134,7 +134,7 @@ namespace PixiEditor.Models.Controllers
         {
         {
             if (ActiveDocument.Layers.Count == 0) return;
             if (ActiveDocument.Layers.Count == 0) return;
 
 
-            bool wasActive = ActiveDocument.Layers[layerIndex].IsActive;
+            var wasActive = ActiveDocument.Layers[layerIndex].IsActive;
             ActiveDocument.Layers.RemoveAt(layerIndex);
             ActiveDocument.Layers.RemoveAt(layerIndex);
             if (wasActive)
             if (wasActive)
                 SetActiveLayer(0);
                 SetActiveLayer(0);
@@ -144,15 +144,10 @@ namespace PixiEditor.Models.Controllers
 
 
         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()));
             if (Mouse.LeftButton == MouseButtonState.Pressed && !IsDraggingViewport() && ActiveDocument != null)
             if (Mouse.LeftButton == MouseButtonState.Pressed && !IsDraggingViewport() && ActiveDocument != null)
-            {
-                ExecuteTool(e.NewPosition, MouseController.ClickedOnCanvas);   
-            }
-            else if (Mouse.LeftButton == MouseButtonState.Released)
-            {
-                HighlightPixels(e.NewPosition);
-            }
+                ExecuteTool(e.NewPosition, MouseController.ClickedOnCanvas);
+            else if (Mouse.LeftButton == MouseButtonState.Released) HighlightPixels(e.NewPosition);
         }
         }
 
 
         public void ExecuteTool(Coordinates newPosition, bool clickedOnCanvas)
         public void ExecuteTool(Coordinates newPosition, bool clickedOnCanvas)
@@ -160,15 +155,11 @@ namespace PixiEditor.Models.Controllers
             if (SelectedTool.CanStartOutsideCanvas || clickedOnCanvas)
             if (SelectedTool.CanStartOutsideCanvas || clickedOnCanvas)
             {
             {
                 if (IsOperationTool(SelectedTool))
                 if (IsOperationTool(SelectedTool))
-                {
                     BitmapOperations.ExecuteTool(newPosition,
                     BitmapOperations.ExecuteTool(newPosition,
-                        MouseController.LastMouseMoveCoordinates.ToList(), (BitmapOperationTool)SelectedTool);
-                }
+                        MouseController.LastMouseMoveCoordinates.ToList(), (BitmapOperationTool) SelectedTool);
                 else
                 else
-                {
                     ReadonlyToolUtility.ExecuteTool(MouseController.LastMouseMoveCoordinates.ToArray(),
                     ReadonlyToolUtility.ExecuteTool(MouseController.LastMouseMoveCoordinates.ToArray(),
-                        (ReadonlyTool)SelectedTool);
-                }
+                        (ReadonlyTool) SelectedTool);
             }
             }
         }
         }
 
 
@@ -179,13 +170,13 @@ namespace PixiEditor.Models.Controllers
 
 
         private void MouseController_StartedRecordingChanges(object sender, EventArgs e)
         private void MouseController_StartedRecordingChanges(object sender, EventArgs e)
         {
         {
-            SelectedTool.OnMouseDown(new MouseEventArgs(Mouse.PrimaryDevice, (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds()));
+            SelectedTool.OnMouseDown(new MouseEventArgs(Mouse.PrimaryDevice, (int) DateTimeOffset.UtcNow.ToUnixTimeSeconds()));
             PreviewLayer = null;
             PreviewLayer = null;
         }
         }
 
 
         private void MouseController_StoppedRecordingChanges(object sender, EventArgs e)
         private void MouseController_StoppedRecordingChanges(object sender, EventArgs e)
         {
         {
-            SelectedTool.OnMouseUp(new MouseEventArgs(Mouse.PrimaryDevice, (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds()));
+            SelectedTool.OnMouseUp(new MouseEventArgs(Mouse.PrimaryDevice, (int) DateTimeOffset.UtcNow.ToUnixTimeSeconds()));
             if (IsOperationTool(SelectedTool) && ((BitmapOperationTool) SelectedTool).RequiresPreviewLayer)
             if (IsOperationTool(SelectedTool) && ((BitmapOperationTool) SelectedTool).RequiresPreviewLayer)
                 BitmapOperations.StopAction();
                 BitmapOperations.StopAction();
         }
         }
@@ -203,11 +194,11 @@ namespace PixiEditor.Models.Controllers
         private void HighlightPixels(Coordinates newPosition)
         private void HighlightPixels(Coordinates newPosition)
         {
         {
             if (ActiveDocument == null || ActiveDocument.Layers.Count == 0 || SelectedTool.HideHighlight) return;
             if (ActiveDocument == null || ActiveDocument.Layers.Count == 0 || SelectedTool.HideHighlight) return;
-            Coordinates[] highlightArea = CoordinatesCalculator.RectangleToCoordinates(
+            var highlightArea = CoordinatesCalculator.RectangleToCoordinates(
                 CoordinatesCalculator.CalculateThicknessCenter(newPosition, ToolSize));
                 CoordinatesCalculator.CalculateThicknessCenter(newPosition, ToolSize));
             if (CanChangeHighlightOffset(highlightArea))
             if (CanChangeHighlightOffset(highlightArea))
             {
             {
-                PreviewLayer.Offset = new Thickness(highlightArea[0].X, highlightArea[0].Y,0,0);
+                PreviewLayer.Offset = new Thickness(highlightArea[0].X, highlightArea[0].Y, 0, 0);
             }
             }
             else if (!IsInsideBounds(highlightArea))
             else if (!IsInsideBounds(highlightArea))
             {
             {
@@ -223,14 +214,14 @@ namespace PixiEditor.Models.Controllers
 
 
         private bool CanChangeHighlightOffset(Coordinates[] highlightArea)
         private bool CanChangeHighlightOffset(Coordinates[] highlightArea)
         {
         {
-            return highlightArea.Length > 0 && PreviewLayer != null && 
+            return highlightArea.Length > 0 && PreviewLayer != null &&
                    IsInsideBounds(highlightArea) && highlightArea.Length == PreviewLayer.Width * PreviewLayer.Height;
                    IsInsideBounds(highlightArea) && highlightArea.Length == PreviewLayer.Width * PreviewLayer.Height;
         }
         }
 
 
         private bool IsInsideBounds(Coordinates[] highlightArea)
         private bool IsInsideBounds(Coordinates[] highlightArea)
         {
         {
             return highlightArea[0].X <= ActiveDocument.Width - 1 &&
             return highlightArea[0].X <= ActiveDocument.Width - 1 &&
-                    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;
         }
         }
 
 
@@ -261,13 +252,13 @@ namespace PixiEditor.Models.Controllers
 
 
     public class LayersChangedEventArgs : EventArgs
     public class LayersChangedEventArgs : EventArgs
     {
     {
-        public int LayerAffected { get; set; }
-        public LayerAction LayerChangeType { get; set; }
-
         public LayersChangedEventArgs(int layerAffected, LayerAction layerChangeType)
         public LayersChangedEventArgs(int layerAffected, LayerAction layerChangeType)
         {
         {
             LayerAffected = layerAffected;
             LayerAffected = layerAffected;
             LayerChangeType = layerChangeType;
             LayerChangeType = layerChangeType;
         }
         }
+
+        public int LayerAffected { get; set; }
+        public LayerAction LayerChangeType { get; set; }
     }
     }
 }
 }

+ 31 - 32
PixiEditor/Models/Controllers/BitmapOperationsUtility.cs

@@ -14,25 +14,26 @@ namespace PixiEditor.Models.Controllers
 {
 {
     public class BitmapOperationsUtility
     public class BitmapOperationsUtility
     {
     {
-        public BitmapManager Manager { get; set; }
-        private LayerChange[] _lastModifiedLayers;
+        private LayerChange[] lastModifiedLayers;
 
 
-        private Coordinates _lastMousePos;
+        private Coordinates lastMousePos;
 
 
         public BitmapOperationsUtility(BitmapManager manager)
         public BitmapOperationsUtility(BitmapManager manager)
         {
         {
             Manager = manager;
             Manager = manager;
         }
         }
 
 
+        public BitmapManager Manager { get; set; }
+
         public event EventHandler<BitmapChangedEventArgs> BitmapChanged;
         public event EventHandler<BitmapChangedEventArgs> BitmapChanged;
 
 
         public void DeletePixels(Layer[] layers, Coordinates[] pixels)
         public void DeletePixels(Layer[] layers, Coordinates[] pixels)
         {
         {
             var changes = BitmapPixelChanges.FromSingleColoredArray(pixels, Color.FromArgb(0, 0, 0, 0));
             var changes = BitmapPixelChanges.FromSingleColoredArray(pixels, Color.FromArgb(0, 0, 0, 0));
             var oldValues = BitmapUtils.GetPixelsForSelection(layers, pixels);
             var oldValues = BitmapUtils.GetPixelsForSelection(layers, pixels);
-            LayerChange[] old = new LayerChange[layers.Length];
-            LayerChange[] newChange = new LayerChange[layers.Length];
-            for (int i = 0; i < layers.Length; i++)
+            var old = new LayerChange[layers.Length];
+            var newChange = new LayerChange[layers.Length];
+            for (var i = 0; i < layers.Length; i++)
             {
             {
                 old[i] = new LayerChange(
                 old[i] = new LayerChange(
                     BitmapPixelChanges.FromArrays(pixels, oldValues[layers[i]]), i);
                     BitmapPixelChanges.FromArrays(pixels, oldValues[layers[i]]), i);
@@ -57,7 +58,7 @@ namespace PixiEditor.Models.Controllers
                 mouseMove.Reverse();
                 mouseMove.Reverse();
                 UseTool(mouseMove, tool, Manager.PrimaryColor);
                 UseTool(mouseMove, tool, Manager.PrimaryColor);
 
 
-                _lastMousePos = newPos;
+                lastMousePos = newPos;
             }
             }
         }
         }
 
 
@@ -66,16 +67,16 @@ namespace PixiEditor.Models.Controllers
         /// </summary>
         /// </summary>
         public void StopAction()
         public void StopAction()
         {
         {
-            if (_lastModifiedLayers == null) return;
-            for (int i = 0; i < _lastModifiedLayers.Length; i++)
+            if (lastModifiedLayers == null) return;
+            for (var i = 0; i < lastModifiedLayers.Length; i++)
             {
             {
-                var layer = Manager.ActiveDocument.Layers[_lastModifiedLayers[i].LayerIndex];
+                var layer = Manager.ActiveDocument.Layers[lastModifiedLayers[i].LayerIndex];
 
 
-                BitmapPixelChanges oldValues = ApplyToLayer(layer, _lastModifiedLayers[i]).PixelChanges;
+                var oldValues = ApplyToLayer(layer, lastModifiedLayers[i]).PixelChanges;
 
 
-               BitmapChanged?.Invoke(this, new BitmapChangedEventArgs(_lastModifiedLayers[i].PixelChanges,
-                    oldValues, _lastModifiedLayers[i].LayerIndex));
-               Manager.PreviewLayer = null;
+                BitmapChanged?.Invoke(this, new BitmapChangedEventArgs(lastModifiedLayers[i].PixelChanges,
+                    oldValues, lastModifiedLayers[i].LayerIndex));
+                Manager.PreviewLayer = null;
             }
             }
         }
         }
 
 
@@ -86,13 +87,13 @@ namespace PixiEditor.Models.Controllers
                 mouseMoveCords = GetSquareCoordiantes(mouseMoveCords);
                 mouseMoveCords = GetSquareCoordiantes(mouseMoveCords);
             if (!tool.RequiresPreviewLayer)
             if (!tool.RequiresPreviewLayer)
             {
             {
-                LayerChange[] modifiedLayers = tool.Use(Manager.ActiveLayer, mouseMoveCords.ToArray(), color);
-                LayerChange[] oldPixelsValues = new LayerChange[modifiedLayers.Length];
-                for (int i = 0; i < modifiedLayers.Length; i++)
+                var modifiedLayers = tool.Use(Manager.ActiveLayer, mouseMoveCords.ToArray(), color);
+                var oldPixelsValues = new LayerChange[modifiedLayers.Length];
+                for (var i = 0; i < modifiedLayers.Length; i++)
                 {
                 {
                     var layer = Manager.ActiveDocument.Layers[modifiedLayers[i].LayerIndex];
                     var layer = Manager.ActiveDocument.Layers[modifiedLayers[i].LayerIndex];
                     oldPixelsValues[i] = ApplyToLayer(layer, modifiedLayers[i]);
                     oldPixelsValues[i] = ApplyToLayer(layer, modifiedLayers[i]);
-                    
+
                     BitmapChanged?.Invoke(this, new BitmapChangedEventArgs(modifiedLayers[i].PixelChanges,
                     BitmapChanged?.Invoke(this, new BitmapChangedEventArgs(modifiedLayers[i].PixelChanges,
                         oldPixelsValues[i].PixelChanges, modifiedLayers[i].LayerIndex));
                         oldPixelsValues[i].PixelChanges, modifiedLayers[i].LayerIndex));
                 }
                 }
@@ -127,8 +128,8 @@ namespace PixiEditor.Models.Controllers
         /// <returns></returns>
         /// <returns></returns>
         private List<Coordinates> GetSquareCoordiantes(List<Coordinates> mouseMoveCords)
         private List<Coordinates> GetSquareCoordiantes(List<Coordinates> mouseMoveCords)
         {
         {
-            int xLength = mouseMoveCords[0].Y - mouseMoveCords[^1].Y;
-            int yLength = mouseMoveCords[0].Y - mouseMoveCords[^1].Y;
+            var xLength = mouseMoveCords[0].Y - mouseMoveCords[^1].Y;
+            var yLength = mouseMoveCords[0].Y - mouseMoveCords[^1].Y;
             if (mouseMoveCords[^1].Y > mouseMoveCords[0].Y) xLength *= -1;
             if (mouseMoveCords[^1].Y > mouseMoveCords[0].Y) xLength *= -1;
             if (mouseMoveCords[^1].X > mouseMoveCords[0].X) xLength *= -1;
             if (mouseMoveCords[^1].X > mouseMoveCords[0].X) xLength *= -1;
             mouseMoveCords[0] = new Coordinates(mouseMoveCords[^1].X + xLength, mouseMoveCords[^1].Y + yLength);
             mouseMoveCords[0] = new Coordinates(mouseMoveCords[^1].X + xLength, mouseMoveCords[^1].Y + yLength);
@@ -137,31 +138,29 @@ namespace PixiEditor.Models.Controllers
 
 
         private BitmapPixelChanges GetOldPixelsValues(Coordinates[] coordinates)
         private BitmapPixelChanges GetOldPixelsValues(Coordinates[] coordinates)
         {
         {
-            Dictionary<Coordinates, Color> values = new Dictionary<Coordinates, Color>();
+            var values = new Dictionary<Coordinates, Color>();
             using (Manager.ActiveLayer.LayerBitmap.GetBitmapContext(ReadWriteMode.ReadOnly))
             using (Manager.ActiveLayer.LayerBitmap.GetBitmapContext(ReadWriteMode.ReadOnly))
             {
             {
                 var relativeCoords = Manager.ActiveLayer.ConvertToRelativeCoordinates(coordinates);
                 var relativeCoords = Manager.ActiveLayer.ConvertToRelativeCoordinates(coordinates);
-                for (int i = 0; i < coordinates.Length; i++)
-                {
+                for (var i = 0; i < coordinates.Length; i++)
                     values.Add(coordinates[i],
                     values.Add(coordinates[i],
                         Manager.ActiveLayer.GetPixel(relativeCoords[i].X, relativeCoords[i].Y));
                         Manager.ActiveLayer.GetPixel(relativeCoords[i].X, relativeCoords[i].Y));
-                }
-
             }
             }
+
             return new BitmapPixelChanges(values);
             return new BitmapPixelChanges(values);
         }
         }
 
 
         private void UseToolOnPreviewLayer(List<Coordinates> mouseMove)
         private void UseToolOnPreviewLayer(List<Coordinates> mouseMove)
         {
         {
             LayerChange[] modifiedLayers;
             LayerChange[] modifiedLayers;
-            if (mouseMove.Count > 0 && mouseMove[0] != _lastMousePos)
+            if (mouseMove.Count > 0 && mouseMove[0] != lastMousePos)
             {
             {
                 Manager.GeneratePreviewLayer();
                 Manager.GeneratePreviewLayer();
                 modifiedLayers = ((BitmapOperationTool) Manager.SelectedTool).Use(Manager.ActiveDocument.ActiveLayer,
                 modifiedLayers = ((BitmapOperationTool) Manager.SelectedTool).Use(Manager.ActiveDocument.ActiveLayer,
                     mouseMove.ToArray(), Manager.PrimaryColor);
                     mouseMove.ToArray(), Manager.PrimaryColor);
-                BitmapPixelChanges[] changes = modifiedLayers.Select(x => x.PixelChanges).ToArray();
+                var changes = modifiedLayers.Select(x => x.PixelChanges).ToArray();
                 Manager.PreviewLayer.SetPixels(BitmapPixelChanges.CombineOverride(changes));
                 Manager.PreviewLayer.SetPixels(BitmapPixelChanges.CombineOverride(changes));
-                _lastModifiedLayers = modifiedLayers;
+                lastModifiedLayers = modifiedLayers;
             }
             }
         }
         }
     }
     }
@@ -169,10 +168,6 @@ namespace PixiEditor.Models.Controllers
 
 
 public class BitmapChangedEventArgs : EventArgs
 public class BitmapChangedEventArgs : EventArgs
 {
 {
-    public BitmapPixelChanges PixelsChanged { get; set; }
-    public BitmapPixelChanges OldPixelsValues { get; set; }
-    public int ChangedLayerIndex { get; set; }
-
     public BitmapChangedEventArgs(BitmapPixelChanges pixelsChanged, BitmapPixelChanges oldPixelsValues,
     public BitmapChangedEventArgs(BitmapPixelChanges pixelsChanged, BitmapPixelChanges oldPixelsValues,
         int changedLayerIndex)
         int changedLayerIndex)
     {
     {
@@ -180,4 +175,8 @@ public class BitmapChangedEventArgs : EventArgs
         OldPixelsValues = oldPixelsValues;
         OldPixelsValues = oldPixelsValues;
         ChangedLayerIndex = changedLayerIndex;
         ChangedLayerIndex = changedLayerIndex;
     }
     }
+
+    public BitmapPixelChanges PixelsChanged { get; set; }
+    public BitmapPixelChanges OldPixelsValues { get; set; }
+    public int ChangedLayerIndex { get; set; }
 }
 }

+ 12 - 13
PixiEditor/Models/Controllers/ClipboardController.cs

@@ -2,7 +2,6 @@
 using System.Linq;
 using System.Linq;
 using System.Windows;
 using System.Windows;
 using System.Windows.Media.Imaging;
 using System.Windows.Media.Imaging;
-using PixiEditor.Models.DataHolders;
 using PixiEditor.Models.ImageManipulation;
 using PixiEditor.Models.ImageManipulation;
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Position;
 using PixiEditor.Models.Position;
@@ -22,14 +21,14 @@ namespace PixiEditor.Models.Controllers
         public static void CopyToClipboard(Layer[] layers, Coordinates[] selection, int originalImageWidth, int originalImageHeight)
         public static void CopyToClipboard(Layer[] layers, Coordinates[] selection, int originalImageWidth, int originalImageHeight)
         {
         {
             Clipboard.Clear();
             Clipboard.Clear();
-            WriteableBitmap combinedBitmaps = BitmapUtils.CombineLayers(layers, originalImageWidth, originalImageHeight);
+            var combinedBitmaps = BitmapUtils.CombineLayers(layers, originalImageWidth, originalImageHeight);
             using (var pngStream = new MemoryStream())
             using (var pngStream = new MemoryStream())
             {
             {
-                DataObject data = new DataObject();
+                var data = new DataObject();
                 var croppedBmp = BitmapSelectionToBmpSource(combinedBitmaps, selection);
                 var croppedBmp = BitmapSelectionToBmpSource(combinedBitmaps, selection);
                 data.SetData(DataFormats.Bitmap, croppedBmp, true); //Bitmap, no transparency support
                 data.SetData(DataFormats.Bitmap, croppedBmp, true); //Bitmap, no transparency support
 
 
-                PngBitmapEncoder encoder = new PngBitmapEncoder();
+                var encoder = new PngBitmapEncoder();
                 encoder.Frames.Add(BitmapFrame.Create(croppedBmp));
                 encoder.Frames.Add(BitmapFrame.Create(croppedBmp));
                 encoder.Save(pngStream);
                 encoder.Save(pngStream);
                 data.SetData("PNG", pngStream, false); //PNG, supports transparency
                 data.SetData("PNG", pngStream, false); //PNG, supports transparency
@@ -44,7 +43,7 @@ namespace PixiEditor.Models.Controllers
         /// </summary>
         /// </summary>
         public static void PasteFromClipboard()
         public static void PasteFromClipboard()
         {
         {
-            WriteableBitmap image = GetImageFromClipboard();
+            var image = GetImageFromClipboard();
             if (image != null) AddImageToLayers(image);
             if (image != null) AddImageToLayers(image);
         }
         }
 
 
@@ -54,14 +53,14 @@ namespace PixiEditor.Models.Controllers
         /// <returns>WriteableBitmap</returns>
         /// <returns>WriteableBitmap</returns>
         public static WriteableBitmap GetImageFromClipboard()
         public static WriteableBitmap GetImageFromClipboard()
         {
         {
-            DataObject dao = (DataObject)Clipboard.GetDataObject();
+            var dao = (DataObject) Clipboard.GetDataObject();
             WriteableBitmap finalImage = null;
             WriteableBitmap finalImage = null;
             if (dao.GetDataPresent("PNG"))
             if (dao.GetDataPresent("PNG"))
-                using (MemoryStream pngStream = dao.GetData("PNG") as MemoryStream)
+                using (var pngStream = dao.GetData("PNG") as MemoryStream)
                 {
                 {
                     if (pngStream != null)
                     if (pngStream != null)
                     {
                     {
-                        PngBitmapDecoder decoder = new PngBitmapDecoder(pngStream, BitmapCreateOptions.IgnoreImageCache,
+                        var decoder = new PngBitmapDecoder(pngStream, BitmapCreateOptions.IgnoreImageCache,
                             BitmapCacheOption.OnLoad);
                             BitmapCacheOption.OnLoad);
                         finalImage = new WriteableBitmap(decoder.Frames[0].Clone());
                         finalImage = new WriteableBitmap(decoder.Frames[0].Clone());
                     }
                     }
@@ -76,7 +75,7 @@ namespace PixiEditor.Models.Controllers
 
 
         public static bool IsImageInClipboard()
         public static bool IsImageInClipboard()
         {
         {
-            DataObject dao = (DataObject) Clipboard.GetDataObject();
+            var dao = (DataObject) Clipboard.GetDataObject();
             if (dao == null) return false;
             if (dao == null) return false;
             return dao.GetDataPresent("PNG") || dao.GetDataPresent(DataFormats.Dib) ||
             return dao.GetDataPresent("PNG") || dao.GetDataPresent(DataFormats.Dib) ||
                    dao.GetDataPresent(DataFormats.Bitmap);
                    dao.GetDataPresent(DataFormats.Bitmap);
@@ -89,10 +88,10 @@ namespace PixiEditor.Models.Controllers
 
 
         public static BitmapSource BitmapSelectionToBmpSource(WriteableBitmap bitmap, Coordinates[] selection)
         public static BitmapSource BitmapSelectionToBmpSource(WriteableBitmap bitmap, Coordinates[] selection)
         {
         {
-            int offsetX = selection.Min(x => x.X);
-            int offsetY = selection.Min(x => x.Y);
-            int width = selection.Max(x => x.X) - offsetX + 1;
-            int height = selection.Max(x => x.Y) - offsetY + 1;
+            var offsetX = selection.Min(x => x.X);
+            var offsetY = selection.Min(x => x.Y);
+            var width = selection.Max(x => x.X) - offsetX + 1;
+            var height = selection.Max(x => x.Y) - offsetY + 1;
             return bitmap.Crop(offsetX, offsetY, width, height);
             return bitmap.Crop(offsetX, offsetY, width, height);
         }
         }
     }
     }

+ 2 - 3
PixiEditor/Models/Controllers/MouseMovementController.cs

@@ -1,6 +1,5 @@
 using System;
 using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
-using Accessibility;
 using PixiEditor.Models.Position;
 using PixiEditor.Models.Position;
 
 
 namespace PixiEditor.Models.Controllers
 namespace PixiEditor.Models.Controllers
@@ -58,10 +57,10 @@ namespace PixiEditor.Models.Controllers
 
 
 public class MouseMovementEventArgs : EventArgs
 public class MouseMovementEventArgs : EventArgs
 {
 {
-    public Coordinates NewPosition { get; set; }
-
     public MouseMovementEventArgs(Coordinates mousePosition)
     public MouseMovementEventArgs(Coordinates mousePosition)
     {
     {
         NewPosition = mousePosition;
         NewPosition = mousePosition;
     }
     }
+
+    public Coordinates NewPosition { get; set; }
 }
 }

+ 4 - 7
PixiEditor/Models/Controllers/PixelChangesController.cs

@@ -1,10 +1,7 @@
 using System;
 using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
-using System.Windows.Media;
 using PixiEditor.Models.DataHolders;
 using PixiEditor.Models.DataHolders;
-using PixiEditor.Models.Position;
-using PixiEditor.Models.Tools;
 
 
 namespace PixiEditor.Models.Controllers
 namespace PixiEditor.Models.Controllers
 {
 {
@@ -67,13 +64,13 @@ namespace PixiEditor.Models.Controllers
         {
         {
             //Maybe replace Tuple with custom data type
             //Maybe replace Tuple with custom data type
             if (LastChanges == null) return null;
             if (LastChanges == null) return null;
-            Tuple<LayerChange, LayerChange>[] result = new Tuple<LayerChange, LayerChange>[LastChanges.Count];
-            int i = 0;
+            var result = new Tuple<LayerChange, LayerChange>[LastChanges.Count];
+            var i = 0;
             foreach (var change in LastChanges)
             foreach (var change in LastChanges)
             {
             {
-                Dictionary<Coordinates, Color> pixelChanges =
+                var pixelChanges =
                     change.Value.PixelChanges.ChangedPixels.ToDictionary(entry => entry.Key, entry => entry.Value);
                     change.Value.PixelChanges.ChangedPixels.ToDictionary(entry => entry.Key, entry => entry.Value);
-                Dictionary<Coordinates, Color> oldValues = LastOldValues[change.Key].PixelChanges.ChangedPixels
+                var oldValues = LastOldValues[change.Key].PixelChanges.ChangedPixels
                     .ToDictionary(entry => entry.Key, entry => entry.Value);
                     .ToDictionary(entry => entry.Key, entry => entry.Value);
 
 
                 var tmp = new LayerChange(new BitmapPixelChanges(pixelChanges), change.Key);
                 var tmp = new LayerChange(new BitmapPixelChanges(pixelChanges), change.Key);

+ 5 - 5
PixiEditor/Models/Controllers/Shortcuts/Shortcut.cs

@@ -4,11 +4,6 @@ namespace PixiEditor.Models.Controllers.Shortcuts
 {
 {
     public class Shortcut
     public class Shortcut
     {
     {
-        public Key ShortcutKey { get; set; }
-        public ModifierKeys Modifier { get; set; }
-        public ICommand Command { get; set; }
-        public object CommandParameter { get; set; }
-
         public Shortcut(Key shortcutKey, ICommand command, object commandParameter = null,
         public Shortcut(Key shortcutKey, ICommand command, object commandParameter = null,
             ModifierKeys modifier = ModifierKeys.None)
             ModifierKeys modifier = ModifierKeys.None)
         {
         {
@@ -18,6 +13,11 @@ namespace PixiEditor.Models.Controllers.Shortcuts
             CommandParameter = commandParameter;
             CommandParameter = commandParameter;
         }
         }
 
 
+        public Key ShortcutKey { get; set; }
+        public ModifierKeys Modifier { get; set; }
+        public ICommand Command { get; set; }
+        public object CommandParameter { get; set; }
+
         public void Execute()
         public void Execute()
         {
         {
             if (Command.CanExecute(CommandParameter)) Command.Execute(CommandParameter);
             if (Command.CanExecute(CommandParameter)) Command.Execute(CommandParameter);

+ 7 - 7
PixiEditor/Models/Controllers/Shortcuts/ShortcutController.cs

@@ -6,24 +6,24 @@ namespace PixiEditor.Models.Controllers.Shortcuts
 {
 {
     public class ShortcutController
     public class ShortcutController
     {
     {
-        public static bool BlockShortcutExecution { get; set; }
-
-        public List<Shortcut> Shortcuts { get; set; }
-        public Shortcut LastShortcut { get; private set; }
-
         public ShortcutController()
         public ShortcutController()
         {
         {
             Shortcuts = new List<Shortcut>();
             Shortcuts = new List<Shortcut>();
         }
         }
 
 
+        public static bool BlockShortcutExecution { get; set; }
+
+        public List<Shortcut> Shortcuts { get; set; }
+        public Shortcut LastShortcut { get; private set; }
+
         public void KeyPressed(Key key, ModifierKeys modifiers)
         public void KeyPressed(Key key, ModifierKeys modifiers)
         {
         {
             if (!BlockShortcutExecution)
             if (!BlockShortcutExecution)
             {
             {
-                Shortcut[] shortcuts = Shortcuts.FindAll(x => x.ShortcutKey == key).ToArray();
+                var shortcuts = Shortcuts.FindAll(x => x.ShortcutKey == key).ToArray();
                 if (shortcuts.Length < 1) return;
                 if (shortcuts.Length < 1) return;
                 shortcuts = shortcuts.OrderByDescending(x => x.Modifier).ToArray();
                 shortcuts = shortcuts.OrderByDescending(x => x.Modifier).ToArray();
-                for (int i = 0; i < shortcuts.Length; i++)
+                for (var i = 0; i < shortcuts.Length; i++)
                     if (modifiers.HasFlag(shortcuts[i].Modifier))
                     if (modifiers.HasFlag(shortcuts[i].Modifier))
                     {
                     {
                         shortcuts[i].Execute();
                         shortcuts[i].Execute();

+ 11 - 12
PixiEditor/Models/Controllers/UndoManager.cs

@@ -1,13 +1,12 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
-using System.Reflection;
 using PixiEditor.Models.DataHolders;
 using PixiEditor.Models.DataHolders;
 
 
 namespace PixiEditor.Models.Controllers
 namespace PixiEditor.Models.Controllers
 {
 {
     public static class UndoManager
     public static class UndoManager
     {
     {
-        private static bool _lastChangeWasUndo;
+        private static bool lastChangeWasUndo;
         public static Stack<Change> UndoStack { get; set; } = new Stack<Change>();
         public static Stack<Change> UndoStack { get; set; } = new Stack<Change>();
         public static Stack<Change> RedoStack { get; set; } = new Stack<Change>();
         public static Stack<Change> RedoStack { get; set; } = new Stack<Change>();
 
 
@@ -32,10 +31,10 @@ namespace PixiEditor.Models.Controllers
         /// <param name="change"></param>
         /// <param name="change"></param>
         public static void AddUndoChange(Change change)
         public static void AddUndoChange(Change change)
         {
         {
-            if (_lastChangeWasUndo == false && RedoStack.Count > 0
+            if (lastChangeWasUndo == false && RedoStack.Count > 0
             ) //Clears RedoStack if las move wasn't redo or undo and if redo stack is greater than 0
             ) //Clears RedoStack if las move wasn't redo or undo and if redo stack is greater than 0
                 RedoStack.Clear();
                 RedoStack.Clear();
-            _lastChangeWasUndo = false;
+            lastChangeWasUndo = false;
             change.Root ??= MainRoot;
             change.Root ??= MainRoot;
             UndoStack.Push(change);
             UndoStack.Push(change);
         }
         }
@@ -45,8 +44,8 @@ namespace PixiEditor.Models.Controllers
         /// </summary>
         /// </summary>
         public static void Undo()
         public static void Undo()
         {
         {
-            _lastChangeWasUndo = true;
-            Change change = UndoStack.Pop();
+            lastChangeWasUndo = true;
+            var change = UndoStack.Pop();
             if (change.ReverseProcess == null)
             if (change.ReverseProcess == null)
                 SetPropertyValue(change.Root, change.Property, change.OldValue);
                 SetPropertyValue(change.Root, change.Property, change.OldValue);
             else
             else
@@ -59,8 +58,8 @@ namespace PixiEditor.Models.Controllers
         /// </summary>
         /// </summary>
         public static void Redo()
         public static void Redo()
         {
         {
-            _lastChangeWasUndo = true;
-            Change change = RedoStack.Pop();
+            lastChangeWasUndo = true;
+            var change = RedoStack.Pop();
             if (change.Process == null)
             if (change.Process == null)
                 SetPropertyValue(change.Root, change.Property, change.NewValue);
                 SetPropertyValue(change.Root, change.Property, change.NewValue);
             else
             else
@@ -71,14 +70,14 @@ namespace PixiEditor.Models.Controllers
 
 
         private static void SetPropertyValue(object target, string propName, object value)
         private static void SetPropertyValue(object target, string propName, object value)
         {
         {
-            string[] bits = propName.Split('.');
-            for (int i = 0; i < bits.Length - 1; i++)
+            var bits = propName.Split('.');
+            for (var i = 0; i < bits.Length - 1; i++)
             {
             {
-                PropertyInfo propertyToGet = target.GetType().GetProperty(bits[i]);
+                var propertyToGet = target.GetType().GetProperty(bits[i]);
                 target = propertyToGet.GetValue(target, null);
                 target = propertyToGet.GetValue(target, null);
             }
             }
 
 
-            PropertyInfo propertyToSet = target.GetType().GetProperty(bits.Last());
+            var propertyToSet = target.GetType().GetProperty(bits.Last());
             propertyToSet.SetValue(target, value, null);
             propertyToSet.SetValue(target, value, null);
         }
         }
     }
     }

+ 6 - 10
PixiEditor/Models/DataHolders/BitmapPixelChanges.cs

@@ -10,7 +10,6 @@ namespace PixiEditor.Models.DataHolders
 {
 {
     public struct BitmapPixelChanges
     public struct BitmapPixelChanges
     {
     {
-
         public bool WasBuiltAsSingleColored { get; private set; }
         public bool WasBuiltAsSingleColored { get; private set; }
 
 
         public static BitmapPixelChanges Empty => new BitmapPixelChanges(new Dictionary<Coordinates, Color>());
         public static BitmapPixelChanges Empty => new BitmapPixelChanges(new Dictionary<Coordinates, Color>());
@@ -30,11 +29,8 @@ namespace PixiEditor.Models.DataHolders
         /// <returns>Single-colored BitmapPixelChanges</returns>
         /// <returns>Single-colored BitmapPixelChanges</returns>
         public static BitmapPixelChanges FromSingleColoredArray(IEnumerable<Coordinates> coordinates, Color color)
         public static BitmapPixelChanges FromSingleColoredArray(IEnumerable<Coordinates> coordinates, Color color)
         {
         {
-            Dictionary<Coordinates, Color> dict = new Dictionary<Coordinates, Color>();
-            foreach (var coordinate in coordinates)
-            {
-                dict.Add(coordinate, color);
-            }
+            var dict = new Dictionary<Coordinates, Color>();
+            foreach (var coordinate in coordinates) dict.Add(coordinate, color);
             return new BitmapPixelChanges(dict) {WasBuiltAsSingleColored = true};
             return new BitmapPixelChanges(dict) {WasBuiltAsSingleColored = true};
         }
         }
 
 
@@ -46,9 +42,9 @@ namespace PixiEditor.Models.DataHolders
         public static BitmapPixelChanges CombineOverride(BitmapPixelChanges[] changes)
         public static BitmapPixelChanges CombineOverride(BitmapPixelChanges[] changes)
         {
         {
             if (changes == null || changes.Length == 0) throw new ArgumentException();
             if (changes == null || changes.Length == 0) throw new ArgumentException();
-            BitmapPixelChanges output = Empty;
+            var output = Empty;
 
 
-            for (int i = 0; i < changes.Length; i++) output.ChangedPixels.AddRangeOverride(changes[i].ChangedPixels);
+            for (var i = 0; i < changes.Length; i++) output.ChangedPixels.AddRangeOverride(changes[i].ChangedPixels);
             return output;
             return output;
         }
         }
 
 
@@ -63,8 +59,8 @@ namespace PixiEditor.Models.DataHolders
             var coordinateArray = coordinates.ToArray();
             var coordinateArray = coordinates.ToArray();
             var colorArray = color.ToArray();
             var colorArray = color.ToArray();
             if (coordinateArray.Length != colorArray.Length) throw new ArrayLengthMismatchException();
             if (coordinateArray.Length != colorArray.Length) throw new ArrayLengthMismatchException();
-            Dictionary<Coordinates, Color> dict = new Dictionary<Coordinates, Color>();
-            for (int i = 0; i < coordinateArray.Length; i++) dict.Add(coordinateArray[i], colorArray[i]);
+            var dict = new Dictionary<Coordinates, Color>();
+            for (var i = 0; i < coordinateArray.Length; i++) dict.Add(coordinateArray[i], colorArray[i]);
             return new BitmapPixelChanges(dict);
             return new BitmapPixelChanges(dict);
         }
         }
     }
     }

+ 12 - 11
PixiEditor/Models/DataHolders/Change.cs

@@ -5,19 +5,8 @@ namespace PixiEditor.Models.DataHolders
     [Serializable]
     [Serializable]
     public class Change
     public class Change
     {
     {
-        public object OldValue { get; set; }
-
-        public object NewValue { get; set; }
-
-        public string Description { get; set; }
-
-        public string Property { get; set; }
-
-        public Action<object[]> ReverseProcess { get; set; }
-        public Action<object[]> Process { get; set; }
         public object[] ProcessArguments;
         public object[] ProcessArguments;
         public object[] ReverseProcessArguments;
         public object[] ReverseProcessArguments;
-        public object Root { get; set; }
 
 
         /// <summary>
         /// <summary>
         ///     Creates new change for property based undo system
         ///     Creates new change for property based undo system
@@ -74,5 +63,17 @@ namespace PixiEditor.Models.DataHolders
             ProcessArguments = processArguments;
             ProcessArguments = processArguments;
             Description = description;
             Description = description;
         }
         }
+
+        public object OldValue { get; set; }
+
+        public object NewValue { get; set; }
+
+        public string Description { get; set; }
+
+        public string Property { get; set; }
+
+        public Action<object[]> ReverseProcess { get; set; }
+        public Action<object[]> Process { get; set; }
+        public object Root { get; set; }
     }
     }
 }
 }

+ 77 - 87
PixiEditor/Models/DataHolders/Document.cs

@@ -1,38 +1,44 @@
 using System;
 using System;
-using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.Collections.ObjectModel;
 using System.Linq;
 using System.Linq;
 using System.Windows;
 using System.Windows;
 using System.Windows.Media;
 using System.Windows.Media;
-using System.Windows.Media.Imaging;
 using PixiEditor.Helpers;
 using PixiEditor.Helpers;
 using PixiEditor.Models.Controllers;
 using PixiEditor.Models.Controllers;
 using PixiEditor.Models.Enums;
 using PixiEditor.Models.Enums;
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Position;
 using PixiEditor.Models.Position;
-using PixiEditor.Models.Tools.Tools;
-using PixiEditor.ViewModels;
 
 
 namespace PixiEditor.Models.DataHolders
 namespace PixiEditor.Models.DataHolders
 {
 {
     public class Document : NotifyableObject
     public class Document : NotifyableObject
     {
     {
+        private int activeLayerIndex;
+        private int height;
+        private int width;
+
+        public Document(int width, int height)
+        {
+            Width = width;
+            Height = height;
+        }
+
         public int Width
         public int Width
         {
         {
-            get => _width;
+            get => width;
             set
             set
             {
             {
-                _width = value;
+                width = value;
                 RaisePropertyChanged("Width");
                 RaisePropertyChanged("Width");
             }
             }
         }
         }
 
 
         public int Height
         public int Height
         {
         {
-            get => _height;
+            get => height;
             set
             set
             {
             {
-                _height = value;
+                height = value;
                 RaisePropertyChanged("Height");
                 RaisePropertyChanged("Height");
             }
             }
         }
         }
@@ -43,25 +49,16 @@ namespace PixiEditor.Models.DataHolders
 
 
         public int ActiveLayerIndex
         public int ActiveLayerIndex
         {
         {
-            get => _activeLayerIndex;
+            get => activeLayerIndex;
             set
             set
             {
             {
-                _activeLayerIndex = value;
+                activeLayerIndex = value;
                 RaisePropertyChanged("ActiveLayerIndex");
                 RaisePropertyChanged("ActiveLayerIndex");
                 RaisePropertyChanged("ActiveLayer");
                 RaisePropertyChanged("ActiveLayer");
             }
             }
         }
         }
 
 
         public ObservableCollection<Color> Swatches { get; set; } = new ObservableCollection<Color>();
         public ObservableCollection<Color> Swatches { get; set; } = new ObservableCollection<Color>();
-        private int _activeLayerIndex;
-        private int _height;
-        private int _width;
-
-        public Document(int width, int height)
-        {
-            Width = width;
-            Height = height;
-        }
 
 
         public event EventHandler<DocumentSizeChangedEventArgs> DocumentSizeChanged;
         public event EventHandler<DocumentSizeChangedEventArgs> DocumentSizeChanged;
 
 
@@ -76,18 +73,18 @@ namespace PixiEditor.Models.DataHolders
         /// </param>
         /// </param>
         public void ResizeCanvas(int width, int height, AnchorPoint anchor)
         public void ResizeCanvas(int width, int height, AnchorPoint anchor)
         {
         {
-            int oldWidth = Width;
-            int oldHeight = Height;
+            var oldWidth = Width;
+            var oldHeight = Height;
 
 
-            int offsetX = GetOffsetXForAnchor(Width, width, anchor);
-            int offsetY = GetOffsetYForAnchor(Height, height, anchor);
+            var offsetX = GetOffsetXForAnchor(Width, width, anchor);
+            var offsetY = GetOffsetYForAnchor(Height, height, anchor);
 
 
-            Thickness[] oldOffsets = Layers.Select(x => x.Offset).ToArray();
-            Thickness[] newOffsets = Layers.Select(x => new Thickness(offsetX + x.OffsetX, offsetY + x.OffsetY, 0, 0))
+            var oldOffsets = Layers.Select(x => x.Offset).ToArray();
+            var newOffsets = Layers.Select(x => new Thickness(offsetX + x.OffsetX, offsetY + x.OffsetY, 0, 0))
                 .ToArray();
                 .ToArray();
 
 
-                object[] processArgs = {newOffsets, width, height};
-            object[] reverseProcessArgs = { oldOffsets, Width, Height};
+            object[] processArgs = {newOffsets, width, height};
+            object[] reverseProcessArgs = {oldOffsets, Width, Height};
 
 
             ResizeCanvas(newOffsets, width, height);
             ResizeCanvas(newOffsets, width, height);
             UndoManager.AddUndoChange(new Change(ResizeCanvasProcess,
             UndoManager.AddUndoChange(new Change(ResizeCanvasProcess,
@@ -121,24 +118,24 @@ namespace PixiEditor.Models.DataHolders
             object[] reverseArgs = {Width, Height};
             object[] reverseArgs = {Width, Height};
             object[] args = {newWidth, newHeight};
             object[] args = {newWidth, newHeight};
             ResizeDocument(args);
             ResizeDocument(args);
-            UndoManager.AddUndoChange(new Change( ResizeDocument, reverseArgs,
+            UndoManager.AddUndoChange(new Change(ResizeDocument, reverseArgs,
                 ResizeDocument, args, "Resize document"));
                 ResizeDocument, args, "Resize document"));
         }
         }
 
 
         private void ResizeDocument(object[] arguments)
         private void ResizeDocument(object[] arguments)
         {
         {
-            int oldWidth = Width;
-            int oldHeight = Height;
+            var oldWidth = Width;
+            var oldHeight = Height;
 
 
-            int newWidth = (int) arguments[0];
-            int newHeight = (int) arguments[1];
+            var newWidth = (int) arguments[0];
+            var newHeight = (int) arguments[1];
 
 
-            for (int i = 0; i < Layers.Count; i++)
+            for (var i = 0; i < Layers.Count; i++)
             {
             {
-                float widthRatio = (float)newWidth / Width;
-                float heightRatio = (float)newHeight / Height;
-                int layerWidth = (int)(Layers[i].Width * widthRatio);
-                int layerHeight = (int)(Layers[i].Height * heightRatio);
+                var widthRatio = (float) newWidth / Width;
+                var heightRatio = (float) newHeight / Height;
+                var layerWidth = (int) (Layers[i].Width * widthRatio);
+                var layerHeight = (int) (Layers[i].Height * heightRatio);
 
 
                 Layers[i].Resize(layerWidth, layerHeight, newWidth, newHeight);
                 Layers[i].Resize(layerWidth, layerHeight, newWidth, newHeight);
                 Layers[i].Offset = new Thickness(Layers[i].OffsetX * widthRatio, Layers[i].OffsetY * heightRatio, 0, 0);
                 Layers[i].Offset = new Thickness(Layers[i].OffsetX * widthRatio, Layers[i].OffsetY * heightRatio, 0, 0);
@@ -152,12 +149,12 @@ namespace PixiEditor.Models.DataHolders
 
 
         private void ResizeCanvasProcess(object[] arguments)
         private void ResizeCanvasProcess(object[] arguments)
         {
         {
-            int oldWidth = Width;
-            int oldHeight = Height;
+            var oldWidth = Width;
+            var oldHeight = Height;
 
 
-            Thickness[] offset = (Thickness[])arguments[0];
-            int width = (int) arguments[1];
-            int height = (int) arguments[2];
+            var offset = (Thickness[]) arguments[0];
+            var width = (int) arguments[1];
+            var height = (int) arguments[2];
             ResizeCanvas(offset, width, height);
             ResizeCanvas(offset, width, height);
             DocumentSizeChanged?.Invoke(this, new DocumentSizeChangedEventArgs(oldWidth, oldHeight, width, height));
             DocumentSizeChanged?.Invoke(this, new DocumentSizeChangedEventArgs(oldWidth, oldHeight, width, height));
         }
         }
@@ -170,7 +167,7 @@ namespace PixiEditor.Models.DataHolders
         /// <param name="newHeight">New canvas height.</param>
         /// <param name="newHeight">New canvas height.</param>
         private void ResizeCanvas(Thickness[] offset, int newWidth, int newHeight)
         private void ResizeCanvas(Thickness[] offset, int newWidth, int newHeight)
         {
         {
-            for (int i = 0; i < Layers.Count; i++)
+            for (var i = 0; i < Layers.Count; i++)
             {
             {
                 Layers[i].Offset = offset[i];
                 Layers[i].Offset = offset[i];
                 Layers[i].MaxWidth = newWidth;
                 Layers[i].MaxWidth = newWidth;
@@ -186,63 +183,56 @@ namespace PixiEditor.Models.DataHolders
         /// </summary>
         /// </summary>
         public void ClipCanvas()
         public void ClipCanvas()
         {
         {
-            DoubleCords points = GetEdgePoints();
-            int smallestX = points.Coords1.X;
-            int smallestY = points.Coords1.Y;
-            int biggestX = points.Coords2.X;
-            int biggestY = points.Coords2.Y;
+            var points = GetEdgePoints();
+            var smallestX = points.Coords1.X;
+            var smallestY = points.Coords1.Y;
+            var biggestX = points.Coords2.X;
+            var biggestY = points.Coords2.Y;
 
 
             if (smallestX == 0 && smallestY == 0 && biggestX == 0 && biggestY == 0)
             if (smallestX == 0 && smallestY == 0 && biggestX == 0 && biggestY == 0)
                 return;
                 return;
 
 
-            int width = biggestX - smallestX;
-            int height = biggestY - smallestY;
+            var width = biggestX - smallestX;
+            var height = biggestY - smallestY;
             var moveVector = new Coordinates(-smallestX, -smallestY);
             var moveVector = new Coordinates(-smallestX, -smallestY);
 
 
-            Thickness[] oldOffsets = Layers.Select(x => x.Offset).ToArray();
-            int oldWidth = Width;
-            int oldHeight = Height;
+            var oldOffsets = Layers.Select(x => x.Offset).ToArray();
+            var oldWidth = Width;
+            var oldHeight = Height;
 
 
             MoveOffsets(moveVector);
             MoveOffsets(moveVector);
             Width = width;
             Width = width;
             Height = height;
             Height = height;
 
 
-            object[] reverseArguments = { oldOffsets, oldWidth, oldHeight };
-            object[] processArguments = { Layers.Select(x => x.Offset).ToArray(), width, height};
+            object[] reverseArguments = {oldOffsets, oldWidth, oldHeight};
+            object[] processArguments = {Layers.Select(x => x.Offset).ToArray(), width, height};
 
 
-            UndoManager.AddUndoChange(new Change(ResizeCanvasProcess, reverseArguments, 
+            UndoManager.AddUndoChange(new Change(ResizeCanvasProcess, reverseArguments,
                 ResizeCanvasProcess, processArguments, "Clip canvas"));
                 ResizeCanvasProcess, processArguments, "Clip canvas"));
         }
         }
 
 
         private DoubleCords GetEdgePoints()
         private DoubleCords GetEdgePoints()
         {
         {
             var firstLayer = Layers[0];
             var firstLayer = Layers[0];
-            int smallestX = firstLayer.OffsetX;
-            int smallestY = firstLayer.OffsetY;
-            int biggestX = smallestX + firstLayer.Width;
-            int biggestY = smallestY + firstLayer.Height;
+            var smallestX = firstLayer.OffsetX;
+            var smallestY = firstLayer.OffsetY;
+            var biggestX = smallestX + firstLayer.Width;
+            var biggestY = smallestY + firstLayer.Height;
 
 
-            for (int i = 0; i < Layers.Count; i++)
+            for (var i = 0; i < Layers.Count; i++)
             {
             {
                 Layers[i].ClipCanvas();
                 Layers[i].ClipCanvas();
                 if (Layers[i].OffsetX < smallestX)
                 if (Layers[i].OffsetX < smallestX)
                     smallestX = Layers[i].OffsetX;
                     smallestX = Layers[i].OffsetX;
-                if (Layers[i].OffsetX + Layers[i].Width > biggestX)
-                {
-                    biggestX = Layers[i].OffsetX + Layers[i].Width;
-                }
+                if (Layers[i].OffsetX + Layers[i].Width > biggestX) biggestX = Layers[i].OffsetX + Layers[i].Width;
 
 
                 if (Layers[i].OffsetY < smallestY)
                 if (Layers[i].OffsetY < smallestY)
                     smallestY = Layers[i].OffsetY;
                     smallestY = Layers[i].OffsetY;
-                if (Layers[i].OffsetY + Layers[i].Height > biggestY)
-                {
-                    biggestY = Layers[i].OffsetY + Layers[i].Height;
-                }
+                if (Layers[i].OffsetY + Layers[i].Height > biggestY) biggestY = Layers[i].OffsetY + Layers[i].Height;
             }
             }
 
 
-            return new DoubleCords(new Coordinates(smallestX, smallestY), 
+            return new DoubleCords(new Coordinates(smallestX, smallestY),
                 new Coordinates(biggestX, biggestY));
                 new Coordinates(biggestX, biggestY));
-
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -251,27 +241,27 @@ namespace PixiEditor.Models.DataHolders
         /// <param name="moveVector"></param>
         /// <param name="moveVector"></param>
         private void MoveOffsets(Coordinates moveVector)
         private void MoveOffsets(Coordinates moveVector)
         {
         {
-            for (int i = 0; i < Layers.Count; i++)
+            for (var i = 0; i < Layers.Count; i++)
             {
             {
                 var offset = Layers[i].Offset;
                 var offset = Layers[i].Offset;
-                Layers[i].Offset = new Thickness(offset.Left + moveVector.X, offset.Top + moveVector.Y, 0,0 );
+                Layers[i].Offset = new Thickness(offset.Left + moveVector.X, offset.Top + moveVector.Y, 0, 0);
             }
             }
         }
         }
 
 
         private void MoveOffsetsProcess(object[] arguments)
         private void MoveOffsetsProcess(object[] arguments)
         {
         {
-            Coordinates vector = (Coordinates) arguments[0];
+            var vector = (Coordinates) arguments[0];
             MoveOffsets(vector);
             MoveOffsets(vector);
         }
         }
 
 
         public void CenterContent()
         public void CenterContent()
         {
         {
-            DoubleCords points = GetEdgePoints();
+            var points = GetEdgePoints();
 
 
-            int smallestX = points.Coords1.X;
-            int smallestY = points.Coords1.Y;
-            int biggestX = points.Coords2.X;
-            int biggestY = points.Coords2.Y;
+            var smallestX = points.Coords1.X;
+            var smallestY = points.Coords1.Y;
+            var biggestX = points.Coords2.X;
+            var biggestY = points.Coords2.Y;
 
 
             if (smallestX == 0 && smallestY == 0 && biggestX == 0 && biggestY == 0)
             if (smallestX == 0 && smallestY == 0 && biggestX == 0 && biggestY == 0)
                 return;
                 return;
@@ -279,21 +269,16 @@ namespace PixiEditor.Models.DataHolders
             var contentCenter = CoordinatesCalculator.GetCenterPoint(points.Coords1, points.Coords2);
             var contentCenter = CoordinatesCalculator.GetCenterPoint(points.Coords1, points.Coords2);
             var documentCenter = CoordinatesCalculator.GetCenterPoint(new Coordinates(0, 0),
             var documentCenter = CoordinatesCalculator.GetCenterPoint(new Coordinates(0, 0),
                 new Coordinates(Width, Height));
                 new Coordinates(Width, Height));
-            Coordinates moveVector = new Coordinates(documentCenter.X - contentCenter.X, documentCenter.Y - contentCenter.Y);
+            var moveVector = new Coordinates(documentCenter.X - contentCenter.X, documentCenter.Y - contentCenter.Y);
 
 
             MoveOffsets(moveVector);
             MoveOffsets(moveVector);
-            UndoManager.AddUndoChange(new Change(MoveOffsetsProcess, new object[]{ new Coordinates(-moveVector.X, -moveVector.Y) }, MoveOffsetsProcess, 
-                new object[]{moveVector}, "Center content"));
+            UndoManager.AddUndoChange(new Change(MoveOffsetsProcess, new object[] {new Coordinates(-moveVector.X, -moveVector.Y)}, MoveOffsetsProcess,
+                new object[] {moveVector}, "Center content"));
         }
         }
     }
     }
 
 
     public class DocumentSizeChangedEventArgs
     public class DocumentSizeChangedEventArgs
     {
     {
-        public int OldWidth { get; set; }
-        public int OldHeight { get; set; }
-        public int NewWidth { get; set; }
-        public int NewHeight { get; set; }
-
         public DocumentSizeChangedEventArgs(int oldWidth, int oldHeight, int newWidth, int newHeight)
         public DocumentSizeChangedEventArgs(int oldWidth, int oldHeight, int newWidth, int newHeight)
         {
         {
             OldWidth = oldWidth;
             OldWidth = oldWidth;
@@ -301,5 +286,10 @@ namespace PixiEditor.Models.DataHolders
             NewWidth = newWidth;
             NewWidth = newWidth;
             NewHeight = newHeight;
             NewHeight = newHeight;
         }
         }
+
+        public int OldWidth { get; set; }
+        public int OldHeight { get; set; }
+        public int NewWidth { get; set; }
+        public int NewHeight { get; set; }
     }
     }
 }
 }

+ 3 - 4
PixiEditor/Models/DataHolders/LayerChange.cs

@@ -1,14 +1,10 @@
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Layers;
-using PixiEditor.Models.Tools;
 using PixiEditor.ViewModels;
 using PixiEditor.ViewModels;
 
 
 namespace PixiEditor.Models.DataHolders
 namespace PixiEditor.Models.DataHolders
 {
 {
     public class LayerChange
     public class LayerChange
     {
     {
-        public BitmapPixelChanges PixelChanges { get; set; }
-        public int LayerIndex { get; set; }
-
         public LayerChange(BitmapPixelChanges pixelChanges, int layerIndex)
         public LayerChange(BitmapPixelChanges pixelChanges, int layerIndex)
         {
         {
             PixelChanges = pixelChanges;
             PixelChanges = pixelChanges;
@@ -20,5 +16,8 @@ namespace PixiEditor.Models.DataHolders
             PixelChanges = pixelChanges;
             PixelChanges = pixelChanges;
             LayerIndex = ViewModelMain.Current.BitmapManager.ActiveDocument.Layers.IndexOf(layer);
             LayerIndex = ViewModelMain.Current.BitmapManager.ActiveDocument.Layers.IndexOf(layer);
         }
         }
+
+        public BitmapPixelChanges PixelChanges { get; set; }
+        public int LayerIndex { get; set; }
     }
     }
 }
 }

+ 13 - 15
PixiEditor/Models/DataHolders/Selection.cs

@@ -6,38 +6,36 @@ using PixiEditor.Helpers;
 using PixiEditor.Models.Enums;
 using PixiEditor.Models.Enums;
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Position;
 using PixiEditor.Models.Position;
-using PixiEditor.Models.Tools;
-using PixiEditor.ViewModels;
 
 
 namespace PixiEditor.Models.DataHolders
 namespace PixiEditor.Models.DataHolders
 {
 {
     public class Selection : NotifyableObject
     public class Selection : NotifyableObject
     {
     {
+        private readonly Color selectionBlue;
+        private Layer selectionLayer;
+
+        public Selection(Coordinates[] selectedPoints)
+        {
+            SelectedPoints = new ObservableCollection<Coordinates>(selectedPoints);
+            SelectionLayer = new Layer("_selectionLayer");
+            selectionBlue = Color.FromArgb(127, 142, 202, 255);
+        }
+
         public ObservableCollection<Coordinates> SelectedPoints { get; private set; }
         public ObservableCollection<Coordinates> SelectedPoints { get; private set; }
 
 
         public Layer SelectionLayer
         public Layer SelectionLayer
         {
         {
-            get => _selectionLayer;
+            get => selectionLayer;
             set
             set
             {
             {
-                _selectionLayer = value;
+                selectionLayer = value;
                 RaisePropertyChanged("SelectionLayer");
                 RaisePropertyChanged("SelectionLayer");
             }
             }
         }
         }
 
 
-        private readonly Color _selectionBlue;
-        private Layer _selectionLayer;
-
-        public Selection(Coordinates[] selectedPoints)
-        {
-            SelectedPoints = new ObservableCollection<Coordinates>(selectedPoints);
-            SelectionLayer = new Layer("_selectionLayer");
-            _selectionBlue = Color.FromArgb(127, 142, 202, 255);
-        }
-
         public void SetSelection(IEnumerable<Coordinates> selection, SelectionType mode)
         public void SetSelection(IEnumerable<Coordinates> selection, SelectionType mode)
         {
         {
-            Color selectionColor = _selectionBlue;
+            var selectionColor = selectionBlue;
             switch (mode)
             switch (mode)
             {
             {
                 case SelectionType.New:
                 case SelectionType.New:

+ 11 - 11
PixiEditor/Models/DataHolders/SerializableDocument.cs

@@ -11,11 +11,6 @@ namespace PixiEditor.Models.DataHolders
     [Serializable]
     [Serializable]
     public class SerializableDocument
     public class SerializableDocument
     {
     {
-        public int Width { get; set; }
-        public int Height { get; set; }
-        public SerializableLayer[] Layers { get; set; }
-        public Tuple<byte, byte, byte, byte>[] Swatches { get; set; }
-
         public SerializableDocument(Document document)
         public SerializableDocument(Document document)
         {
         {
             Width = document.Width;
             Width = document.Width;
@@ -24,9 +19,14 @@ namespace PixiEditor.Models.DataHolders
             Swatches = document.Swatches.Select(x => new Tuple<byte, byte, byte, byte>(x.A, x.R, x.G, x.B)).ToArray();
             Swatches = document.Swatches.Select(x => new Tuple<byte, byte, byte, byte>(x.A, x.R, x.G, x.B)).ToArray();
         }
         }
 
 
+        public int Width { get; set; }
+        public int Height { get; set; }
+        public SerializableLayer[] Layers { get; set; }
+        public Tuple<byte, byte, byte, byte>[] Swatches { get; set; }
+
         public Document ToDocument()
         public Document ToDocument()
         {
         {
-            Document document = new Document(Width, Height)
+            var document = new Document(Width, Height)
             {
             {
                 Layers = ToLayers(),
                 Layers = ToLayers(),
                 Swatches = new ObservableCollection<Color>(Swatches.Select(x =>
                 Swatches = new ObservableCollection<Color>(Swatches.Select(x =>
@@ -37,12 +37,12 @@ namespace PixiEditor.Models.DataHolders
 
 
         public ObservableCollection<Layer> ToLayers()
         public ObservableCollection<Layer> ToLayers()
         {
         {
-            ObservableCollection<Layer> layers = new ObservableCollection<Layer>();
-            for (int i = 0; i < Layers.Length; i++)
+            var layers = new ObservableCollection<Layer>();
+            for (var i = 0; i < Layers.Length; i++)
             {
             {
-                SerializableLayer serLayer = Layers[i];
-                Layer layer =
-                    new Layer(serLayer.Name,BitmapUtils.BytesToWriteableBitmap(serLayer.Width, serLayer.Height, serLayer.BitmapBytes))
+                var serLayer = Layers[i];
+                var layer =
+                    new Layer(serLayer.Name, BitmapUtils.BytesToWriteableBitmap(serLayer.Width, serLayer.Height, serLayer.BitmapBytes))
                     {
                     {
                         IsVisible = serLayer.IsVisible,
                         IsVisible = serLayer.IsVisible,
                         Offset = new Thickness(serLayer.OffsetX, serLayer.OffsetY, 0, 0),
                         Offset = new Thickness(serLayer.OffsetX, serLayer.OffsetY, 0, 0),

+ 1 - 1
PixiEditor/Models/Dialogs/ConfirmationDialog.cs

@@ -7,7 +7,7 @@ namespace PixiEditor.Models.Dialogs
     {
     {
         public static ConfirmationType Show(string message)
         public static ConfirmationType Show(string message)
         {
         {
-            ConfirmationPopup popup = new ConfirmationPopup
+            var popup = new ConfirmationPopup
             {
             {
                 Body = message
                 Body = message
             };
             };

+ 23 - 23
PixiEditor/Models/Dialogs/ExportFileDialog.cs

@@ -5,14 +5,27 @@ namespace PixiEditor.Models.Dialogs
 {
 {
     public class ExportFileDialog : CustomDialog
     public class ExportFileDialog : CustomDialog
     {
     {
+        private int fileHeight;
+
+
+        private string filePath;
+
+        private int fileWidth;
+
+        public ExportFileDialog(Size fileDimensions)
+        {
+            FileHeight = (int) fileDimensions.Height;
+            FileWidth = (int) fileDimensions.Width;
+        }
+
         public int FileWidth
         public int FileWidth
         {
         {
-            get => _fileWidth;
+            get => fileWidth;
             set
             set
             {
             {
-                if (_fileWidth != value)
+                if (fileWidth != value)
                 {
                 {
-                    _fileWidth = value;
+                    fileWidth = value;
                     RaisePropertyChanged("Width");
                     RaisePropertyChanged("Width");
                 }
                 }
             }
             }
@@ -20,12 +33,12 @@ namespace PixiEditor.Models.Dialogs
 
 
         public int FileHeight
         public int FileHeight
         {
         {
-            get => _fileHeight;
+            get => fileHeight;
             set
             set
             {
             {
-                if (_fileHeight != value)
+                if (fileHeight != value)
                 {
                 {
-                    _fileHeight = value;
+                    fileHeight = value;
                     RaisePropertyChanged("FileHeight");
                     RaisePropertyChanged("FileHeight");
                 }
                 }
             }
             }
@@ -33,33 +46,20 @@ namespace PixiEditor.Models.Dialogs
 
 
         public string FilePath
         public string FilePath
         {
         {
-            get => _filePath;
+            get => filePath;
             set
             set
             {
             {
-                if (_filePath != value)
+                if (filePath != value)
                 {
                 {
-                    _filePath = value;
+                    filePath = value;
                     RaisePropertyChanged("FilePath");
                     RaisePropertyChanged("FilePath");
                 }
                 }
             }
             }
         }
         }
 
 
-        private int _fileHeight;
-
-
-        private string _filePath;
-
-        private int _fileWidth;
-
-        public ExportFileDialog(Size fileDimensions)
-        {
-            FileHeight = (int) fileDimensions.Height;
-            FileWidth = (int) fileDimensions.Width;
-        }
-
         public override bool ShowDialog()
         public override bool ShowDialog()
         {
         {
-            SaveFilePopup popup = new SaveFilePopup
+            var popup = new SaveFilePopup
             {
             {
                 SaveWidth = FileWidth,
                 SaveWidth = FileWidth,
                 SaveHeight = FileHeight
                 SaveHeight = FileHeight

+ 16 - 16
PixiEditor/Models/Dialogs/ImportFileDialog.cs

@@ -4,14 +4,20 @@ namespace PixiEditor.Models.Dialogs
 {
 {
     internal class ImportFileDialog : CustomDialog
     internal class ImportFileDialog : CustomDialog
     {
     {
+        private int fileHeight;
+
+
+        private string filePath;
+        private int fileWidth;
+
         public int FileWidth
         public int FileWidth
         {
         {
-            get => _fileWidth;
+            get => fileWidth;
             set
             set
             {
             {
-                if (_fileWidth != value)
+                if (fileWidth != value)
                 {
                 {
-                    _fileWidth = value;
+                    fileWidth = value;
                     RaisePropertyChanged("Width");
                     RaisePropertyChanged("Width");
                 }
                 }
             }
             }
@@ -19,12 +25,12 @@ namespace PixiEditor.Models.Dialogs
 
 
         public int FileHeight
         public int FileHeight
         {
         {
-            get => _fileHeight;
+            get => fileHeight;
             set
             set
             {
             {
-                if (_fileHeight != value)
+                if (fileHeight != value)
                 {
                 {
-                    _fileHeight = value;
+                    fileHeight = value;
                     RaisePropertyChanged("FileHeight");
                     RaisePropertyChanged("FileHeight");
                 }
                 }
             }
             }
@@ -32,26 +38,20 @@ namespace PixiEditor.Models.Dialogs
 
 
         public string FilePath
         public string FilePath
         {
         {
-            get => _filePath;
+            get => filePath;
             set
             set
             {
             {
-                if (_filePath != value)
+                if (filePath != value)
                 {
                 {
-                    _filePath = value;
+                    filePath = value;
                     RaisePropertyChanged("FilePath");
                     RaisePropertyChanged("FilePath");
                 }
                 }
             }
             }
         }
         }
 
 
-        private int _fileHeight;
-
-
-        private string _filePath;
-        private int _fileWidth;
-
         public override bool ShowDialog()
         public override bool ShowDialog()
         {
         {
-            ImportFilePopup popup = new ImportFilePopup();
+            var popup = new ImportFilePopup();
             popup.FilePath = FilePath;
             popup.FilePath = FilePath;
             popup.ShowDialog();
             popup.ShowDialog();
             if (popup.DialogResult == true)
             if (popup.DialogResult == true)

+ 10 - 10
PixiEditor/Models/Dialogs/NewFileDialog.cs

@@ -5,14 +5,18 @@ namespace PixiEditor.Models.Dialogs
 {
 {
     public class NewFileDialog : CustomDialog
     public class NewFileDialog : CustomDialog
     {
     {
+        private int height;
+
+        private int width;
+
         public int Width
         public int Width
         {
         {
-            get => _width;
+            get => width;
             set
             set
             {
             {
-                if (_width != value)
+                if (width != value)
                 {
                 {
-                    _width = value;
+                    width = value;
                     RaisePropertyChanged("Width");
                     RaisePropertyChanged("Width");
                 }
                 }
             }
             }
@@ -20,21 +24,17 @@ namespace PixiEditor.Models.Dialogs
 
 
         public int Height
         public int Height
         {
         {
-            get => _height;
+            get => height;
             set
             set
             {
             {
-                if (_height != value)
+                if (height != value)
                 {
                 {
-                    _height = value;
+                    height = value;
                     RaisePropertyChanged("Height");
                     RaisePropertyChanged("Height");
                 }
                 }
             }
             }
         }
         }
 
 
-        private int _height;
-
-        private int _width;
-
         public override bool ShowDialog()
         public override bool ShowDialog()
         {
         {
             Window popup = new NewFilePopup();
             Window popup = new NewFilePopup();

+ 18 - 18
PixiEditor/Models/Dialogs/ResizeDocumentDialog.cs

@@ -5,17 +5,27 @@ namespace PixiEditor.Models.Dialogs
 {
 {
     public class ResizeDocumentDialog : CustomDialog
     public class ResizeDocumentDialog : CustomDialog
     {
     {
+        private int height;
+        private int width;
+
+        public ResizeDocumentDialog(int currentWidth, int currentHeight, bool openResizeCanvas = false)
+        {
+            Width = currentWidth;
+            Height = currentHeight;
+            OpenResizeCanvas = openResizeCanvas;
+        }
+
         public bool OpenResizeCanvas { get; set; }
         public bool OpenResizeCanvas { get; set; }
         public AnchorPoint ResizeAnchor { get; set; }
         public AnchorPoint ResizeAnchor { get; set; }
 
 
         public int Width
         public int Width
         {
         {
-            get => _width;
+            get => width;
             set
             set
             {
             {
-                if (_width != value)
+                if (width != value)
                 {
                 {
-                    _width = value;
+                    width = value;
                     RaisePropertyChanged("Width");
                     RaisePropertyChanged("Width");
                 }
                 }
             }
             }
@@ -23,27 +33,17 @@ namespace PixiEditor.Models.Dialogs
 
 
         public int Height
         public int Height
         {
         {
-            get => _height;
+            get => height;
             set
             set
             {
             {
-                if (_height != value)
+                if (height != value)
                 {
                 {
-                    _height = value;
+                    height = value;
                     RaisePropertyChanged("Height");
                     RaisePropertyChanged("Height");
                 }
                 }
             }
             }
         }
         }
 
 
-        private int _height;
-        private int _width;
-
-        public ResizeDocumentDialog(int currentWidth, int currentHeight, bool openResizeCanvas = false)
-        {
-            Width = currentWidth;
-            Height = currentHeight;
-            OpenResizeCanvas = openResizeCanvas;
-        }
-
         public override bool ShowDialog()
         public override bool ShowDialog()
         {
         {
             return OpenResizeCanvas ? ShowResizeCanvasDialog() : ShowResizeDocumentCanvas();
             return OpenResizeCanvas ? ShowResizeCanvasDialog() : ShowResizeDocumentCanvas();
@@ -51,7 +51,7 @@ namespace PixiEditor.Models.Dialogs
 
 
         private bool ShowResizeDocumentCanvas()
         private bool ShowResizeDocumentCanvas()
         {
         {
-            ResizeDocumentPopup popup = new ResizeDocumentPopup
+            var popup = new ResizeDocumentPopup
             {
             {
                 NewHeight = Height,
                 NewHeight = Height,
                 NewWidth = Width
                 NewWidth = Width
@@ -69,7 +69,7 @@ namespace PixiEditor.Models.Dialogs
 
 
         private bool ShowResizeCanvasDialog()
         private bool ShowResizeCanvasDialog()
         {
         {
-            ResizeCanvasPopup popup = new ResizeCanvasPopup
+            var popup = new ResizeCanvasPopup
             {
             {
                 NewHeight = Height,
                 NewHeight = Height,
                 NewWidth = Width
                 NewWidth = Width

+ 4 - 7
PixiEditor/Models/Enums/BrightnessMode.cs

@@ -1,11 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-
-namespace PixiEditor.Models.Enums
+namespace PixiEditor.Models.Enums
 {
 {
     public enum BrightnessMode
     public enum BrightnessMode
     {
     {
-        Default, Repeat
+        Default,
+        Repeat
     }
     }
-}
+}

+ 4 - 7
PixiEditor/Models/Enums/CapType.cs

@@ -1,11 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-
-namespace PixiEditor.Models.Enums
+namespace PixiEditor.Models.Enums
 {
 {
     public enum CapType
     public enum CapType
     {
     {
-        Square, Round
+        Square,
+        Round
     }
     }
-}
+}

+ 1 - 1
PixiEditor/Models/Enums/FileType.cs

@@ -2,6 +2,6 @@
 {
 {
     public enum FileType
     public enum FileType
     {
     {
-        PNG = 0
+        Png = 0
     }
     }
 }
 }

+ 2 - 2
PixiEditor/Models/Events/DocumentChangedEventArgs.cs

@@ -4,11 +4,11 @@ namespace PixiEditor.Models.Events
 {
 {
     public class DocumentChangedEventArgs
     public class DocumentChangedEventArgs
     {
     {
-        public Document NewDocument { get; set; }
-
         public DocumentChangedEventArgs(Document newDocument)
         public DocumentChangedEventArgs(Document newDocument)
         {
         {
             NewDocument = newDocument;
             NewDocument = newDocument;
         }
         }
+
+        public Document NewDocument { get; set; }
     }
     }
 }
 }

+ 2 - 2
PixiEditor/Models/IO/BinarySerialization.cs

@@ -9,7 +9,7 @@ namespace PixiEditor.Models.IO
         {
         {
             using (Stream stream = File.Open(path, FileMode.Create))
             using (Stream stream = File.Open(path, FileMode.Create))
             {
             {
-                BinaryFormatter binaryFormatter = new BinaryFormatter();
+                var binaryFormatter = new BinaryFormatter();
                 binaryFormatter.Serialize(stream, objectToWrite);
                 binaryFormatter.Serialize(stream, objectToWrite);
             }
             }
         }
         }
@@ -18,7 +18,7 @@ namespace PixiEditor.Models.IO
         {
         {
             using (Stream stream = File.Open(path, FileMode.Open))
             using (Stream stream = File.Open(path, FileMode.Open))
             {
             {
-                BinaryFormatter formatter = new BinaryFormatter();
+                var formatter = new BinaryFormatter();
                 return (T) formatter.Deserialize(stream);
                 return (T) formatter.Deserialize(stream);
             }
             }
         }
         }

+ 5 - 5
PixiEditor/Models/IO/Exporter.cs

@@ -21,12 +21,12 @@ namespace PixiEditor.Models.IO
         /// <param name="updateWorkspacePath">Should editor remember dialog path for further saves</param>
         /// <param name="updateWorkspacePath">Should editor remember dialog path for further saves</param>
         public static bool SaveAsEditableFileWithDialog(Document document, bool updateWorkspacePath = false)
         public static bool SaveAsEditableFileWithDialog(Document document, bool updateWorkspacePath = false)
         {
         {
-            SaveFileDialog dialog = new SaveFileDialog
+            var dialog = new SaveFileDialog
             {
             {
                 Filter = "PixiEditor Files | *.pixi",
                 Filter = "PixiEditor Files | *.pixi",
                 DefaultExt = "pixi"
                 DefaultExt = "pixi"
             };
             };
-            if ((bool)dialog.ShowDialog())
+            if ((bool) dialog.ShowDialog())
             {
             {
                 SaveAsEditableFile(document, dialog.FileName, updateWorkspacePath);
                 SaveAsEditableFile(document, dialog.FileName, updateWorkspacePath);
                 return true;
                 return true;
@@ -50,7 +50,7 @@ namespace PixiEditor.Models.IO
         /// <param name="fileDimensions">Size of file</param>
         /// <param name="fileDimensions">Size of file</param>
         public static void Export(WriteableBitmap bitmap, Size fileDimensions)
         public static void Export(WriteableBitmap bitmap, Size fileDimensions)
         {
         {
-            ExportFileDialog info = new ExportFileDialog(fileDimensions);
+            var info = new ExportFileDialog(fileDimensions);
             //If OK on dialog has been clicked
             //If OK on dialog has been clicked
             if (info.ShowDialog())
             if (info.ShowDialog())
             {
             {
@@ -80,9 +80,9 @@ namespace PixiEditor.Models.IO
             {
             {
                 bitmap = bitmap.Resize(exportWidth, exportHeight,
                 bitmap = bitmap.Resize(exportWidth, exportHeight,
                     WriteableBitmapExtensions.Interpolation.NearestNeighbor);
                     WriteableBitmapExtensions.Interpolation.NearestNeighbor);
-                using (FileStream stream = new FileStream(savePath, FileMode.Create))
+                using (var stream = new FileStream(savePath, FileMode.Create))
                 {
                 {
-                    PngBitmapEncoder encoder = new PngBitmapEncoder();
+                    var encoder = new PngBitmapEncoder();
                     encoder.Frames.Add(BitmapFrame.Create(bitmap));
                     encoder.Frames.Add(BitmapFrame.Create(bitmap));
                     encoder.Save(stream);
                     encoder.Save(stream);
                 }
                 }

+ 3 - 6
PixiEditor/Models/IO/Importer.cs

@@ -17,10 +17,7 @@ namespace PixiEditor.Models.IO
         public static WriteableBitmap ImportImage(string path, int width, int height)
         public static WriteableBitmap ImportImage(string path, int width, int height)
         {
         {
             var wbmp = ImportImage(path);
             var wbmp = ImportImage(path);
-            if (wbmp.PixelWidth != width || wbmp.PixelHeight != height)
-            {
-                return wbmp.Resize(width, height, WriteableBitmapExtensions.Interpolation.NearestNeighbor);
-            }
+            if (wbmp.PixelWidth != width || wbmp.PixelHeight != height) return wbmp.Resize(width, height, WriteableBitmapExtensions.Interpolation.NearestNeighbor);
 
 
             return wbmp;
             return wbmp;
         }
         }
@@ -31,8 +28,8 @@ namespace PixiEditor.Models.IO
         /// <param name="path">Path of image.</param>
         /// <param name="path">Path of image.</param>
         public static WriteableBitmap ImportImage(string path)
         public static WriteableBitmap ImportImage(string path)
         {
         {
-            Uri uri = new Uri(path);
-            BitmapImage bitmap = new BitmapImage();
+            var uri = new Uri(path);
+            var bitmap = new BitmapImage();
             bitmap.BeginInit();
             bitmap.BeginInit();
             bitmap.UriSource = uri;
             bitmap.UriSource = uri;
             bitmap.EndInit();
             bitmap.EndInit();

+ 14 - 19
PixiEditor/Models/ImageManipulation/BitmapUtils.cs

@@ -1,12 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Drawing;
-using System.Windows;
-using System.Windows.Interop;
+using System.Collections.Generic;
+using System.Windows.Media;
 using System.Windows.Media.Imaging;
 using System.Windows.Media.Imaging;
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Position;
 using PixiEditor.Models.Position;
-using Color = System.Windows.Media.Color;
 
 
 namespace PixiEditor.Models.ImageManipulation
 namespace PixiEditor.Models.ImageManipulation
 {
 {
@@ -22,7 +18,7 @@ namespace PixiEditor.Models.ImageManipulation
         public static WriteableBitmap BytesToWriteableBitmap(int currentBitmapWidth, int currentBitmapHeight,
         public static WriteableBitmap BytesToWriteableBitmap(int currentBitmapWidth, int currentBitmapHeight,
             byte[] byteArray)
             byte[] byteArray)
         {
         {
-            WriteableBitmap bitmap = BitmapFactory.New(currentBitmapWidth, currentBitmapHeight);
+            var bitmap = BitmapFactory.New(currentBitmapWidth, currentBitmapHeight);
             bitmap.FromByteArray(byteArray);
             bitmap.FromByteArray(byteArray);
             return bitmap;
             return bitmap;
         }
         }
@@ -36,16 +32,16 @@ namespace PixiEditor.Models.ImageManipulation
         /// <returns>WriteableBitmap of layered bitmaps</returns>
         /// <returns>WriteableBitmap of layered bitmaps</returns>
         public static WriteableBitmap CombineLayers(Layer[] layers, int width, int height)
         public static WriteableBitmap CombineLayers(Layer[] layers, int width, int height)
         {
         {
-            WriteableBitmap finalBitmap = BitmapFactory.New(width, height);
+            var finalBitmap = BitmapFactory.New(width, height);
 
 
             using (finalBitmap.GetBitmapContext())
             using (finalBitmap.GetBitmapContext())
             {
             {
-                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 (var i = 0; i < layers.Length; i++)
+                for (var y = 0; y < finalBitmap.Height; y++)
+                for (var x = 0; x < finalBitmap.Width; x++)
                 {
                 {
-                    Color color = layers[i].GetPixelWithOffset(x, y);
-                    color = Color.FromArgb((byte)(color.A * layers[i].Opacity), color.R,color.G, color.B);
+                    var color = layers[i].GetPixelWithOffset(x, y);
+                    color = Color.FromArgb((byte) (color.A * layers[i].Opacity), color.R, color.G, color.B);
                     if (color.A != 0 || color.R != 0 || color.B != 0 || color.G != 0) finalBitmap.SetPixel(x, y, color);
                     if (color.A != 0 || color.R != 0 || color.B != 0 || color.G != 0) finalBitmap.SetPixel(x, y, color);
                 }
                 }
             }
             }
@@ -55,18 +51,17 @@ namespace PixiEditor.Models.ImageManipulation
 
 
         public static Dictionary<Layer, Color[]> GetPixelsForSelection(Layer[] layers, Coordinates[] selection)
         public static Dictionary<Layer, Color[]> GetPixelsForSelection(Layer[] layers, Coordinates[] selection)
         {
         {
-            Dictionary<Layer, Color[]> result = new Dictionary<Layer, Color[]>();
+            var result = new Dictionary<Layer, Color[]>();
 
 
-            for (int i = 0; i < layers.Length; i++)
+            for (var i = 0; i < layers.Length; i++)
             {
             {
-                Color[] pixels = new Color[selection.Length];
+                var pixels = new Color[selection.Length];
 
 
                 using (layers[i].LayerBitmap.GetBitmapContext())
                 using (layers[i].LayerBitmap.GetBitmapContext())
                 {
                 {
-
-                    for (int j = 0; j < pixels.Length; j++)
+                    for (var j = 0; j < pixels.Length; j++)
                     {
                     {
-                        Coordinates position = layers[i].GetRelativePosition(selection[j]);
+                        var position = layers[i].GetRelativePosition(selection[j]);
                         if (position.X < 0 || position.X > layers[i].Width - 1 || position.Y < 0 ||
                         if (position.X < 0 || position.X > layers[i].Width - 1 || position.Y < 0 ||
                             position.Y > layers[i].Height - 1)
                             position.Y > layers[i].Height - 1)
                             continue;
                             continue;

+ 26 - 25
PixiEditor/Models/ImageManipulation/Morphology.cs

@@ -9,26 +9,26 @@ namespace PixiEditor.Models.ImageManipulation
     {
     {
         public static IEnumerable<Coordinates> ApplyDilation(Coordinates[] points, int kernelSize, int[,] mask)
         public static IEnumerable<Coordinates> ApplyDilation(Coordinates[] points, int kernelSize, int[,] mask)
         {
         {
-            int kernelDim = kernelSize;
+            var kernelDim = kernelSize;
 
 
             //This is the offset of center pixel from border of the kernel
             //This is the offset of center pixel from border of the kernel
-            int kernelOffset = (kernelDim - 1) / 2;
-            int margin = kernelDim;
+            var kernelOffset = (kernelDim - 1) / 2;
+            var margin = kernelDim;
 
 
-            byte[,] byteImg = GetByteArrayForPoints(points, margin);
-            byte[,] outputArray = byteImg.Clone() as byte[,];
-            Coordinates offset = new Coordinates(points.Min(x => x.X) - margin, points.Min(x => x.Y) - margin);
+            var byteImg = GetByteArrayForPoints(points, margin);
+            var outputArray = byteImg.Clone() as byte[,];
+            var offset = new Coordinates(points.Min(x => x.X) - margin, points.Min(x => x.Y) - margin);
 
 
-            int width = byteImg.GetLength(0);
-            int height = byteImg.GetLength(1);
-            for (int y = kernelOffset; y < height - kernelOffset; y++)
-            for (int x = kernelOffset; x < width - kernelOffset; x++)
+            var width = byteImg.GetLength(0);
+            var height = byteImg.GetLength(1);
+            for (var y = kernelOffset; y < height - kernelOffset; y++)
+            for (var x = kernelOffset; x < width - kernelOffset; x++)
             {
             {
                 byte value = 0;
                 byte value = 0;
 
 
                 //Apply dilation
                 //Apply dilation
-                for (int ykernel = -kernelOffset; ykernel <= kernelOffset; ykernel++)
-                for (int xkernel = -kernelOffset; xkernel <= kernelOffset; xkernel++)
+                for (var ykernel = -kernelOffset; ykernel <= kernelOffset; ykernel++)
+                for (var xkernel = -kernelOffset; xkernel <= kernelOffset; xkernel++)
                     if (mask[xkernel + kernelOffset, ykernel + kernelOffset] == 1)
                     if (mask[xkernel + kernelOffset, ykernel + kernelOffset] == 1)
                         value = Math.Max(value, byteImg[x + xkernel, y + ykernel]);
                         value = Math.Max(value, byteImg[x + xkernel, y + ykernel]);
                     else
                     else
@@ -42,11 +42,11 @@ namespace PixiEditor.Models.ImageManipulation
 
 
         private static IEnumerable<Coordinates> ToCoordinates(byte[,] byteArray, Coordinates offset)
         private static IEnumerable<Coordinates> ToCoordinates(byte[,] byteArray, Coordinates offset)
         {
         {
-            List<Coordinates> output = new List<Coordinates>();
-            int width = byteArray.GetLength(0);
+            var output = new List<Coordinates>();
+            var width = byteArray.GetLength(0);
 
 
-            for (int y = 0; y < byteArray.GetLength(1); y++)
-            for (int x = 0; x < width; x++)
+            for (var y = 0; y < byteArray.GetLength(1); y++)
+            for (var x = 0; x < width; x++)
                 if (byteArray[x, y] == 1)
                 if (byteArray[x, y] == 1)
                     output.Add(new Coordinates(x + offset.X, y + offset.Y));
                     output.Add(new Coordinates(x + offset.X, y + offset.Y));
             return output;
             return output;
@@ -54,24 +54,25 @@ namespace PixiEditor.Models.ImageManipulation
 
 
         private static byte[,] GetByteArrayForPoints(Coordinates[] points, int margin)
         private static byte[,] GetByteArrayForPoints(Coordinates[] points, int margin)
         {
         {
-            Tuple<int, int> dimensions = GetDimensionsForPoints(points);
-            int minX = points.Min(x => x.X);
-            int minY = points.Min(x => x.Y);
-            byte[,] array = new byte[dimensions.Item1 + margin * 2, dimensions.Item2 + margin * 2];
+            var dimensions = GetDimensionsForPoints(points);
+            var minX = points.Min(x => x.X);
+            var minY = points.Min(x => x.Y);
+            var array = new byte[dimensions.Item1 + margin * 2, dimensions.Item2 + margin * 2];
 
 
-            for (int y = 0; y < dimensions.Item2 + margin; y++)
-            for (int x = 0; x < dimensions.Item1 + margin; x++)
+            for (var y = 0; y < dimensions.Item2 + margin; y++)
+            for (var x = 0; x < dimensions.Item1 + margin; x++)
             {
             {
-                Coordinates cords = new Coordinates(x + minX, y + minY);
+                var cords = new Coordinates(x + minX, y + minY);
                 array[x + margin, y + margin] = points.Contains(cords) ? (byte) 1 : (byte) 0;
                 array[x + margin, y + margin] = points.Contains(cords) ? (byte) 1 : (byte) 0;
             }
             }
+
             return array;
             return array;
         }
         }
 
 
         private static Tuple<int, int> GetDimensionsForPoints(Coordinates[] points)
         private static Tuple<int, int> GetDimensionsForPoints(Coordinates[] points)
         {
         {
-            int width = points.Max(x => x.X) - points.Min(x => x.X);
-            int height = points.Max(x => x.Y) - points.Min(x => x.Y);
+            var width = points.Max(x => x.X) - points.Min(x => x.X);
+            var height = points.Max(x => x.Y) - points.Min(x => x.Y);
             return new Tuple<int, int>(width + 1, height + 1);
             return new Tuple<int, int>(width + 1, height + 1);
         }
         }
     }
     }

+ 4 - 4
PixiEditor/Models/ImageManipulation/Transform.cs

@@ -12,15 +12,15 @@ namespace PixiEditor.Models.ImageManipulation
         /// <returns>Translation as coordinate</returns>
         /// <returns>Translation as coordinate</returns>
         public static Coordinates GetTranslation(Coordinates from, Coordinates to)
         public static Coordinates GetTranslation(Coordinates from, Coordinates to)
         {
         {
-            int translationX = to.X - from.X;
-            int translationY = to.Y - from.Y;
+            var translationX = to.X - from.X;
+            var translationY = to.Y - from.Y;
             return new Coordinates(translationX, translationY);
             return new Coordinates(translationX, translationY);
         }
         }
 
 
         public static Coordinates[] Translate(Coordinates[] points, Coordinates vector)
         public static Coordinates[] Translate(Coordinates[] points, Coordinates vector)
         {
         {
-            Coordinates[] translatedPoints = new Coordinates[points.Length];
-            for (int i = 0; i < translatedPoints.Length; i++)
+            var translatedPoints = new Coordinates[points.Length];
+            for (var i = 0; i < translatedPoints.Length; i++)
                 translatedPoints[i] = new Coordinates(points[i].X + vector.X, points[i].Y + vector.Y);
                 translatedPoints[i] = new Coordinates(points[i].X + vector.X, points[i].Y + vector.Y);
             return translatedPoints;
             return translatedPoints;
         }
         }

+ 8 - 8
PixiEditor/Models/Layers/BasicLayer.cs

@@ -6,28 +6,28 @@ namespace PixiEditor.Models.Layers
     [Serializable]
     [Serializable]
     public class BasicLayer : NotifyableObject
     public class BasicLayer : NotifyableObject
     {
     {
+        private int height;
+
+        private int width;
+
         public int Width
         public int Width
         {
         {
-            get => _width;
+            get => width;
             set
             set
             {
             {
-                _width = value;
+                width = value;
                 RaisePropertyChanged("Width");
                 RaisePropertyChanged("Width");
             }
             }
         }
         }
 
 
         public int Height
         public int Height
         {
         {
-            get => _height;
+            get => height;
             set
             set
             {
             {
-                _height = value;
+                height = value;
                 RaisePropertyChanged("Height");
                 RaisePropertyChanged("Height");
             }
             }
         }
         }
-
-        private int _height;
-
-        private int _width;
     }
     }
 }
 }

+ 108 - 123
PixiEditor/Models/Layers/Layer.cs

@@ -6,51 +6,89 @@ using System.Windows.Media;
 using System.Windows.Media.Imaging;
 using System.Windows.Media.Imaging;
 using PixiEditor.Models.DataHolders;
 using PixiEditor.Models.DataHolders;
 using PixiEditor.Models.Position;
 using PixiEditor.Models.Position;
-using PixiEditor.Models.Tools;
 
 
 namespace PixiEditor.Models.Layers
 namespace PixiEditor.Models.Layers
 {
 {
     public class Layer : BasicLayer
     public class Layer : BasicLayer
     {
     {
-
         private const int SizeOfArgb = 4;
         private const int SizeOfArgb = 4;
+        private bool clipRequested;
+
+        private bool isActive;
+
+        private bool isRenaming;
+        private bool isVisible = true;
+        private WriteableBitmap layerBitmap;
+
+        private string name;
+
+        private Thickness offset;
+
+        private float opacity = 1;
+
+        public Dictionary<Coordinates, Color> LastRelativeCoordinates;
+
+        public Layer(string name)
+        {
+            Name = name;
+            LayerBitmap = BitmapFactory.New(0, 0);
+            Width = 0;
+            Height = 0;
+        }
+
+        public Layer(string name, int width, int height)
+        {
+            Name = name;
+            LayerBitmap = BitmapFactory.New(width, height);
+            Width = width;
+            Height = height;
+        }
+
+
+        public Layer(string name, WriteableBitmap layerBitmap)
+        {
+            Name = name;
+            LayerBitmap = layerBitmap;
+            Width = layerBitmap.PixelWidth;
+            Height = layerBitmap.PixelHeight;
+        }
 
 
         public string Name
         public string Name
         {
         {
-            get => _name;
+            get => name;
             set
             set
             {
             {
-                _name = value;
+                name = value;
                 RaisePropertyChanged("Name");
                 RaisePropertyChanged("Name");
             }
             }
         }
         }
 
 
         public bool IsActive
         public bool IsActive
         {
         {
-            get => _isActive;
+            get => isActive;
             set
             set
             {
             {
-                _isActive = value;
+                isActive = value;
                 RaisePropertyChanged("IsActive");
                 RaisePropertyChanged("IsActive");
             }
             }
         }
         }
 
 
         public bool IsVisible
         public bool IsVisible
         {
         {
-            get => _isVisible;
+            get => isVisible;
             set
             set
             {
             {
-                _isVisible = value;
+                isVisible = value;
                 RaisePropertyChanged("IsVisible");
                 RaisePropertyChanged("IsVisible");
             }
             }
         }
         }
 
 
         public bool IsRenaming
         public bool IsRenaming
         {
         {
-            get => _isRenaming;
+            get => isRenaming;
             set
             set
             {
             {
-                _isRenaming = value;
+                isRenaming = value;
                 RaisePropertyChanged("IsRenaming");
                 RaisePropertyChanged("IsRenaming");
             }
             }
         }
         }
@@ -58,22 +96,20 @@ namespace PixiEditor.Models.Layers
 
 
         public WriteableBitmap LayerBitmap
         public WriteableBitmap LayerBitmap
         {
         {
-            get => _layerBitmap;
+            get => layerBitmap;
             set
             set
             {
             {
-                _layerBitmap = value;
+                layerBitmap = value;
                 RaisePropertyChanged("LayerBitmap");
                 RaisePropertyChanged("LayerBitmap");
             }
             }
         }
         }
 
 
-        private float _opacity = 1;
-
         public float Opacity
         public float Opacity
         {
         {
-            get => _opacity;
+            get => opacity;
             set
             set
             {
             {
-                _opacity = value;
+                opacity = value;
                 RaisePropertyChanged("Opacity");
                 RaisePropertyChanged("Opacity");
             }
             }
         }
         }
@@ -82,72 +118,34 @@ namespace PixiEditor.Models.Layers
 
 
         public int OffsetY => (int) Offset.Top;
         public int OffsetY => (int) Offset.Top;
 
 
-        private Thickness _offset;
-
         public Thickness Offset
         public Thickness Offset
         {
         {
-            get => _offset;
+            get => offset;
             set
             set
             {
             {
-                _offset = value;
+                offset = value;
                 RaisePropertyChanged("Offset");
                 RaisePropertyChanged("Offset");
             }
             }
         }
         }
 
 
-        private bool _isActive;
-
-        private bool _isRenaming;
-        private bool _isVisible = true;
-        private WriteableBitmap _layerBitmap;
-
-        private string _name;
-        private bool _clipRequested;
-
         public int MaxWidth { get; set; } = int.MaxValue;
         public int MaxWidth { get; set; } = int.MaxValue;
         public int MaxHeight { get; set; } = int.MaxValue;
         public int MaxHeight { get; set; } = int.MaxValue;
 
 
-        public Dictionary<Coordinates,Color> LastRelativeCoordinates;
-
-        public Layer(string name)
-        {
-            Name = name;
-            LayerBitmap = BitmapFactory.New(0, 0);
-            Width = 0;
-            Height = 0;
-        }
-
-        public Layer(string name, int width, int height)
-        {
-            Name = name;
-            LayerBitmap = BitmapFactory.New(width, height);
-            Width = width;
-            Height = height;
-        }
-
-
-        public Layer(string name, WriteableBitmap layerBitmap)
-        {
-            Name = name;
-            LayerBitmap = layerBitmap;
-            Width = layerBitmap.PixelWidth;
-            Height = layerBitmap.PixelHeight;
-        }
-
         /// <summary>
         /// <summary>
-        /// Returns clone of layer
+        ///     Returns clone of layer
         /// </summary>
         /// </summary>
         /// <returns></returns>
         /// <returns></returns>
         public Layer Clone()
         public Layer Clone()
         {
         {
             return new Layer(Name, LayerBitmap.Clone())
             return new Layer(Name, LayerBitmap.Clone())
             {
             {
-                IsVisible = this.IsVisible,
-                Offset = this.Offset,
-                MaxHeight = this.MaxHeight,
-                MaxWidth = this.MaxWidth,
-                Opacity = this.Opacity,
-                IsActive = this.IsActive,
-                IsRenaming = this.IsRenaming
+                IsVisible = IsVisible,
+                Offset = Offset,
+                MaxHeight = MaxHeight,
+                MaxWidth = MaxWidth,
+                Opacity = Opacity,
+                IsActive = IsActive,
+                IsRenaming = IsRenaming
             };
             };
         }
         }
 
 
@@ -185,7 +183,7 @@ namespace PixiEditor.Models.Layers
         /// <returns>Color of a pixel</returns>
         /// <returns>Color of a pixel</returns>
         public Color GetPixelWithOffset(int x, int y)
         public Color GetPixelWithOffset(int x, int y)
         {
         {
-            Coordinates cords = GetRelativePosition(new Coordinates(x, y));
+            var cords = GetRelativePosition(new Coordinates(x, y));
             return GetPixel(cords.X, cords.Y);
             return GetPixel(cords.X, cords.Y);
         }
         }
 
 
@@ -197,10 +195,7 @@ namespace PixiEditor.Models.Layers
         /// <returns>Color of pixel, if out of bounds, returns transparent pixel.</returns>
         /// <returns>Color of pixel, if out of bounds, returns transparent pixel.</returns>
         public Color GetPixel(int x, int y)
         public Color GetPixel(int x, int y)
         {
         {
-            if (x > Width - 1 || x < 0 || y > Height - 1 || y < 0)
-            {
-                return Color.FromArgb(0, 0, 0, 0);
-            }
+            if (x > Width - 1 || x < 0 || y > Height - 1 || y < 0) return Color.FromArgb(0, 0, 0, 0);
 
 
             return LayerBitmap.GetPixel(x, y);
             return LayerBitmap.GetPixel(x, y);
         }
         }
@@ -214,7 +209,7 @@ namespace PixiEditor.Models.Layers
         /// <param name="applyOffset">Converts pixels coordinates to relative to bitmap</param>
         /// <param name="applyOffset">Converts pixels coordinates to relative to bitmap</param>
         public void SetPixel(Coordinates coordinates, Color color, bool dynamicResize = true, bool applyOffset = true)
         public void SetPixel(Coordinates coordinates, Color color, bool dynamicResize = true, bool applyOffset = true)
         {
         {
-            SetPixels(BitmapPixelChanges.FromSingleColoredArray(new []{ coordinates }, color), dynamicResize, applyOffset);
+            SetPixels(BitmapPixelChanges.FromSingleColoredArray(new[] {coordinates}, color), dynamicResize, applyOffset);
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -226,9 +221,9 @@ namespace PixiEditor.Models.Layers
         public void SetPixels(BitmapPixelChanges pixels, bool dynamicResize = true, bool applyOffset = true)
         public void SetPixels(BitmapPixelChanges pixels, bool dynamicResize = true, bool applyOffset = true)
         {
         {
             if (pixels.ChangedPixels == null || pixels.ChangedPixels.Count == 0) return;
             if (pixels.ChangedPixels == null || pixels.ChangedPixels.Count == 0) return;
-            if(dynamicResize)
+            if (dynamicResize)
                 DynamicResize(pixels);
                 DynamicResize(pixels);
-            if(applyOffset)
+            if (applyOffset)
                 pixels.ChangedPixels = GetRelativePosition(pixels.ChangedPixels);
                 pixels.ChangedPixels = GetRelativePosition(pixels.ChangedPixels);
             LastRelativeCoordinates = pixels.ChangedPixels;
             LastRelativeCoordinates = pixels.ChangedPixels;
 
 
@@ -240,6 +235,7 @@ namespace PixiEditor.Models.Layers
                     ctx.WriteableBitmap.SetPixel(coords.Key.X, coords.Key.Y, coords.Value);
                     ctx.WriteableBitmap.SetPixel(coords.Key.X, coords.Key.Y, coords.Value);
                 }
                 }
             }
             }
+
             ClipIfNecessary();
             ClipIfNecessary();
         }
         }
 
 
@@ -256,11 +252,8 @@ namespace PixiEditor.Models.Layers
         /// <returns></returns>
         /// <returns></returns>
         public Coordinates[] ConvertToRelativeCoordinates(Coordinates[] nonRelativeCords)
         public Coordinates[] ConvertToRelativeCoordinates(Coordinates[] nonRelativeCords)
         {
         {
-            Coordinates[] result = new Coordinates[nonRelativeCords.Length];
-            for (int i = 0; i < nonRelativeCords.Length; i++)
-            {
-                result[i] = new Coordinates(nonRelativeCords[i].X - OffsetX, nonRelativeCords[i].Y - OffsetY);
-            }
+            var result = new Coordinates[nonRelativeCords.Length];
+            for (var i = 0; i < nonRelativeCords.Length; i++) result[i] = new Coordinates(nonRelativeCords[i].X - OffsetX, nonRelativeCords[i].Y - OffsetY);
 
 
             return result;
             return result;
         }
         }
@@ -274,38 +267,30 @@ namespace PixiEditor.Models.Layers
             if (pixels.ChangedPixels.Count == 0) return;
             if (pixels.ChangedPixels.Count == 0) return;
             ResetOffset(pixels);
             ResetOffset(pixels);
             var borderData = ExtractBorderData(pixels);
             var borderData = ExtractBorderData(pixels);
-            DoubleCords minMaxCords = borderData.Item1;
-            int newMaxX = minMaxCords.Coords2.X - OffsetX;
-            int newMaxY = minMaxCords.Coords2.Y - OffsetY;
-            int newMinX = minMaxCords.Coords1.X - OffsetX;
-            int newMinY = minMaxCords.Coords1.Y - OffsetY;
+            var minMaxCords = borderData.Item1;
+            var newMaxX = minMaxCords.Coords2.X - OffsetX;
+            var newMaxY = minMaxCords.Coords2.Y - OffsetY;
+            var newMinX = minMaxCords.Coords1.X - OffsetX;
+            var newMinY = minMaxCords.Coords1.Y - OffsetY;
 
 
             if (!(pixels.WasBuiltAsSingleColored && pixels.ChangedPixels.First().Value.A == 0))
             if (!(pixels.WasBuiltAsSingleColored && pixels.ChangedPixels.First().Value.A == 0))
             {
             {
-                if (newMaxX + 1 > Width || newMaxY + 1 > Height)
-                {
-                    IncreaseSizeToBottom(newMaxX, newMaxY);
-                }
-                if (newMinX < 0 || newMinY < 0)
-                {
-                    IncreaseSizeToTop(newMinX, newMinY);
-                }
+                if (newMaxX + 1 > Width || newMaxY + 1 > Height) IncreaseSizeToBottom(newMaxX, newMaxY);
+                if (newMinX < 0 || newMinY < 0) IncreaseSizeToTop(newMinX, newMinY);
             }
             }
 
 
-            if(borderData.Item2) //if clip is requested
-            {
-                _clipRequested = true;
-            }
+            if (borderData.Item2) //if clip is requested
+                clipRequested = true;
         }
         }
 
 
         private Tuple<DoubleCords, bool> ExtractBorderData(BitmapPixelChanges pixels)
         private Tuple<DoubleCords, bool> ExtractBorderData(BitmapPixelChanges pixels)
         {
         {
-            Coordinates firstCords = pixels.ChangedPixels.First().Key;
-            int minX = firstCords.X;
-            int minY = firstCords.Y;
-            int maxX = minX;
-            int maxY = minY;
-            bool clipRequested = false;
+            var firstCords = pixels.ChangedPixels.First().Key;
+            var minX = firstCords.X;
+            var minY = firstCords.Y;
+            var maxX = minX;
+            var maxY = minY;
+            var clipRequested = false;
 
 
             foreach (var pixel in pixels.ChangedPixels)
             foreach (var pixel in pixels.ChangedPixels)
             {
             {
@@ -317,8 +302,8 @@ namespace PixiEditor.Models.Layers
 
 
                 if (clipRequested == false && IsBorderPixel(pixel.Key) && pixel.Value.A == 0)
                 if (clipRequested == false && IsBorderPixel(pixel.Key) && pixel.Value.A == 0)
                     clipRequested = true;
                     clipRequested = true;
-
             }
             }
+
             return new Tuple<DoubleCords, bool>(
             return new Tuple<DoubleCords, bool>(
                 new DoubleCords(new Coordinates(minX, minY), new Coordinates(maxX, maxY)), clipRequested);
                 new DoubleCords(new Coordinates(minX, minY), new Coordinates(maxX, maxY)), clipRequested);
         }
         }
@@ -336,10 +321,10 @@ namespace PixiEditor.Models.Layers
 
 
         private void ClipIfNecessary()
         private void ClipIfNecessary()
         {
         {
-            if (_clipRequested)
+            if (clipRequested)
             {
             {
                 ClipCanvas();
                 ClipCanvas();
-                _clipRequested = false;
+                clipRequested = false;
             }
             }
         }
         }
 
 
@@ -349,17 +334,17 @@ namespace PixiEditor.Models.Layers
         public void ClipCanvas()
         public void ClipCanvas()
         {
         {
             var points = GetEdgePoints();
             var points = GetEdgePoints();
-            int smallestX = points.Coords1.X;
-            int smallestY = points.Coords1.Y;
-            int biggestX = points.Coords2.X;
-            int biggestY = points.Coords2.Y;
+            var smallestX = points.Coords1.X;
+            var smallestY = points.Coords1.Y;
+            var biggestX = points.Coords2.X;
+            var biggestY = points.Coords2.Y;
 
 
             if (smallestX < 0 && smallestY < 0 && biggestX < 0 && biggestY < 0)
             if (smallestX < 0 && smallestY < 0 && biggestX < 0 && biggestY < 0)
                 return;
                 return;
 
 
-            int width = biggestX - smallestX + 1;
-            int height = biggestY - smallestY + 1;
-            ResizeCanvas(0,0, smallestX, smallestY, width, height);
+            var width = biggestX - smallestX + 1;
+            var height = biggestY - smallestY + 1;
+            ResizeCanvas(0, 0, smallestX, smallestY, width, height);
             Offset = new Thickness(OffsetX + smallestX, OffsetY + smallestY, 0, 0);
             Offset = new Thickness(OffsetX + smallestX, OffsetY + smallestY, 0, 0);
         }
         }
 
 
@@ -380,19 +365,19 @@ namespace PixiEditor.Models.Layers
             Offset = new Thickness(Math.Clamp(OffsetX + newMinX, 0, MaxWidth),
             Offset = new Thickness(Math.Clamp(OffsetX + newMinX, 0, MaxWidth),
                 Math.Clamp(OffsetY + newMinY, 0, MaxHeight), 0, 0);
                 Math.Clamp(OffsetY + newMinY, 0, MaxHeight), 0, 0);
 
 
-            int newWidth = Math.Clamp(Width - newMinX, 0, MaxWidth);
-            int newHeight = Math.Clamp(Height - newMinY, 0, MaxHeight);
+            var newWidth = Math.Clamp(Width - newMinX, 0, MaxWidth);
+            var newHeight = Math.Clamp(Height - newMinY, 0, MaxHeight);
 
 
-            int offsetX = Math.Abs(newWidth - Width);
-            int offsetY = Math.Abs(newHeight - Height);
+            var offsetX = Math.Abs(newWidth - Width);
+            var offsetY = Math.Abs(newHeight - Height);
 
 
             ResizeCanvas(offsetX, offsetY, 0, 0, newWidth, newHeight);
             ResizeCanvas(offsetX, offsetY, 0, 0, newWidth, newHeight);
         }
         }
 
 
         private DoubleCords GetEdgePoints()
         private DoubleCords GetEdgePoints()
         {
         {
-            Coordinates smallestPixel = CoordinatesCalculator.FindMinEdgeNonTransparentPixel(LayerBitmap);
-            Coordinates biggestPixel = CoordinatesCalculator.FindMostEdgeNonTransparentPixel(LayerBitmap);
+            var smallestPixel = CoordinatesCalculator.FindMinEdgeNonTransparentPixel(LayerBitmap);
+            var biggestPixel = CoordinatesCalculator.FindMostEdgeNonTransparentPixel(LayerBitmap);
 
 
             return new DoubleCords(smallestPixel, biggestPixel);
             return new DoubleCords(smallestPixel, biggestPixel);
         }
         }
@@ -401,9 +386,9 @@ namespace PixiEditor.Models.Layers
         {
         {
             if (Width == 0 || Height == 0)
             if (Width == 0 || Height == 0)
             {
             {
-                int offsetX = pixels.ChangedPixels.Min(x => x.Key.X);
-                int offsetY = pixels.ChangedPixels.Min(x => x.Key.Y);
-                Offset = new Thickness(offsetX, offsetY, 0,0);
+                var offsetX = pixels.ChangedPixels.Min(x => x.Key.X);
+                var offsetY = pixels.ChangedPixels.Min(x => x.Key.Y);
+                Offset = new Thickness(offsetX, offsetY, 0, 0);
             }
             }
         }
         }
 
 
@@ -422,7 +407,7 @@ namespace PixiEditor.Models.Layers
         public byte[] ConvertBitmapToBytes()
         public byte[] ConvertBitmapToBytes()
         {
         {
             LayerBitmap.Lock();
             LayerBitmap.Lock();
-            byte[] byteArray = LayerBitmap.ToByteArray();
+            var byteArray = LayerBitmap.ToByteArray();
             LayerBitmap.Unlock();
             LayerBitmap.Unlock();
             return byteArray;
             return byteArray;
         }
         }
@@ -438,15 +423,15 @@ namespace PixiEditor.Models.Layers
         /// <param name="newHeight"></param>
         /// <param name="newHeight"></param>
         private void ResizeCanvas(int offsetX, int offsetY, int offsetXSrc, int offsetYSrc, int newWidth, int newHeight)
         private void ResizeCanvas(int offsetX, int offsetY, int offsetXSrc, int offsetYSrc, int newWidth, int newHeight)
         {
         {
-            int iteratorHeight = Height > newHeight ? newHeight : Height;
-            int count = Width > newWidth ? newWidth : Width;
+            var iteratorHeight = Height > newHeight ? newHeight : Height;
+            var count = Width > newWidth ? newWidth : Width;
 
 
             using (var srcContext = LayerBitmap.GetBitmapContext(ReadWriteMode.ReadOnly))
             using (var srcContext = LayerBitmap.GetBitmapContext(ReadWriteMode.ReadOnly))
             {
             {
                 var result = BitmapFactory.New(newWidth, newHeight);
                 var result = BitmapFactory.New(newWidth, newHeight);
                 using (var destContext = result.GetBitmapContext())
                 using (var destContext = result.GetBitmapContext())
                 {
                 {
-                    for (int line = 0; line < iteratorHeight; line++)
+                    for (var line = 0; line < iteratorHeight; line++)
                     {
                     {
                         var srcOff = ((offsetYSrc + line) * Width + offsetXSrc) * SizeOfArgb;
                         var srcOff = ((offsetYSrc + line) * Width + offsetXSrc) * SizeOfArgb;
                         var dstOff = ((offsetY + line) * newWidth + offsetX) * SizeOfArgb;
                         var dstOff = ((offsetY + line) * newWidth + offsetX) * SizeOfArgb;

+ 16 - 15
PixiEditor/Models/Layers/SerializableLayer.cs

@@ -6,17 +6,6 @@ namespace PixiEditor.Models.Layers
     [Serializable]
     [Serializable]
     public class SerializableLayer
     public class SerializableLayer
     {
     {
-        public string Name { get; set; }
-        public int Width { get; set; }
-        public int Height { get; set; }
-        public int MaxWidth { get; set; }
-        public int MaxHeight { get; set; }
-        public byte[] BitmapBytes { get; set; }
-        public bool IsVisible { get; set; }
-        public int OffsetX { get; set; }
-        public int OffsetY { get; set; }
-        public float Opacity { get; set; }
-
         public SerializableLayer(Layer layer)
         public SerializableLayer(Layer layer)
         {
         {
             Name = layer.Name;
             Name = layer.Name;
@@ -24,25 +13,37 @@ namespace PixiEditor.Models.Layers
             Height = layer.Height;
             Height = layer.Height;
             BitmapBytes = layer.ConvertBitmapToBytes();
             BitmapBytes = layer.ConvertBitmapToBytes();
             IsVisible = layer.IsVisible;
             IsVisible = layer.IsVisible;
-            OffsetX = (int)layer.Offset.Left;
-            OffsetY = (int)layer.Offset.Top;
+            OffsetX = (int) layer.Offset.Left;
+            OffsetY = (int) layer.Offset.Top;
             Opacity = layer.Opacity;
             Opacity = layer.Opacity;
             MaxWidth = layer.MaxWidth;
             MaxWidth = layer.MaxWidth;
             MaxHeight = layer.MaxHeight;
             MaxHeight = layer.MaxHeight;
         }
         }
 
 
+        public string Name { get; set; }
+        public int Width { get; set; }
+        public int Height { get; set; }
+        public int MaxWidth { get; set; }
+        public int MaxHeight { get; set; }
+        public byte[] BitmapBytes { get; set; }
+        public bool IsVisible { get; set; }
+        public int OffsetX { get; set; }
+        public int OffsetY { get; set; }
+        public float Opacity { get; set; }
+
         public override bool Equals(object? obj)
         public override bool Equals(object? obj)
         {
         {
             if (obj == null || obj.GetType() != typeof(SerializableLayer)) return false;
             if (obj == null || obj.GetType() != typeof(SerializableLayer)) return false;
 
 
-            SerializableLayer layer = (SerializableLayer) obj;
+            var layer = (SerializableLayer) obj;
 
 
             return Equals(layer);
             return Equals(layer);
         }
         }
 
 
         protected bool Equals(SerializableLayer other)
         protected bool Equals(SerializableLayer other)
         {
         {
-            return Name == other.Name && Width == other.Width && Height == other.Height && MaxWidth == other.MaxWidth && MaxHeight == other.MaxHeight && BitmapBytes.SequenceEqual(other.BitmapBytes) && IsVisible == other.IsVisible && OffsetX == other.OffsetX && OffsetY == other.OffsetY && Opacity.Equals(other.Opacity);
+            return Name == other.Name && Width == other.Width && Height == other.Height && MaxWidth == other.MaxWidth && MaxHeight == other.MaxHeight &&
+                   BitmapBytes.SequenceEqual(other.BitmapBytes) && IsVisible == other.IsVisible && OffsetX == other.OffsetX && OffsetY == other.OffsetY && Opacity.Equals(other.Opacity);
         }
         }
 
 
         public override int GetHashCode()
         public override int GetHashCode()

+ 1 - 4
PixiEditor/Models/Position/Coordinates.cs

@@ -31,10 +31,7 @@ namespace PixiEditor.Models.Position
 
 
         public override bool Equals(object obj)
         public override bool Equals(object obj)
         {
         {
-            if (obj is Coordinates coords)
-            {
-                return this == coords;
-            }
+            if (obj is Coordinates coords) return this == coords;
 
 
             return false;
             return false;
         }
         }

+ 17 - 19
PixiEditor/Models/Position/CoordinatesCalculator.cs

@@ -2,8 +2,6 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Windows.Media;
 using System.Windows.Media;
 using System.Windows.Media.Imaging;
 using System.Windows.Media.Imaging;
-using PixiEditor.Models.DataHolders;
-using PixiEditor.Models.Layers;
 
 
 namespace PixiEditor.Models.Position
 namespace PixiEditor.Models.Position
 {
 {
@@ -38,8 +36,8 @@ namespace PixiEditor.Models.Position
 
 
         public static Coordinates GetCenterPoint(Coordinates startingPoint, Coordinates endPoint)
         public static Coordinates GetCenterPoint(Coordinates startingPoint, Coordinates endPoint)
         {
         {
-            int x = (int) Math.Floor((startingPoint.X + endPoint.X) / 2f);
-            int y = (int) Math.Floor((startingPoint.Y + endPoint.Y) / 2f);
+            var x = (int) Math.Floor((startingPoint.X + endPoint.X) / 2f);
+            var y = (int) Math.Floor((startingPoint.Y + endPoint.Y) / 2f);
             return new Coordinates(x, y);
             return new Coordinates(x, y);
         }
         }
 
 
@@ -55,9 +53,9 @@ namespace PixiEditor.Models.Position
         {
         {
             x2++;
             x2++;
             y2++;
             y2++;
-            List<Coordinates> coordinates = new List<Coordinates>();
-            for (int y = y1; y < y1 + (y2 - y1); y++)
-            for (int x = x1; x < x1 + (x2 - x1); x++)
+            var coordinates = new List<Coordinates>();
+            for (var y = y1; y < y1 + (y2 - y1); y++)
+            for (var x = x1; x < x1 + (x2 - x1); x++)
                 coordinates.Add(new Coordinates(x, y));
                 coordinates.Add(new Coordinates(x, y));
             return coordinates.ToArray();
             return coordinates.ToArray();
         }
         }
@@ -91,10 +89,10 @@ namespace PixiEditor.Models.Position
 
 
         public static int FindMinYNonTransparent(WriteableBitmap bitmap)
         public static int FindMinYNonTransparent(WriteableBitmap bitmap)
         {
         {
-            Color transparent = Color.FromArgb(0, 0, 0, 0);
+            var transparent = Color.FromArgb(0, 0, 0, 0);
             using var ctx = bitmap.GetBitmapContext(ReadWriteMode.ReadOnly);
             using var ctx = bitmap.GetBitmapContext(ReadWriteMode.ReadOnly);
-            for (int y = 0; y < ctx.Height; y++)
-            for (int x = 0; x < ctx.Width; x++)
+            for (var y = 0; y < ctx.Height; y++)
+            for (var x = 0; x < ctx.Width; x++)
                 if (ctx.WriteableBitmap.GetPixel(x, y) != transparent)
                 if (ctx.WriteableBitmap.GetPixel(x, y) != transparent)
                     return y;
                     return y;
 
 
@@ -103,10 +101,10 @@ namespace PixiEditor.Models.Position
 
 
         public static int FindMinXNonTransparent(WriteableBitmap bitmap)
         public static int FindMinXNonTransparent(WriteableBitmap bitmap)
         {
         {
-            Color transparent = Color.FromArgb(0, 0, 0, 0);
+            var transparent = Color.FromArgb(0, 0, 0, 0);
             using var ctx = bitmap.GetBitmapContext(ReadWriteMode.ReadOnly);
             using var ctx = bitmap.GetBitmapContext(ReadWriteMode.ReadOnly);
-            for (int x = 0; x < ctx.Width; x++)
-            for (int y = 0; y < ctx.Height; y++)
+            for (var x = 0; x < ctx.Width; x++)
+            for (var y = 0; y < ctx.Height; y++)
                 if (bitmap.GetPixel(x, y) != transparent)
                 if (bitmap.GetPixel(x, y) != transparent)
                     return x;
                     return x;
 
 
@@ -115,10 +113,10 @@ namespace PixiEditor.Models.Position
 
 
         public static int FindMaxYNonTransparent(WriteableBitmap bitmap)
         public static int FindMaxYNonTransparent(WriteableBitmap bitmap)
         {
         {
-            Color transparent = Color.FromArgb(0, 0, 0, 0);
+            var transparent = Color.FromArgb(0, 0, 0, 0);
             bitmap.Lock();
             bitmap.Lock();
-            for (int y = (int) bitmap.Height - 1; y >= 0; y--)
-            for (int x = (int) bitmap.Width - 1; x >= 0; x--)
+            for (var y = (int) bitmap.Height - 1; y >= 0; y--)
+            for (var x = (int) bitmap.Width - 1; x >= 0; x--)
                 if (bitmap.GetPixel(x, y) != transparent)
                 if (bitmap.GetPixel(x, y) != transparent)
                 {
                 {
                     bitmap.Unlock();
                     bitmap.Unlock();
@@ -131,10 +129,10 @@ namespace PixiEditor.Models.Position
 
 
         public static int FindMaxXNonTransparent(WriteableBitmap bitmap)
         public static int FindMaxXNonTransparent(WriteableBitmap bitmap)
         {
         {
-            Color transparent = Color.FromArgb(0, 0, 0, 0);
+            var transparent = Color.FromArgb(0, 0, 0, 0);
             bitmap.Lock();
             bitmap.Lock();
-            for (int x = (int) bitmap.Width - 1; x >= 0; x--)
-            for (int y = (int) bitmap.Height - 1; y >= 0; y--)
+            for (var x = (int) bitmap.Width - 1; x >= 0; x--)
+            for (var y = (int) bitmap.Height - 1; y >= 0; y--)
                 if (bitmap.GetPixel(x, y) != transparent)
                 if (bitmap.GetPixel(x, y) != transparent)
                 {
                 {
                     bitmap.Unlock();
                     bitmap.Unlock();

+ 5 - 7
PixiEditor/Models/Position/MousePositionConverter.cs

@@ -1,7 +1,5 @@
-using System.Runtime.InteropServices;
-using System.Windows;
-using PixiEditor.Models.DataHolders;
-using PixiEditor.Models.Layers;
+using System.Drawing;
+using System.Runtime.InteropServices;
 
 
 namespace PixiEditor.Models.Position
 namespace PixiEditor.Models.Position
 {
 {
@@ -10,11 +8,11 @@ namespace PixiEditor.Models.Position
         public static Coordinates CurrentCoordinates { get; set; }
         public static Coordinates CurrentCoordinates { get; set; }
 
 
         [DllImport("user32.dll")]
         [DllImport("user32.dll")]
-        private static extern bool GetCursorPos(out System.Drawing.Point point);
+        private static extern bool GetCursorPos(out Point point);
 
 
-        public static System.Drawing.Point GetCursorPosition()
+        public static Point GetCursorPosition()
         {
         {
-            System.Drawing.Point point;
+            Point point;
             GetCursorPos(out point);
             GetCursorPos(out point);
             return point;
             return point;
         }
         }

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

@@ -13,12 +13,12 @@ namespace PixiEditor.Models.Tools
 
 
         protected LayerChange[] Only(BitmapPixelChanges changes, Layer layer)
         protected LayerChange[] Only(BitmapPixelChanges changes, Layer layer)
         {
         {
-            return new[] { new LayerChange(changes, layer) };
+            return new[] {new LayerChange(changes, layer)};
         }
         }
 
 
         protected LayerChange[] Only(BitmapPixelChanges changes, int layerIndex)
         protected LayerChange[] Only(BitmapPixelChanges changes, int layerIndex)
         {
         {
-            return new[] { new LayerChange(changes, layerIndex) };
+            return new[] {new LayerChange(changes, layerIndex)};
         }
         }
     }
     }
 }
 }

+ 5 - 6
PixiEditor/Models/Tools/ShapeTool.cs

@@ -5,15 +5,12 @@ using System.Windows.Media;
 using PixiEditor.Models.DataHolders;
 using PixiEditor.Models.DataHolders;
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Layers;
 using PixiEditor.Models.Position;
 using PixiEditor.Models.Position;
-using PixiEditor.Models.Tools.ToolSettings;
 using PixiEditor.Models.Tools.ToolSettings.Toolbars;
 using PixiEditor.Models.Tools.ToolSettings.Toolbars;
 
 
 namespace PixiEditor.Models.Tools
 namespace PixiEditor.Models.Tools
 {
 {
     public abstract class ShapeTool : BitmapOperationTool
     public abstract class ShapeTool : BitmapOperationTool
     {
     {
-        public abstract override ToolType ToolType { get; }
-
         public ShapeTool()
         public ShapeTool()
         {
         {
             RequiresPreviewLayer = true;
             RequiresPreviewLayer = true;
@@ -21,12 +18,14 @@ namespace PixiEditor.Models.Tools
             Toolbar = new BasicShapeToolbar();
             Toolbar = new BasicShapeToolbar();
         }
         }
 
 
+        public abstract override ToolType ToolType { get; }
+
         public abstract override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color);
         public abstract override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color);
 
 
         protected IEnumerable<Coordinates> GetThickShape(IEnumerable<Coordinates> shape, int thickness)
         protected IEnumerable<Coordinates> GetThickShape(IEnumerable<Coordinates> shape, int thickness)
         {
         {
-            List<Coordinates> output = new List<Coordinates>();
-            foreach(var item in shape)
+            var output = new List<Coordinates>();
+            foreach (var item in shape)
                 output.AddRange(
                 output.AddRange(
                     CoordinatesCalculator.RectangleToCoordinates(
                     CoordinatesCalculator.RectangleToCoordinates(
                         CoordinatesCalculator.CalculateThicknessCenter(item, thickness)));
                         CoordinatesCalculator.CalculateThicknessCenter(item, thickness)));
@@ -37,7 +36,7 @@ namespace PixiEditor.Models.Tools
         protected DoubleCords CalculateCoordinatesForShapeRotation(Coordinates startingCords,
         protected DoubleCords CalculateCoordinatesForShapeRotation(Coordinates startingCords,
             Coordinates secondCoordinates)
             Coordinates secondCoordinates)
         {
         {
-            Coordinates currentCoordinates = secondCoordinates;
+            var currentCoordinates = secondCoordinates;
 
 
             if (startingCords.X > currentCoordinates.X && startingCords.Y > currentCoordinates.Y)
             if (startingCords.X > currentCoordinates.X && startingCords.Y > currentCoordinates.Y)
                 return new DoubleCords(new Coordinates(currentCoordinates.X, currentCoordinates.Y),
                 return new DoubleCords(new Coordinates(currentCoordinates.X, currentCoordinates.Y),

+ 15 - 8
PixiEditor/Models/Tools/Tool.cs

@@ -7,6 +7,7 @@ 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";
         public bool HideHighlight { get; set; } = false;
         public bool HideHighlight { get; set; } = false;
@@ -14,10 +15,10 @@ namespace PixiEditor.Models.Tools
 
 
         public bool IsActive
         public bool IsActive
         {
         {
-            get => _isActive;
+            get => isActive;
             set
             set
             {
             {
-                _isActive = value;
+                isActive = value;
                 RaisePropertyChanged("IsActive");
                 RaisePropertyChanged("IsActive");
             }
             }
         }
         }
@@ -25,16 +26,22 @@ namespace PixiEditor.Models.Tools
         public Cursor Cursor { get; set; } = Cursors.Arrow;
         public Cursor Cursor { get; set; } = Cursors.Arrow;
 
 
         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)
+        {
+        }
 
 
-        public virtual void OnMouseUp(MouseEventArgs e) { }
+        public virtual void OnMouseUp(MouseEventArgs e)
+        {
+        }
 
 
-        public virtual void OnMouseMove(MouseEventArgs e) { }
+        public virtual void OnMouseMove(MouseEventArgs e)
+        {
+        }
 
 
-        public virtual void AfterAddedUndo() { }
+        public virtual void AfterAddedUndo()
+        {
+        }
     }
     }
 }
 }

+ 2 - 2
PixiEditor/Models/Tools/ToolSettings/Settings/BoolSetting.cs

@@ -23,13 +23,13 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
 
 
         private Control GenerateCheckBox()
         private Control GenerateCheckBox()
         {
         {
-            CheckBox checkBox = new CheckBox
+            var checkBox = new CheckBox
             {
             {
                 IsChecked = Value,
                 IsChecked = Value,
                 VerticalAlignment = VerticalAlignment.Center
                 VerticalAlignment = VerticalAlignment.Center
             };
             };
 
 
-            Binding binding = new Binding("Value")
+            var binding = new Binding("Value")
             {
             {
                 Mode = BindingMode.TwoWay
                 Mode = BindingMode.TwoWay
             };
             };

+ 2 - 2
PixiEditor/Models/Tools/ToolSettings/Settings/ColorSetting.cs

@@ -15,8 +15,8 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
 
 
         private PortableColorPicker GenerateColorPicker()
         private PortableColorPicker GenerateColorPicker()
         {
         {
-            PortableColorPicker picker = new PortableColorPicker();
-            Binding binding = new Binding("Value")
+            var picker = new PortableColorPicker();
+            var binding = new Binding("Value")
             {
             {
                 Mode = BindingMode.TwoWay
                 Mode = BindingMode.TwoWay
             };
             };

+ 6 - 6
PixiEditor/Models/Tools/ToolSettings/Settings/DropdownSetting.cs

@@ -7,8 +7,6 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
 {
 {
     public class DropdownSetting : Setting<object>
     public class DropdownSetting : Setting<object>
     {
     {
-        public string[] Values { get; set; }
-
         public DropdownSetting(string name, string[] values, string label) : base(name)
         public DropdownSetting(string name, string[] values, string label) : base(name)
         {
         {
             Values = values;
             Values = values;
@@ -17,16 +15,18 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
             Label = label;
             Label = label;
         }
         }
 
 
+        public string[] Values { get; set; }
+
 
 
         private ComboBox GenerateDropdown()
         private ComboBox GenerateDropdown()
         {
         {
-            ComboBox combobox = new ComboBox
+            var combobox = new ComboBox
             {
             {
                 VerticalAlignment = VerticalAlignment.Center
                 VerticalAlignment = VerticalAlignment.Center
             };
             };
             GenerateItems(combobox);
             GenerateItems(combobox);
 
 
-            Binding binding = new Binding("Value")
+            var binding = new Binding("Value")
             {
             {
                 Mode = BindingMode.TwoWay
                 Mode = BindingMode.TwoWay
             };
             };
@@ -36,9 +36,9 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
 
 
         private void GenerateItems(ComboBox comboBox)
         private void GenerateItems(ComboBox comboBox)
         {
         {
-            for (int i = 0; i < Values.Length; i++)
+            for (var i = 0; i < Values.Length; i++)
             {
             {
-                ComboBoxItem item = new ComboBoxItem
+                var item = new ComboBoxItem
                 {
                 {
                     Content = Values[i]
                     Content = Values[i]
                 };
                 };

+ 5 - 5
PixiEditor/Models/Tools/ToolSettings/Settings/FloatSetting.cs

@@ -5,9 +5,6 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
 {
 {
     public class FloatSetting : Setting<float>
     public class FloatSetting : Setting<float>
     {
     {
-        public float Min { get; set; }
-        public float Max { get; set; }
-
         public FloatSetting(string name, float initialValue, string label = "",
         public FloatSetting(string name, float initialValue, string label = "",
             float min = float.NegativeInfinity, float max = float.PositiveInfinity) : base(name)
             float min = float.NegativeInfinity, float max = float.PositiveInfinity) : base(name)
         {
         {
@@ -18,16 +15,19 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
             SettingControl = GenerateNumberInput();
             SettingControl = GenerateNumberInput();
         }
         }
 
 
+        public float Min { get; set; }
+        public float Max { get; set; }
+
         private NumberInput GenerateNumberInput()
         private NumberInput GenerateNumberInput()
         {
         {
-            NumberInput numbrInput = new NumberInput
+            var numbrInput = new NumberInput
             {
             {
                 Width = 40,
                 Width = 40,
                 Height = 20,
                 Height = 20,
                 Min = Min,
                 Min = Min,
                 Max = Max
                 Max = Max
             };
             };
-            Binding binding = new Binding("Value")
+            var binding = new Binding("Value")
             {
             {
                 Mode = BindingMode.TwoWay
                 Mode = BindingMode.TwoWay
             };
             };

+ 5 - 5
PixiEditor/Models/Tools/ToolSettings/Settings/Setting.cs

@@ -25,6 +25,11 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
 
 
     public abstract class Setting : NotifyableObject
     public abstract class Setting : NotifyableObject
     {
     {
+        protected Setting(string name)
+        {
+            Name = name;
+        }
+
         public string Name { get; }
         public string Name { get; }
 
 
         public string Label { get; set; }
         public string Label { get; set; }
@@ -32,10 +37,5 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
         public bool HasLabel => !string.IsNullOrEmpty(Label);
         public bool HasLabel => !string.IsNullOrEmpty(Label);
 
 
         public Control SettingControl { get; set; }
         public Control SettingControl { get; set; }
-
-        protected Setting(string name)
-        {
-            Name = name;
-        }
     }
     }
 }
 }

+ 4 - 7
PixiEditor/Models/Tools/ToolSettings/Settings/SizeSetting.cs

@@ -18,7 +18,7 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
 
 
         private TextBox GenerateTextBox()
         private TextBox GenerateTextBox()
         {
         {
-            TextBox tb = new TextBox
+            var tb = new TextBox
             {
             {
                 TextAlignment = TextAlignment.Center,
                 TextAlignment = TextAlignment.Center,
                 MaxLength = 4,
                 MaxLength = 4,
@@ -26,18 +26,15 @@ namespace PixiEditor.Models.Tools.ToolSettings.Settings
                 Height = 20
                 Height = 20
             };
             };
 
 
-            if (Application.Current != null)
-            {
-                tb.Style = (Style)Application.Current.TryFindResource("DarkTextBoxStyle");
-            }
+            if (Application.Current != null) tb.Style = (Style) Application.Current.TryFindResource("DarkTextBoxStyle");
 
 
-            Binding binding = new Binding("Value")
+            var binding = new Binding("Value")
             {
             {
                 Converter = new ToolSizeToIntConverter(),
                 Converter = new ToolSizeToIntConverter(),
                 Mode = BindingMode.TwoWay
                 Mode = BindingMode.TwoWay
             };
             };
             tb.SetBinding(TextBox.TextProperty, binding);
             tb.SetBinding(TextBox.TextProperty, binding);
-            TextBoxFocusBehavior behavor = new TextBoxFocusBehavior
+            var behavor = new TextBoxFocusBehavior
             {
             {
                 FillSize = true
                 FillSize = true
             };
             };

+ 4 - 4
PixiEditor/Models/Tools/ToolSettings/Toolbars/Toolbar.cs

@@ -29,7 +29,7 @@ namespace PixiEditor.Models.Tools.ToolSettings.Toolbars
         public T GetSetting<T>(string name)
         public T GetSetting<T>(string name)
             where T : Setting
             where T : Setting
         {
         {
-            Setting setting =  Settings.FirstOrDefault(currentSetting => string.Equals(currentSetting.Name, name, StringComparison.CurrentCultureIgnoreCase));
+            var setting = Settings.FirstOrDefault(currentSetting => string.Equals(currentSetting.Name, name, StringComparison.CurrentCultureIgnoreCase));
 
 
             if (setting == null || !(setting is T convertedSetting))
             if (setting == null || !(setting is T convertedSetting))
                 return null;
                 return null;
@@ -42,7 +42,7 @@ namespace PixiEditor.Models.Tools.ToolSettings.Toolbars
         /// </summary>
         /// </summary>
         public void SaveToolbarSettings()
         public void SaveToolbarSettings()
         {
         {
-            foreach (Setting setting in Settings)
+            foreach (var setting in Settings)
                 AddSettingToCollection(SharedSettings, setting);
                 AddSettingToCollection(SharedSettings, setting);
         }
         }
 
 
@@ -51,13 +51,13 @@ namespace PixiEditor.Models.Tools.ToolSettings.Toolbars
         /// </summary>
         /// </summary>
         public void LoadSharedSettings()
         public void LoadSharedSettings()
         {
         {
-            foreach (Setting sharedSetting in SharedSettings)
+            foreach (var sharedSetting in SharedSettings)
                 AddSettingToCollection(Settings, sharedSetting);
                 AddSettingToCollection(Settings, sharedSetting);
         }
         }
 
 
         private static void AddSettingToCollection(ICollection<Setting> collection, Setting setting)
         private static void AddSettingToCollection(ICollection<Setting> collection, Setting setting)
         {
         {
-            Setting storedSetting = collection.FirstOrDefault(currentSetting => currentSetting.Name == setting.Name);
+            var storedSetting = collection.FirstOrDefault(currentSetting => currentSetting.Name == setting.Name);
             if (storedSetting != null)
             if (storedSetting != null)
                 collection.Remove(storedSetting);
                 collection.Remove(storedSetting);
 
 

+ 16 - 16
PixiEditor/Models/Tools/Tools/BrightnessTool.cs

@@ -17,10 +17,7 @@ namespace PixiEditor.Models.Tools.Tools
     {
     {
         private const float CorrectionFactor = 5f; //Initial correction factor
         private const float CorrectionFactor = 5f; //Initial correction factor
 
 
-        public override ToolType ToolType => ToolType.Brightness;
-        public BrightnessMode Mode { get; set; } = BrightnessMode.Default;
-
-        private List<Coordinates> _pixelsVisited = new List<Coordinates>();
+        private readonly List<Coordinates> pixelsVisited = new List<Coordinates>();
 
 
         public BrightnessTool()
         public BrightnessTool()
         {
         {
@@ -28,19 +25,22 @@ namespace PixiEditor.Models.Tools.Tools
             Toolbar = new BrightnessToolToolbar(CorrectionFactor);
             Toolbar = new BrightnessToolToolbar(CorrectionFactor);
         }
         }
 
 
+        public override ToolType ToolType => ToolType.Brightness;
+        public BrightnessMode Mode { get; set; } = BrightnessMode.Default;
+
         public override void OnMouseDown(MouseEventArgs e)
         public override void OnMouseDown(MouseEventArgs e)
         {
         {
-            _pixelsVisited.Clear();
+            pixelsVisited.Clear();
         }
         }
 
 
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         {
         {
-            int toolSize = Toolbar.GetSetting<SizeSetting>("ToolSize").Value;
-            float correctionFactor = Toolbar.GetSetting<FloatSetting>("CorrectionFactor").Value;
+            var toolSize = Toolbar.GetSetting<SizeSetting>("ToolSize").Value;
+            var correctionFactor = Toolbar.GetSetting<FloatSetting>("CorrectionFactor").Value;
             Enum.TryParse((Toolbar.GetSetting<DropdownSetting>("Mode")?.Value as ComboBoxItem)?.Content as string, out BrightnessMode mode);
             Enum.TryParse((Toolbar.GetSetting<DropdownSetting>("Mode")?.Value as ComboBoxItem)?.Content as string, out BrightnessMode mode);
             Mode = mode;
             Mode = mode;
 
 
-            LayerChange[] layersChanges = new LayerChange[1];
+            var layersChanges = new LayerChange[1];
             if (Keyboard.IsKeyDown(Key.LeftCtrl))
             if (Keyboard.IsKeyDown(Key.LeftCtrl))
                 layersChanges[0] = new LayerChange(ChangeBrightness(layer, coordinates[0], toolSize, -correctionFactor),
                 layersChanges[0] = new LayerChange(ChangeBrightness(layer, coordinates[0], toolSize, -correctionFactor),
                     layer);
                     layer);
@@ -53,23 +53,23 @@ namespace PixiEditor.Models.Tools.Tools
         public BitmapPixelChanges ChangeBrightness(Layer layer, Coordinates coordinates, int toolSize,
         public BitmapPixelChanges ChangeBrightness(Layer layer, Coordinates coordinates, int toolSize,
             float correctionFactor)
             float correctionFactor)
         {
         {
-            DoubleCords centeredCoords = CoordinatesCalculator.CalculateThicknessCenter(coordinates, toolSize);
-            Coordinates[] rectangleCoordinates = CoordinatesCalculator.RectangleToCoordinates(centeredCoords.Coords1.X,
+            var centeredCoords = CoordinatesCalculator.CalculateThicknessCenter(coordinates, toolSize);
+            var 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>());
+            var changes = new BitmapPixelChanges(new Dictionary<Coordinates, Color>());
 
 
-            for (int i = 0; i < rectangleCoordinates.Length; i++)
+            for (var i = 0; i < rectangleCoordinates.Length; i++)
             {
             {
                 if (Mode == BrightnessMode.Default)
                 if (Mode == BrightnessMode.Default)
                 {
                 {
-                    if(_pixelsVisited.Contains(rectangleCoordinates[i]))
+                    if (pixelsVisited.Contains(rectangleCoordinates[i]))
                         continue;
                         continue;
-                    _pixelsVisited.Add(rectangleCoordinates[i]);
+                    pixelsVisited.Add(rectangleCoordinates[i]);
                 }
                 }
 
 
-                Color pixel = layer.GetPixelWithOffset(rectangleCoordinates[i].X, rectangleCoordinates[i].Y);
-                Color newColor = ExColor.ChangeColorBrightness(Color.FromArgb(pixel.A, pixel.R, pixel.G, pixel.B),
+                var pixel = layer.GetPixelWithOffset(rectangleCoordinates[i].X, rectangleCoordinates[i].Y);
+                var 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);

+ 43 - 45
PixiEditor/Models/Tools/Tools/CircleTool.cs

@@ -12,22 +12,22 @@ namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class CircleTool : ShapeTool
     public class CircleTool : ShapeTool
     {
     {
-        public override ToolType ToolType => ToolType.Circle;
-
         public CircleTool()
         public CircleTool()
         {
         {
             Tooltip = "Draws circle on canvas (C). Hold Shift to draw even circle.";
             Tooltip = "Draws circle on canvas (C). Hold Shift to draw even circle.";
         }
         }
 
 
+        public override ToolType ToolType => ToolType.Circle;
+
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         {
         {
-            int thickness = Toolbar.GetSetting<SizeSetting>("ToolSize").Value;
-            DoubleCords fixedCoordinates = CalculateCoordinatesForShapeRotation(coordinates[^1], coordinates[0]);
-            IEnumerable<Coordinates> outline = CreateEllipse(fixedCoordinates.Coords1, fixedCoordinates.Coords2, thickness);
-            BitmapPixelChanges pixels = BitmapPixelChanges.FromSingleColoredArray(outline, color);
+            var thickness = Toolbar.GetSetting<SizeSetting>("ToolSize").Value;
+            var fixedCoordinates = CalculateCoordinatesForShapeRotation(coordinates[^1], coordinates[0]);
+            var outline = CreateEllipse(fixedCoordinates.Coords1, fixedCoordinates.Coords2, thickness);
+            var pixels = BitmapPixelChanges.FromSingleColoredArray(outline, color);
             if (Toolbar.GetSetting<BoolSetting>("Fill").Value)
             if (Toolbar.GetSetting<BoolSetting>("Fill").Value)
             {
             {
-                Color fillColor = Toolbar.GetSetting<ColorSetting>("FillColor").Value;
+                var fillColor = Toolbar.GetSetting<ColorSetting>("FillColor").Value;
                 pixels.ChangedPixels.AddRangeNewOnly(
                 pixels.ChangedPixels.AddRangeNewOnly(
                     BitmapPixelChanges.FromSingleColoredArray(CalculateFillForEllipse(outline), fillColor)
                     BitmapPixelChanges.FromSingleColoredArray(CalculateFillForEllipse(outline), fillColor)
                         .ChangedPixels);
                         .ChangedPixels);
@@ -47,8 +47,8 @@ namespace PixiEditor.Models.Tools.Tools
         public IEnumerable<Coordinates> CreateEllipse(Coordinates startCoordinates, Coordinates endCoordinates, int thickness,
         public IEnumerable<Coordinates> CreateEllipse(Coordinates startCoordinates, Coordinates endCoordinates, int thickness,
             bool filled)
             bool filled)
         {
         {
-            List<Coordinates> output = new List<Coordinates>();
-            IEnumerable<Coordinates> outline = CreateEllipse(startCoordinates, endCoordinates, thickness);
+            var output = new List<Coordinates>();
+            var outline = CreateEllipse(startCoordinates, endCoordinates, thickness);
             output.AddRange(outline);
             output.AddRange(outline);
             if (filled)
             if (filled)
             {
             {
@@ -58,6 +58,7 @@ namespace PixiEditor.Models.Tools.Tools
 
 
             return output;
             return output;
         }
         }
+
         /// <summary>
         /// <summary>
         ///     Calculates ellipse points for specified coordinates and thickness.
         ///     Calculates ellipse points for specified coordinates and thickness.
         /// </summary>
         /// </summary>
@@ -65,16 +66,15 @@ namespace PixiEditor.Models.Tools.Tools
         /// <param name="endCoordinates">Bottom right coordinate of ellipse</param>
         /// <param name="endCoordinates">Bottom right coordinate of ellipse</param>
         /// <param name="thickness">Thickness of ellipse</param>
         /// <param name="thickness">Thickness of ellipse</param>
         /// <returns>Coordinates for ellipse</returns>
         /// <returns>Coordinates for ellipse</returns>
-        
         public IEnumerable<Coordinates> CreateEllipse(Coordinates startCoordinates, Coordinates endCoordinates, int thickness)
         public IEnumerable<Coordinates> CreateEllipse(Coordinates startCoordinates, Coordinates endCoordinates, int thickness)
         {
         {
-            double radiusX = (endCoordinates.X - startCoordinates.X) / 2.0;
-            double radiusY = (endCoordinates.Y - startCoordinates.Y) / 2.0;
-            double centerX = (startCoordinates.X + endCoordinates.X + 1) / 2.0;
-            double centerY = (startCoordinates.Y + endCoordinates.Y + 1) / 2.0;
+            var radiusX = (endCoordinates.X - startCoordinates.X) / 2.0;
+            var radiusY = (endCoordinates.Y - startCoordinates.Y) / 2.0;
+            var centerX = (startCoordinates.X + endCoordinates.X + 1) / 2.0;
+            var centerY = (startCoordinates.Y + endCoordinates.Y + 1) / 2.0;
 
 
-            List<Coordinates> output = new List<Coordinates>();
-            IEnumerable<Coordinates> ellipse = MidpointEllipse(radiusX, radiusY, centerX, centerY);
+            var output = new List<Coordinates>();
+            var ellipse = MidpointEllipse(radiusX, radiusY, centerX, centerY);
             if (thickness == 1)
             if (thickness == 1)
                 output.AddRange(ellipse);
                 output.AddRange(ellipse);
             else
             else
@@ -90,10 +90,10 @@ namespace PixiEditor.Models.Tools.Tools
             //ellipse formula: halfHeight^2 * x^2 + halfWidth^2 * y^2 - halfHeight^2 * halfWidth^2 = 0
             //ellipse formula: halfHeight^2 * x^2 + halfWidth^2 * y^2 - halfHeight^2 * halfWidth^2 = 0
 
 
             //Make sure we are always at the center of a pixel
             //Make sure we are always at the center of a pixel
-            double currentX = Math.Ceiling(centerX - 0.5) + 0.5;
-            double currentY = centerY + halfHeight;
+            var currentX = Math.Ceiling(centerX - 0.5) + 0.5;
+            var currentY = centerY + halfHeight;
 
 
-            List<Coordinates> outputCoordinates = new List<Coordinates>();
+            var outputCoordinates = new List<Coordinates>();
 
 
             double currentSlope;
             double currentSlope;
 
 
@@ -108,15 +108,12 @@ namespace PixiEditor.Models.Tools.Tools
                 if (Math.Pow(halfHeight, 2) * Math.Pow(currentX - centerX, 2) +
                 if (Math.Pow(halfHeight, 2) * Math.Pow(currentX - centerX, 2) +
                     Math.Pow(halfWidth, 2) * Math.Pow(currentY - centerY - 0.5, 2) -
                     Math.Pow(halfWidth, 2) * Math.Pow(currentY - centerY - 0.5, 2) -
                     Math.Pow(halfWidth, 2) * Math.Pow(halfHeight, 2) >= 0)
                     Math.Pow(halfWidth, 2) * Math.Pow(halfHeight, 2) >= 0)
-                {
                     currentY--;
                     currentY--;
-                }
 
 
                 //calculate how far we've advanced
                 //calculate how far we've advanced
-                double derivativeX = 2 * Math.Pow(halfHeight, 2) * (currentX - centerX);
-                double derivativeY = 2 * Math.Pow(halfWidth, 2) * (currentY - centerY);
+                var derivativeX = 2 * Math.Pow(halfHeight, 2) * (currentX - centerX);
+                var derivativeY = 2 * Math.Pow(halfWidth, 2) * (currentY - centerY);
                 currentSlope = -(derivativeX / derivativeY);
                 currentSlope = -(derivativeX / derivativeY);
-
             } while (currentSlope > -1 && currentY - centerY > 0.5);
             } while (currentSlope > -1 && currentY - centerY > 0.5);
 
 
             //from middle to 0
             //from middle to 0
@@ -128,9 +125,7 @@ namespace PixiEditor.Models.Tools.Tools
                 if (Math.Pow(halfHeight, 2) * Math.Pow(currentX - centerX + 0.5, 2) +
                 if (Math.Pow(halfHeight, 2) * Math.Pow(currentX - centerX + 0.5, 2) +
                     Math.Pow(halfWidth, 2) * Math.Pow(currentY - centerY, 2) -
                     Math.Pow(halfWidth, 2) * Math.Pow(currentY - centerY, 2) -
                     Math.Pow(halfWidth, 2) * Math.Pow(halfHeight, 2) < 0)
                     Math.Pow(halfWidth, 2) * Math.Pow(halfHeight, 2) < 0)
-                {
                     currentX++;
                     currentX++;
-                }
             }
             }
 
 
             return outputCoordinates;
             return outputCoordinates;
@@ -138,42 +133,45 @@ namespace PixiEditor.Models.Tools.Tools
 
 
         private Coordinates[] FallbackRectangle(double halfWidth, double halfHeight, double centerX, double centerY)
         private Coordinates[] FallbackRectangle(double halfWidth, double halfHeight, double centerX, double centerY)
         {
         {
-            List<Coordinates> coordinates = new List<Coordinates>();
-            for (double x = centerX - halfWidth; x <= centerX + halfWidth; x++)
+            var coordinates = new List<Coordinates>();
+            for (var x = centerX - halfWidth; x <= centerX + halfWidth; x++)
             {
             {
-                coordinates.Add(new Coordinates((int)x, (int)(centerY - halfHeight)));
-                coordinates.Add(new Coordinates((int)x, (int)(centerY + halfHeight)));
+                coordinates.Add(new Coordinates((int) x, (int) (centerY - halfHeight)));
+                coordinates.Add(new Coordinates((int) x, (int) (centerY + halfHeight)));
             }
             }
-            for (double y = centerY - halfHeight + 1; y <= centerY + halfHeight - 1; y++)
+
+            for (var y = centerY - halfHeight + 1; y <= centerY + halfHeight - 1; y++)
             {
             {
-                coordinates.Add(new Coordinates((int)(centerX - halfWidth), (int)y));
-                coordinates.Add(new Coordinates((int)(centerX + halfWidth), (int)y));
+                coordinates.Add(new Coordinates((int) (centerX - halfWidth), (int) y));
+                coordinates.Add(new Coordinates((int) (centerX + halfWidth), (int) y));
             }
             }
+
             return coordinates.ToArray();
             return coordinates.ToArray();
         }
         }
 
 
         private IEnumerable<Coordinates> CalculateFillForEllipse(IEnumerable<Coordinates> outlineCoordinates)
         private IEnumerable<Coordinates> CalculateFillForEllipse(IEnumerable<Coordinates> outlineCoordinates)
         {
         {
-            List<Coordinates> finalCoordinates = new List<Coordinates>();
-            int bottom = outlineCoordinates.Max(x => x.Y);
-            int top = outlineCoordinates.Min(x => x.Y);
-            for (int i = top + 1; i < bottom; i++)
+            var finalCoordinates = new List<Coordinates>();
+            var bottom = outlineCoordinates.Max(x => x.Y);
+            var top = outlineCoordinates.Min(x => x.Y);
+            for (var i = top + 1; i < bottom; i++)
             {
             {
                 var rowCords = outlineCoordinates.Where(x => x.Y == i);
                 var rowCords = outlineCoordinates.Where(x => x.Y == i);
-                int right = rowCords.Max(x => x.X);
-                int left = rowCords.Min(x => x.X);
-                for (int j = left + 1; j < right; j++) finalCoordinates.Add(new Coordinates(j, i));
+                var right = rowCords.Max(x => x.X);
+                var left = rowCords.Min(x => x.X);
+                for (var j = left + 1; j < right; j++) finalCoordinates.Add(new Coordinates(j, i));
             }
             }
 
 
             return finalCoordinates;
             return finalCoordinates;
         }
         }
+
         private Coordinates[] GetRegionPoints(double x, double xc, double y, double yc)
         private Coordinates[] GetRegionPoints(double x, double xc, double y, double yc)
         {
         {
-            Coordinates[] outputCoordinates = new Coordinates[4];
-            outputCoordinates[0] = new Coordinates((int)Math.Floor(x),                  (int)Math.Floor(y));
-            outputCoordinates[1] = new Coordinates((int)Math.Floor((-(x - xc) + xc)),   (int)Math.Floor(y));
-            outputCoordinates[2] = new Coordinates((int)Math.Floor(x),                  (int)Math.Floor((-(y - yc) + yc)));
-            outputCoordinates[3] = new Coordinates((int)Math.Floor((-(x - xc) + xc)),   (int)Math.Floor((-(y - yc) + yc)));
+            var outputCoordinates = new Coordinates[4];
+            outputCoordinates[0] = new Coordinates((int) Math.Floor(x), (int) Math.Floor(y));
+            outputCoordinates[1] = new Coordinates((int) Math.Floor(-(x - xc) + xc), (int) Math.Floor(y));
+            outputCoordinates[2] = new Coordinates((int) Math.Floor(x), (int) Math.Floor(-(y - yc) + yc));
+            outputCoordinates[3] = new Coordinates((int) Math.Floor(-(x - xc) + xc), (int) Math.Floor(-(y - yc) + yc));
             return outputCoordinates;
             return outputCoordinates;
         }
         }
     }
     }

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

@@ -7,14 +7,14 @@ namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class ColorPickerTool : ReadonlyTool
     public class ColorPickerTool : ReadonlyTool
     {
     {
-        public override ToolType ToolType => ToolType.ColorPicker;
-
         public ColorPickerTool()
         public ColorPickerTool()
         {
         {
             HideHighlight = true;
             HideHighlight = true;
             Tooltip = "Swaps primary color with selected on canvas. (O)";
             Tooltip = "Swaps primary color with selected on canvas. (O)";
         }
         }
 
 
+        public override ToolType ToolType => ToolType.ColorPicker;
+
         public override void Use(Coordinates[] coordinates)
         public override void Use(Coordinates[] coordinates)
         {
         {
             ViewModelMain.Current.PrimaryColor = GetColorUnderMouse();
             ViewModelMain.Current.PrimaryColor = GetColorUnderMouse();

+ 4 - 4
PixiEditor/Models/Tools/Tools/EraserTool.cs

@@ -9,14 +9,14 @@ namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class EraserTool : BitmapOperationTool
     public class EraserTool : BitmapOperationTool
     {
     {
-        public override ToolType ToolType => ToolType.Eraser;
-
         public EraserTool()
         public EraserTool()
         {
         {
             Tooltip = "Erasers color from pixel (E)";
             Tooltip = "Erasers color from pixel (E)";
             Toolbar = new BasicToolbar();
             Toolbar = new BasicToolbar();
         }
         }
 
 
+        public override ToolType ToolType => ToolType.Eraser;
+
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         {
         {
             return Erase(layer, coordinates, Toolbar.GetSetting<SizeSetting>("ToolSize").Value);
             return Erase(layer, coordinates, Toolbar.GetSetting<SizeSetting>("ToolSize").Value);
@@ -24,8 +24,8 @@ namespace PixiEditor.Models.Tools.Tools
 
 
         public LayerChange[] Erase(Layer layer, Coordinates[] coordinates, int toolSize)
         public LayerChange[] Erase(Layer layer, Coordinates[] coordinates, int toolSize)
         {
         {
-            Coordinates startingCords = coordinates.Length > 1 ? coordinates[1] : coordinates[0];
-            PenTool pen = new PenTool();
+            var startingCords = coordinates.Length > 1 ? coordinates[1] : coordinates[0];
+            var pen = new PenTool();
             var pixels = pen.Draw(startingCords, coordinates[0], System.Windows.Media.Colors.Transparent, toolSize);
             var pixels = pen.Draw(startingCords, coordinates[0], System.Windows.Media.Colors.Transparent, toolSize);
             return new[] {new LayerChange(pixels, layer)};
             return new[] {new LayerChange(pixels, layer)};
         }
         }

+ 11 - 12
PixiEditor/Models/Tools/Tools/FloodFill.cs

@@ -1,5 +1,4 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
 using System.Windows.Media;
 using System.Windows.Media;
 using System.Windows.Media.Imaging;
 using System.Windows.Media.Imaging;
 using PixiEditor.Models.DataHolders;
 using PixiEditor.Models.DataHolders;
@@ -11,13 +10,13 @@ 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);
@@ -25,18 +24,18 @@ namespace PixiEditor.Models.Tools.Tools
 
 
         public BitmapPixelChanges ForestFire(Layer layer, Coordinates startingCoords, Color newColor)
         public BitmapPixelChanges ForestFire(Layer layer, Coordinates startingCoords, Color newColor)
         {
         {
-            List<Coordinates> changedCoords = new List<Coordinates>();
+            var changedCoords = new List<Coordinates>();
 
 
-            Layer clone = layer.Clone();
-            int width = ViewModelMain.Current.BitmapManager.ActiveDocument.Width;
-            int height = ViewModelMain.Current.BitmapManager.ActiveDocument.Height;
+            var clone = layer.Clone();
+            var width = ViewModelMain.Current.BitmapManager.ActiveDocument.Width;
+            var height = ViewModelMain.Current.BitmapManager.ActiveDocument.Height;
 
 
-            Color colorToReplace = layer.GetPixelWithOffset(startingCoords.X, startingCoords.Y);
+            var colorToReplace = layer.GetPixelWithOffset(startingCoords.X, startingCoords.Y);
 
 
             var stack = new Stack<Coordinates>();
             var stack = new Stack<Coordinates>();
             stack.Push(new Coordinates(startingCoords.X, startingCoords.Y));
             stack.Push(new Coordinates(startingCoords.X, startingCoords.Y));
-            
-            using(clone.LayerBitmap.GetBitmapContext(ReadWriteMode.ReadWrite))
+
+            using (clone.LayerBitmap.GetBitmapContext(ReadWriteMode.ReadWrite))
             {
             {
                 while (stack.Count > 0)
                 while (stack.Count > 0)
                 {
                 {
@@ -57,8 +56,8 @@ namespace PixiEditor.Models.Tools.Tools
                         stack.Push(new Coordinates(cords.X - 1, cords.Y));
                         stack.Push(new Coordinates(cords.X - 1, cords.Y));
                     }
                     }
                 }
                 }
-
             }
             }
+
             return BitmapPixelChanges.FromSingleColoredArray(changedCoords, newColor);
             return BitmapPixelChanges.FromSingleColoredArray(changedCoords, newColor);
         }
         }
     }
     }

+ 12 - 16
PixiEditor/Models/Tools/Tools/LineTool.cs

@@ -12,26 +12,26 @@ namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class LineTool : ShapeTool
     public class LineTool : ShapeTool
     {
     {
-        public override ToolType ToolType => ToolType.Line;
-
         public LineTool()
         public LineTool()
         {
         {
             Tooltip = "Draws line on canvas (L). Hold Shift to draw even line.";
             Tooltip = "Draws line on canvas (L). Hold Shift to draw even line.";
             Toolbar = new BasicToolbar();
             Toolbar = new BasicToolbar();
         }
         }
 
 
+        public override ToolType ToolType => ToolType.Line;
+
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         {
         {
             var pixels =
             var pixels =
                 BitmapPixelChanges.FromSingleColoredArray(
                 BitmapPixelChanges.FromSingleColoredArray(
-                    CreateLine(coordinates, 
+                    CreateLine(coordinates,
                         Toolbar.GetSetting<SizeSetting>("ToolSize").Value, CapType.Square, CapType.Square), color);
                         Toolbar.GetSetting<SizeSetting>("ToolSize").Value, CapType.Square, CapType.Square), color);
             return Only(pixels, layer);
             return Only(pixels, layer);
         }
         }
 
 
         public IEnumerable<Coordinates> CreateLine(Coordinates start, Coordinates end, int thickness)
         public IEnumerable<Coordinates> CreateLine(Coordinates start, Coordinates end, int thickness)
         {
         {
-            return CreateLine(new[] { end, start }, thickness, CapType.Square, CapType.Square);
+            return CreateLine(new[] {end, start}, thickness, CapType.Square, CapType.Square);
         }
         }
 
 
         public IEnumerable<Coordinates> CreateLine(Coordinates start, Coordinates end, int thickness, CapType startCap,
         public IEnumerable<Coordinates> CreateLine(Coordinates start, Coordinates end, int thickness, CapType startCap,
@@ -42,8 +42,8 @@ namespace PixiEditor.Models.Tools.Tools
 
 
         private IEnumerable<Coordinates> CreateLine(Coordinates[] coordinates, int thickness, CapType startCap, CapType endCap)
         private IEnumerable<Coordinates> CreateLine(Coordinates[] coordinates, int thickness, CapType startCap, CapType endCap)
         {
         {
-            Coordinates startingCoordinates = coordinates[^1];
-            Coordinates latestCoordinates = coordinates[0];
+            var startingCoordinates = coordinates[^1];
+            var latestCoordinates = coordinates[0];
             if (thickness == 1)
             if (thickness == 1)
                 return BresenhamLine(startingCoordinates.X, startingCoordinates.Y, latestCoordinates.X,
                 return BresenhamLine(startingCoordinates.X, startingCoordinates.Y, latestCoordinates.X,
                     latestCoordinates.Y);
                     latestCoordinates.Y);
@@ -57,16 +57,12 @@ namespace PixiEditor.Models.Tools.Tools
 
 
             var line = BresenhamLine(start.X, start.Y, end.X, end.Y);
             var line = BresenhamLine(start.X, start.Y, end.X, end.Y);
 
 
-            List<Coordinates> output = new List<Coordinates>(startingCap);
+            var output = new List<Coordinates>(startingCap);
 
 
             output.AddRange(GetCapCoordinates(endCap, end, thickness));
             output.AddRange(GetCapCoordinates(endCap, end, thickness));
-            if (line.Count() > 2)
-            {
-                output.AddRange(GetThickShape(line.Except(new []{start,end}).ToArray(), thickness));
-            }
+            if (line.Count() > 2) output.AddRange(GetThickShape(line.Except(new[] {start, end}).ToArray(), thickness));
 
 
             return output.Distinct();
             return output.Distinct();
-
         }
         }
 
 
         private IEnumerable<Coordinates> GetCapCoordinates(CapType cap, Coordinates position, int thickness)
         private IEnumerable<Coordinates> GetCapCoordinates(CapType cap, Coordinates position, int thickness)
@@ -77,8 +73,8 @@ namespace PixiEditor.Models.Tools.Tools
                 {
                 {
                     return GetRoundCap(position, thickness); // Round cap is not working very well, circle tool must be improved
                     return GetRoundCap(position, thickness); // Round cap is not working very well, circle tool must be improved
                 }
                 }
-                default: 
-                    return GetThickShape(new[] { position }, thickness);
+                default:
+                    return GetThickShape(new[] {position}, thickness);
             }
             }
         }
         }
 
 
@@ -90,7 +86,7 @@ namespace PixiEditor.Models.Tools.Tools
         /// <returns></returns>
         /// <returns></returns>
         private IEnumerable<Coordinates> GetRoundCap(Coordinates position, int thickness)
         private IEnumerable<Coordinates> GetRoundCap(Coordinates position, int thickness)
         {
         {
-            CircleTool circle = new CircleTool();
+            var circle = new CircleTool();
             var rectangleCords = CoordinatesCalculator.RectangleToCoordinates(
             var rectangleCords = CoordinatesCalculator.RectangleToCoordinates(
                 CoordinatesCalculator.CalculateThicknessCenter(position, thickness));
                 CoordinatesCalculator.CalculateThicknessCenter(position, thickness));
             return circle.CreateEllipse(rectangleCords[0], rectangleCords[^1], 1, true);
             return circle.CreateEllipse(rectangleCords[0], rectangleCords[^1], 1, true);
@@ -98,7 +94,7 @@ namespace PixiEditor.Models.Tools.Tools
 
 
         private IEnumerable<Coordinates> BresenhamLine(int x1, int y1, int x2, int y2)
         private IEnumerable<Coordinates> BresenhamLine(int x1, int y1, int x2, int y2)
         {
         {
-            List<Coordinates> coordinates = new List<Coordinates>();
+            var coordinates = new List<Coordinates>();
             if (x1 == x2 && y1 == y2) return new[] {new Coordinates(x1, y1)};
             if (x1 == x2 && y1 == y2) return new[] {new Coordinates(x1, y1)};
 
 
             int d, dx, dy, ai, bi, xi, yi;
             int d, dx, dy, ai, bi, xi, yi;

+ 64 - 77
PixiEditor/Models/Tools/Tools/MoveTool.cs

@@ -18,18 +18,15 @@ 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 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 Layer[] affectedLayers;
+        private Dictionary<Layer, bool> clearedPixels = new Dictionary<Layer, bool>();
+        private Coordinates[] currentSelection;
+        private Coordinates lastMouseMove;
+        private Coordinates lastStartMousePos;
+        private Dictionary<Layer, Thickness> startingOffsets;
+        private Dictionary<Layer, Color[]> startPixelColors;
+        private Coordinates[] startSelection;
+        private bool updateViewModelSelection = true;
 
 
         public MoveTool()
         public MoveTool()
         {
         {
@@ -40,102 +37,92 @@ namespace PixiEditor.Models.Tools.Tools
             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
                 //Inject to default undo system change custom changes made by this tool
-                foreach (var item in _startPixelColors)
+                foreach (var item in startPixelColors)
                 {
                 {
-                    BitmapPixelChanges beforeMovePixels = BitmapPixelChanges.FromArrays(_startSelection, item.Value);
-                    Change changes = UndoManager.UndoStack.Peek();
-                    int layerIndex = ViewModelMain.Current.BitmapManager.ActiveDocument.Layers.IndexOf(item.Key);
+                    var beforeMovePixels = BitmapPixelChanges.FromArrays(startSelection, item.Value);
+                    var changes = UndoManager.UndoStack.Peek();
+                    var layerIndex = ViewModelMain.Current.BitmapManager.ActiveDocument.Layers.IndexOf(item.Key);
 
 
-                    ((LayerChange[]) changes.OldValue).First(x=> x.LayerIndex == layerIndex).PixelChanges.ChangedPixels
+                    ((LayerChange[]) changes.OldValue).First(x => x.LayerIndex == layerIndex).PixelChanges.ChangedPixels
                         .AddRangeOverride(beforeMovePixels.ChangedPixels);
                         .AddRangeOverride(beforeMovePixels.ChangedPixels);
 
 
                     ((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 OnMouseUp(MouseEventArgs e) //This adds undo if there is no selection, reason why this isn't in AfterUndoAdded,
         public override void OnMouseUp(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"));
-            }
+        {
+            //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)
         private void ApplyOffsets(object[] parameters)
         {
         {
-            Dictionary<Layer, Thickness> offsets = (Dictionary<Layer, Thickness>)parameters[0];
-            foreach (var offset in offsets)
-            {
-                offset.Key.Offset = offset.Value;
-            }
+            var offsets = (Dictionary<Layer, Thickness>) parameters[0];
+            foreach (var offset in offsets) offset.Key.Offset = offset.Value;
         }
         }
 
 
         public override LayerChange[] Use(Layer layer, Coordinates[] mouseMove, Color color)
         public override LayerChange[] Use(Layer layer, Coordinates[] mouseMove, Color color)
         {
         {
-            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
+            var 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
             {
             {
                 ResetSelectionValues(start);
                 ResetSelectionValues(start);
                 if (ViewModelMain.Current.ActiveSelection != null && ViewModelMain.Current.ActiveSelection.SelectedPoints.Count > 0) //Move offset if no selection
                 if (ViewModelMain.Current.ActiveSelection != null && ViewModelMain.Current.ActiveSelection.SelectedPoints.Count > 0) //Move offset if no selection
-                {
-                    _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];
+            var result = new LayerChange[affectedLayers.Length];
             var end = mouseMove[0];
             var end = mouseMove[0];
-            for (int i = 0; i < _affectedLayers.Length; i++)
-            {
-                if (_currentSelection.Length > 0)
+            for (var i = 0; i < affectedLayers.Length; i++)
+                if (currentSelection.Length > 0)
                 {
                 {
-                    var changes = MoveSelection(_affectedLayers[i], mouseMove);
+                    var changes = MoveSelection(affectedLayers[i], mouseMove);
                     changes = RemoveTransparentPixels(changes);
                     changes = RemoveTransparentPixels(changes);
 
 
-                    result[i] = new LayerChange(changes, _affectedLayers[i]);
+                    result[i] = new LayerChange(changes, affectedLayers[i]);
                 }
                 }
                 else
                 else
                 {
                 {
-                    var vector = Transform.GetTranslation(_lastMouseMove, end);
-                    _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]);
+                    var vector = Transform.GetTranslation(lastMouseMove, end);
+                    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]);
                 }
                 }
-            }
-            _lastMouseMove = end;
+
+            lastMouseMove = end;
 
 
             return result;
             return result;
         }
         }
 
 
         private Dictionary<Layer, Thickness> GetOffsets(Layer[] layers)
         private Dictionary<Layer, Thickness> GetOffsets(Layer[] layers)
         {
         {
-            Dictionary<Layer, Thickness> dict = new Dictionary<Layer, Thickness>();
-            for (int i = 0; i < layers.Length; i++)
-            {
-                dict.Add(layers[i], layers[i].Offset);
-            }
+            var dict = new Dictionary<Layer, Thickness>();
+            for (var i = 0; i < layers.Length; i++) dict.Add(layers[i], layers[i].Offset);
 
 
             return dict;
             return dict;
         }
         }
@@ -149,43 +136,43 @@ namespace PixiEditor.Models.Tools.Tools
 
 
         public BitmapPixelChanges MoveSelection(Layer layer, Coordinates[] mouseMove)
         public BitmapPixelChanges MoveSelection(Layer layer, Coordinates[] mouseMove)
         {
         {
-            Coordinates end = mouseMove[0];
+            var end = mouseMove[0];
 
 
-            _currentSelection = TranslateSelection(end, out Coordinates[] previousSelection);
-            if (_updateViewModelSelection)
-                ViewModelMain.Current.ActiveSelection.SetSelection(_currentSelection, SelectionType.New);
+            currentSelection = TranslateSelection(end, out var previousSelection);
+            if (updateViewModelSelection)
+                ViewModelMain.Current.ActiveSelection.SetSelection(currentSelection, SelectionType.New);
             ClearSelectedPixels(layer, previousSelection);
             ClearSelectedPixels(layer, previousSelection);
 
 
 
 
-            _lastMouseMove = end;
-            return BitmapPixelChanges.FromArrays(_currentSelection, _startPixelColors[layer]);
+            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();
+            var 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;
             }
             }
         }
         }
     }
     }

+ 7 - 6
PixiEditor/Models/Tools/Tools/PenTool.cs

@@ -10,27 +10,28 @@ namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class PenTool : BitmapOperationTool
     public class PenTool : BitmapOperationTool
     {
     {
-        public override ToolType ToolType => ToolType.Pen;
-        private readonly SizeSetting _toolSizeSetting;
+        private readonly SizeSetting toolSizeSetting;
 
 
         public PenTool()
         public PenTool()
         {
         {
             Cursor = Cursors.Pen;
             Cursor = Cursors.Pen;
             Tooltip = "Standard brush (B)";
             Tooltip = "Standard brush (B)";
             Toolbar = new BasicToolbar();
             Toolbar = new BasicToolbar();
-            _toolSizeSetting = Toolbar.GetSetting<SizeSetting>("ToolSize");
+            toolSizeSetting = Toolbar.GetSetting<SizeSetting>("ToolSize");
         }
         }
 
 
+        public override ToolType ToolType => ToolType.Pen;
+
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         {
         {
-            Coordinates startingCords = coordinates.Length > 1 ? coordinates[1] : coordinates[0];
-            var pixels = Draw(startingCords, coordinates[0], color, _toolSizeSetting.Value);
+            var startingCords = coordinates.Length > 1 ? coordinates[1] : coordinates[0];
+            var pixels = Draw(startingCords, coordinates[0], color, toolSizeSetting.Value);
             return Only(pixels, layer);
             return Only(pixels, layer);
         }
         }
 
 
         public BitmapPixelChanges Draw(Coordinates startingCoords, Coordinates latestCords, Color color, int toolSize)
         public BitmapPixelChanges Draw(Coordinates startingCoords, Coordinates latestCords, Color color, int toolSize)
         {
         {
-            LineTool line = new LineTool();
+            var line = new LineTool();
             return BitmapPixelChanges.FromSingleColoredArray(
             return BitmapPixelChanges.FromSingleColoredArray(
                 line.CreateLine(startingCoords, latestCords, toolSize), color);
                 line.CreateLine(startingCoords, latestCords, toolSize), color);
         }
         }

+ 23 - 23
PixiEditor/Models/Tools/Tools/RectangleTool.cs

@@ -12,22 +12,22 @@ namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class RectangleTool : ShapeTool
     public class RectangleTool : ShapeTool
     {
     {
-        public override ToolType ToolType => ToolType.Rectangle;
-        public bool Filled { get; set; } = false;
-
         public RectangleTool()
         public RectangleTool()
         {
         {
             Tooltip = "Draws rectangle on canvas (R). Hold Shift to draw square.";
             Tooltip = "Draws rectangle on canvas (R). Hold Shift to draw square.";
         }
         }
 
 
+        public override ToolType ToolType => ToolType.Rectangle;
+        public bool Filled { get; set; } = false;
+
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         public override LayerChange[] Use(Layer layer, Coordinates[] coordinates, Color color)
         {
         {
-            int thickness = Toolbar.GetSetting<SizeSetting>("ToolSize").Value;
-            BitmapPixelChanges pixels =
+            var thickness = Toolbar.GetSetting<SizeSetting>("ToolSize").Value;
+            var pixels =
                 BitmapPixelChanges.FromSingleColoredArray(CreateRectangle(coordinates, thickness), color);
                 BitmapPixelChanges.FromSingleColoredArray(CreateRectangle(coordinates, thickness), color);
             if (Toolbar.GetSetting<BoolSetting>("Fill").Value)
             if (Toolbar.GetSetting<BoolSetting>("Fill").Value)
             {
             {
-                Color fillColor = Toolbar.GetSetting<ColorSetting>("FillColor").Value;
+                var fillColor = Toolbar.GetSetting<ColorSetting>("FillColor").Value;
                 pixels.ChangedPixels.AddRangeOverride(
                 pixels.ChangedPixels.AddRangeOverride(
                     BitmapPixelChanges.FromSingleColoredArray
                     BitmapPixelChanges.FromSingleColoredArray
                             (CalculateFillForRectangle(coordinates[^1], coordinates[0], thickness), fillColor)
                             (CalculateFillForRectangle(coordinates[^1], coordinates[0], thickness), fillColor)
@@ -39,16 +39,16 @@ namespace PixiEditor.Models.Tools.Tools
 
 
         public IEnumerable<Coordinates> CreateRectangle(Coordinates[] coordinates, int thickness)
         public IEnumerable<Coordinates> CreateRectangle(Coordinates[] coordinates, int thickness)
         {
         {
-            DoubleCords fixedCoordinates = CalculateCoordinatesForShapeRotation(coordinates[^1], coordinates[0]);
-            List<Coordinates> output = new List<Coordinates>();
-            IEnumerable<Coordinates> rectangle = CalculateRectanglePoints(fixedCoordinates);
+            var fixedCoordinates = CalculateCoordinatesForShapeRotation(coordinates[^1], coordinates[0]);
+            var output = new List<Coordinates>();
+            var rectangle = CalculateRectanglePoints(fixedCoordinates);
             output.AddRange(rectangle);
             output.AddRange(rectangle);
 
 
-            for (int i = 1; i < (int) Math.Floor(thickness / 2f) + 1; i++)
+            for (var i = 1; i < (int) Math.Floor(thickness / 2f) + 1; i++)
                 output.AddRange(CalculateRectanglePoints(new DoubleCords(
                 output.AddRange(CalculateRectanglePoints(new DoubleCords(
                     new Coordinates(fixedCoordinates.Coords1.X - i, fixedCoordinates.Coords1.Y - i),
                     new Coordinates(fixedCoordinates.Coords1.X - i, fixedCoordinates.Coords1.Y - i),
                     new Coordinates(fixedCoordinates.Coords2.X + i, fixedCoordinates.Coords2.Y + i))));
                     new Coordinates(fixedCoordinates.Coords2.X + i, fixedCoordinates.Coords2.Y + i))));
-            for (int i = 1; i < (int) Math.Ceiling(thickness / 2f); i++)
+            for (var i = 1; i < (int) Math.Ceiling(thickness / 2f); i++)
                 output.AddRange(CalculateRectanglePoints(new DoubleCords(
                 output.AddRange(CalculateRectanglePoints(new DoubleCords(
                     new Coordinates(fixedCoordinates.Coords1.X + i, fixedCoordinates.Coords1.Y + i),
                     new Coordinates(fixedCoordinates.Coords1.X + i, fixedCoordinates.Coords1.Y + i),
                     new Coordinates(fixedCoordinates.Coords2.X - i, fixedCoordinates.Coords2.Y - i))));
                     new Coordinates(fixedCoordinates.Coords2.X - i, fixedCoordinates.Coords2.Y - i))));
@@ -63,15 +63,15 @@ namespace PixiEditor.Models.Tools.Tools
 
 
         private IEnumerable<Coordinates> CalculateRectanglePoints(DoubleCords coordinates)
         private IEnumerable<Coordinates> CalculateRectanglePoints(DoubleCords coordinates)
         {
         {
-            List<Coordinates> finalCoordinates = new List<Coordinates>();
+            var finalCoordinates = new List<Coordinates>();
 
 
-            for (int i = coordinates.Coords1.X; i < coordinates.Coords2.X + 1; i++)
+            for (var i = coordinates.Coords1.X; i < coordinates.Coords2.X + 1; i++)
             {
             {
                 finalCoordinates.Add(new Coordinates(i, coordinates.Coords1.Y));
                 finalCoordinates.Add(new Coordinates(i, coordinates.Coords1.Y));
                 finalCoordinates.Add(new Coordinates(i, coordinates.Coords2.Y));
                 finalCoordinates.Add(new Coordinates(i, coordinates.Coords2.Y));
             }
             }
 
 
-            for (int i = coordinates.Coords1.Y + 1; i <= coordinates.Coords2.Y - 1; i++)
+            for (var i = coordinates.Coords1.Y + 1; i <= coordinates.Coords2.Y - 1; i++)
             {
             {
                 finalCoordinates.Add(new Coordinates(coordinates.Coords1.X, i));
                 finalCoordinates.Add(new Coordinates(coordinates.Coords1.X, i));
                 finalCoordinates.Add(new Coordinates(coordinates.Coords2.X, i));
                 finalCoordinates.Add(new Coordinates(coordinates.Coords2.X, i));
@@ -82,23 +82,23 @@ namespace PixiEditor.Models.Tools.Tools
 
 
         public IEnumerable<Coordinates> CalculateFillForRectangle(Coordinates start, Coordinates end, int thickness)
         public IEnumerable<Coordinates> CalculateFillForRectangle(Coordinates start, Coordinates end, int thickness)
         {
         {
-            int offset = (int) Math.Ceiling(thickness / 2f);
-            DoubleCords fixedCords = CalculateCoordinatesForShapeRotation(start, end);
+            var offset = (int) Math.Ceiling(thickness / 2f);
+            var fixedCords = CalculateCoordinatesForShapeRotation(start, end);
 
 
-            DoubleCords innerCords = new DoubleCords
+            var innerCords = new DoubleCords
             {
             {
                 Coords1 = new Coordinates(fixedCords.Coords1.X + offset, fixedCords.Coords1.Y + offset),
                 Coords1 = new Coordinates(fixedCords.Coords1.X + offset, fixedCords.Coords1.Y + offset),
                 Coords2 = new Coordinates(fixedCords.Coords2.X - (offset - 1), fixedCords.Coords2.Y - (offset - 1))
                 Coords2 = new Coordinates(fixedCords.Coords2.X - (offset - 1), fixedCords.Coords2.Y - (offset - 1))
             };
             };
 
 
-            int height = innerCords.Coords2.Y - innerCords.Coords1.Y;
-            int width = innerCords.Coords2.X - innerCords.Coords1.X;
+            var height = innerCords.Coords2.Y - innerCords.Coords1.Y;
+            var width = innerCords.Coords2.X - innerCords.Coords1.X;
 
 
             if (height < 1 || width < 1) return Array.Empty<Coordinates>();
             if (height < 1 || width < 1) return Array.Empty<Coordinates>();
-            Coordinates[] filledCoordinates = new Coordinates[width * height];
-            int i = 0;
-            for (int y = 0; y < height; y++)
-            for (int x = 0; x < width; x++)
+            var filledCoordinates = new Coordinates[width * height];
+            var i = 0;
+            for (var y = 0; y < height; y++)
+            for (var x = 0; x < width; x++)
             {
             {
                 filledCoordinates[i] = new Coordinates(innerCords.Coords1.X + x, innerCords.Coords1.Y + y);
                 filledCoordinates[i] = new Coordinates(innerCords.Coords1.X + x, innerCords.Coords1.Y + y);
                 i++;
                 i++;

+ 9 - 10
PixiEditor/Models/Tools/Tools/SelectTool.cs

@@ -15,8 +15,7 @@ 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 SelectionType SelectionType = SelectionType.Add;
 
 
         public SelectTool()
         public SelectTool()
@@ -25,25 +24,25 @@ namespace PixiEditor.Models.Tools.Tools
             Toolbar = new SelectToolToolbar();
             Toolbar = new SelectToolToolbar();
         }
         }
 
 
+        public override ToolType ToolType => ToolType.Select;
+
         public override void OnMouseDown(MouseEventArgs e)
         public override void OnMouseDown(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);
 
 
-            _oldSelection = null;
+            oldSelection = null;
             if (ViewModelMain.Current.ActiveSelection != null &&
             if (ViewModelMain.Current.ActiveSelection != null &&
                 ViewModelMain.Current.ActiveSelection.SelectedPoints != null)
                 ViewModelMain.Current.ActiveSelection.SelectedPoints != null)
-                _oldSelection = ViewModelMain.Current.ActiveSelection;
+                oldSelection = ViewModelMain.Current.ActiveSelection;
         }
         }
 
 
         public override void OnMouseUp(MouseEventArgs e)
         public override void OnMouseUp(MouseEventArgs e)
         {
         {
             if (ViewModelMain.Current.ActiveSelection.SelectedPoints.Count() <= 1)
             if (ViewModelMain.Current.ActiveSelection.SelectedPoints.Count() <= 1)
-            {
                 // If we have not selected multiple points, clear the selection
                 // If we have not selected multiple points, clear the selection
                 ViewModelMain.Current.ActiveSelection.Clear();
                 ViewModelMain.Current.ActiveSelection.Clear();
-            }
 
 
-            UndoManager.AddUndoChange(new Change("ActiveSelection", _oldSelection,
+            UndoManager.AddUndoChange(new Change("ActiveSelection", oldSelection,
                 ViewModelMain.Current.ActiveSelection, "Select pixels"));
                 ViewModelMain.Current.ActiveSelection, "Select pixels"));
         }
         }
 
 
@@ -54,14 +53,14 @@ namespace PixiEditor.Models.Tools.Tools
 
 
         private void Select(Coordinates[] pixels)
         private void Select(Coordinates[] pixels)
         {
         {
-            IEnumerable<Coordinates> selection = GetRectangleSelectionForPoints(pixels[^1], pixels[0]);
+            var selection = GetRectangleSelectionForPoints(pixels[^1], pixels[0]);
             ViewModelMain.Current.ActiveSelection.SetSelection(selection, SelectionType);
             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();
-            List<Coordinates> selection = rectangleTool.CreateRectangle(start, end, 1).ToList();
+            var rectangleTool = new RectangleTool();
+            var selection = rectangleTool.CreateRectangle(start, end, 1).ToList();
             selection.AddRange(rectangleTool.CalculateFillForRectangle(start, end, 1));
             selection.AddRange(rectangleTool.CalculateFillForRectangle(start, end, 1));
             return selection;
             return selection;
         }
         }

+ 15 - 21
PixiEditor/Models/Tools/Tools/ZoomTool.cs

@@ -1,33 +1,31 @@
-using PixiEditor.Models.Controllers;
-using PixiEditor.Models.Position;
-using PixiEditor.ViewModels;
-using System;
-using System.Collections.Generic;
-using System.Text;
+using System;
 using System.Windows;
 using System.Windows;
 using System.Windows.Input;
 using System.Windows.Input;
+using PixiEditor.Models.Position;
+using PixiEditor.ViewModels;
 
 
 namespace PixiEditor.Models.Tools.Tools
 namespace PixiEditor.Models.Tools.Tools
 {
 {
     public class ZoomTool : ReadonlyTool
     public class ZoomTool : ReadonlyTool
     {
     {
         public const float ZoomSensitivityMultiplier = 30f;
         public const float ZoomSensitivityMultiplier = 30f;
-        public override ToolType ToolType => ToolType.Zoom;
-        private double _startingX;
-        private double _workAreaWidth = SystemParameters.WorkArea.Width;
-        private double _pixelsPerZoomMultiplier;
+        private readonly double pixelsPerZoomMultiplier;
+        private double startingX;
+        private readonly double workAreaWidth = SystemParameters.WorkArea.Width;
 
 
         public ZoomTool()
         public ZoomTool()
         {
         {
             HideHighlight = true;
             HideHighlight = true;
             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 OnMouseDown(MouseEventArgs e)
         public override void OnMouseDown(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
         }
         }
 
 
@@ -37,25 +35,21 @@ 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
+                var rawPercentDifference = (xPos - startingX) / pixelsPerZoomMultiplier; //negative - zoom out, positive - zoom in, linear
+                var finalPercentDifference = Math.Pow(2, rawPercentDifference) * 100.0; //less than 100 - zoom out, greater than 100 - zoom in
                 Zoom(finalPercentDifference);
                 Zoom(finalPercentDifference);
             }
             }
         }
         }
 
 
         public override void OnMouseUp(MouseEventArgs e)
         public override void OnMouseUp(MouseEventArgs e)
         {
         {
-            if (e.LeftButton == MouseButtonState.Released && e.RightButton == MouseButtonState.Released && 
-                _startingX == MousePositionConverter.GetCursorPosition().X)
+            if (e.LeftButton == MouseButtonState.Released && e.RightButton == MouseButtonState.Released &&
+                startingX == MousePositionConverter.GetCursorPosition().X)
             {
             {
                 if (Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
                 if (Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
-                {
                     Zoom(85);
                     Zoom(85);
-                }
                 else
                 else
-                {
                     Zoom(115);
                     Zoom(115);
-                }
             }
             }
         }
         }
 
 
@@ -68,4 +62,4 @@ namespace PixiEditor.Models.Tools.Tools
         {
         {
         }
         }
     }
     }
-}
+}

+ 1 - 2
PixiEditor/Styles/AnchorPointToggleButtonStyle.xaml

@@ -1,6 +1,5 @@
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
-                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-                    xmlns:local="clr-namespace:PixiEditor">
+                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 
 
     <Style x:Key="FocusVisual">
     <Style x:Key="FocusVisual">
         <Setter Property="Control.Template">
         <Setter Property="Control.Template">

+ 0 - 1
PixiEditor/Styles/ComboBoxDarkStyle.xaml

@@ -1,6 +1,5 @@
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-                    xmlns:local="clr-namespace:PixiEditor"
                     xmlns:theme="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero2">
                     xmlns:theme="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero2">
 
 
     <SolidColorBrush x:Key="ComboBox.Static.Background" Color="#333333" />
     <SolidColorBrush x:Key="ComboBox.Static.Background" Color="#333333" />

+ 1 - 4
PixiEditor/Styles/DockingManagerStyle.xaml

@@ -1,9 +1,6 @@
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                     xmlns:xcad="http://schemas.xceed.com/wpf/xaml/avalondock"
                     xmlns:xcad="http://schemas.xceed.com/wpf/xaml/avalondock"
-                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-                    xmlns:avalonDock="clr-namespace:Xceed.Wpf.AvalonDock;assembly=Xceed.Wpf.AvalonDock"
-                    xmlns:avalonDockControls="clr-namespace:Xceed.Wpf.AvalonDock.Controls;assembly=Xceed.Wpf.AvalonDock"
-                    xmlns:avalonDockConverters="clr-namespace:Xceed.Wpf.AvalonDock.Converters;assembly=Xceed.Wpf.AvalonDock">
+                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 
 
     <Style TargetType="xcad:DockingManager">
     <Style TargetType="xcad:DockingManager">
         <Setter Property="Foreground" Value="Snow" />
         <Setter Property="Foreground" Value="Snow" />

+ 1 - 2
PixiEditor/Styles/ThemeColors.xaml

@@ -1,6 +1,5 @@
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
-                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-                    xmlns:local="clr-namespace:PixiEditor.Styles">
+                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 
 
     <SolidColorBrush x:Key="MainColor" Color="#2D2D30" />
     <SolidColorBrush x:Key="MainColor" Color="#2D2D30" />
     <SolidColorBrush x:Key="AccentColor" Color="#252525" />
     <SolidColorBrush x:Key="AccentColor" Color="#252525" />

+ 1 - 1
PixiEditor/Styles/ThemeStyle.xaml

@@ -162,7 +162,7 @@
         </Setter>
         </Setter>
     </Style>
     </Style>
     <Style TargetType="MenuItem">
     <Style TargetType="MenuItem">
-        <Setter Property="Foreground" Value="White"/>
+        <Setter Property="Foreground" Value="White" />
         <Setter Property="OverridesDefaultStyle" Value="True" />
         <Setter Property="OverridesDefaultStyle" Value="True" />
         <Setter Property="Template">
         <Setter Property="Template">
             <Setter.Value>
             <Setter.Value>

+ 8 - 8
PixiEditor/ViewModels/FeedbackDialogViewModel.cs

@@ -5,10 +5,10 @@ namespace PixiEditor.ViewModels
 {
 {
     internal class FeedbackDialogViewModel : ViewModelBase
     internal class FeedbackDialogViewModel : ViewModelBase
     {
     {
-        private string _emailBody;
+        private string emailBody;
 
 
 
 
-        private string _mailFrom;
+        private string mailFrom;
 
 
         public FeedbackDialogViewModel()
         public FeedbackDialogViewModel()
         {
         {
@@ -21,12 +21,12 @@ namespace PixiEditor.ViewModels
 
 
         public string MailFrom
         public string MailFrom
         {
         {
-            get => _mailFrom;
+            get => mailFrom;
             set
             set
             {
             {
-                if (_mailFrom != value)
+                if (mailFrom != value)
                 {
                 {
-                    _mailFrom = value;
+                    mailFrom = value;
                     RaisePropertyChanged("MailFrom");
                     RaisePropertyChanged("MailFrom");
                 }
                 }
             }
             }
@@ -34,12 +34,12 @@ namespace PixiEditor.ViewModels
 
 
         public string EmailBody
         public string EmailBody
         {
         {
-            get => _emailBody;
+            get => emailBody;
             set
             set
             {
             {
-                if (_emailBody != value)
+                if (emailBody != value)
                 {
                 {
-                    _emailBody = value;
+                    emailBody = value;
                     RaisePropertyChanged("EmailBody");
                     RaisePropertyChanged("EmailBody");
                 }
                 }
             }
             }

+ 23 - 23
PixiEditor/ViewModels/ImportFilePopupViewModel.cs

@@ -9,19 +9,19 @@ namespace PixiEditor.ViewModels
 {
 {
     internal class ImportFilePopupViewModel : ViewModelBase
     internal class ImportFilePopupViewModel : ViewModelBase
     {
     {
-        private string _filePath;
+        private string filePath;
 
 
 
 
-        private int _importHeight = 16;
+        private int importHeight = 16;
 
 
 
 
-        private int _importWidth = 16;
+        private int importWidth = 16;
 
 
 
 
-        private string _pathButtonBorder = "#f08080";
+        private string pathButtonBorder = "#f08080";
 
 
 
 
-        private bool _pathIsCorrect;
+        private bool pathIsCorrect;
 
 
         public ImportFilePopupViewModel()
         public ImportFilePopupViewModel()
         {
         {
@@ -38,12 +38,12 @@ namespace PixiEditor.ViewModels
 
 
         public string PathButtonBorder
         public string PathButtonBorder
         {
         {
-            get => _pathButtonBorder;
+            get => pathButtonBorder;
             set
             set
             {
             {
-                if (_pathButtonBorder != value)
+                if (pathButtonBorder != value)
                 {
                 {
-                    _pathButtonBorder = value;
+                    pathButtonBorder = value;
                     RaisePropertyChanged("PathButtonBorder");
                     RaisePropertyChanged("PathButtonBorder");
                 }
                 }
             }
             }
@@ -51,12 +51,12 @@ namespace PixiEditor.ViewModels
 
 
         public bool PathIsCorrect
         public bool PathIsCorrect
         {
         {
-            get => _pathIsCorrect;
+            get => pathIsCorrect;
             set
             set
             {
             {
-                if (_pathIsCorrect != value)
+                if (pathIsCorrect != value)
                 {
                 {
-                    _pathIsCorrect = value;
+                    pathIsCorrect = value;
                     RaisePropertyChanged("PathIsCorrect");
                     RaisePropertyChanged("PathIsCorrect");
                 }
                 }
             }
             }
@@ -64,12 +64,12 @@ namespace PixiEditor.ViewModels
 
 
         public string FilePath
         public string FilePath
         {
         {
-            get => _filePath;
+            get => filePath;
             set
             set
             {
             {
-                if (_filePath != value)
+                if (filePath != value)
                 {
                 {
-                    _filePath = value;
+                    filePath = value;
                     CheckForPath(value);
                     CheckForPath(value);
                     RaisePropertyChanged("FilePath");
                     RaisePropertyChanged("FilePath");
                 }
                 }
@@ -78,12 +78,12 @@ namespace PixiEditor.ViewModels
 
 
         public int ImportWidth
         public int ImportWidth
         {
         {
-            get => _importWidth;
+            get => importWidth;
             set
             set
             {
             {
-                if (_importWidth != value)
+                if (importWidth != value)
                 {
                 {
-                    _importWidth = value;
+                    importWidth = value;
                     RaisePropertyChanged("ImportWidth");
                     RaisePropertyChanged("ImportWidth");
                 }
                 }
             }
             }
@@ -91,12 +91,12 @@ namespace PixiEditor.ViewModels
 
 
         public int ImportHeight
         public int ImportHeight
         {
         {
-            get => _importHeight;
+            get => importHeight;
             set
             set
             {
             {
-                if (_importHeight != value)
+                if (importHeight != value)
                 {
                 {
-                    _importHeight = value;
+                    importHeight = value;
                     RaisePropertyChanged("ImportHeight");
                     RaisePropertyChanged("ImportHeight");
                 }
                 }
             }
             }
@@ -108,7 +108,7 @@ namespace PixiEditor.ViewModels
         /// <param name="parameter"></param>
         /// <param name="parameter"></param>
         private void ChoosePath(object parameter)
         private void ChoosePath(object parameter)
         {
         {
-            OpenFileDialog path = new OpenFileDialog
+            var path = new OpenFileDialog
             {
             {
                 Title = "Import path",
                 Title = "Import path",
                 CheckPathExists = true,
                 CheckPathExists = true,
@@ -134,8 +134,8 @@ namespace PixiEditor.ViewModels
             {
             {
                 PathButtonBorder = "#b8f080";
                 PathButtonBorder = "#b8f080";
                 PathIsCorrect = true;
                 PathIsCorrect = true;
-                _filePath = path;
-                BitmapImage bitmap = new BitmapImage(new Uri(path));
+                filePath = path;
+                var bitmap = new BitmapImage(new Uri(path));
                 ImportHeight = bitmap.PixelHeight;
                 ImportHeight = bitmap.PixelHeight;
                 ImportWidth = bitmap.PixelWidth;
                 ImportWidth = bitmap.PixelWidth;
             }
             }

+ 3 - 3
PixiEditor/ViewModels/MenuButtonViewModel.cs

@@ -5,7 +5,7 @@ namespace PixiEditor.ViewModels
 {
 {
     internal class MenuButtonViewModel : ViewModelBase
     internal class MenuButtonViewModel : ViewModelBase
     {
     {
-        private Visibility _listViewVisibility;
+        private Visibility listViewVisibility;
 
 
 
 
         public MenuButtonViewModel()
         public MenuButtonViewModel()
@@ -20,10 +20,10 @@ namespace PixiEditor.ViewModels
 
 
         public Visibility ListViewVisibility
         public Visibility ListViewVisibility
         {
         {
-            get => _listViewVisibility;
+            get => listViewVisibility;
             set
             set
             {
             {
-                _listViewVisibility = value;
+                listViewVisibility = value;
                 RaisePropertyChanged("ListViewVisibility");
                 RaisePropertyChanged("ListViewVisibility");
             }
             }
         }
         }

+ 13 - 13
PixiEditor/ViewModels/SaveFilePopupViewModel.cs

@@ -6,13 +6,13 @@ namespace PixiEditor.ViewModels
 {
 {
     internal class SaveFilePopupViewModel : ViewModelBase
     internal class SaveFilePopupViewModel : ViewModelBase
     {
     {
-        private string _filePath;
+        private string filePath;
 
 
 
 
-        private string _pathButtonBorder = "#f08080";
+        private string pathButtonBorder = "#f08080";
 
 
 
 
-        private bool _pathIsCorrect;
+        private bool pathIsCorrect;
 
 
         public SaveFilePopupViewModel()
         public SaveFilePopupViewModel()
         {
         {
@@ -29,12 +29,12 @@ namespace PixiEditor.ViewModels
 
 
         public string PathButtonBorder
         public string PathButtonBorder
         {
         {
-            get => _pathButtonBorder;
+            get => pathButtonBorder;
             set
             set
             {
             {
-                if (_pathButtonBorder != value)
+                if (pathButtonBorder != value)
                 {
                 {
-                    _pathButtonBorder = value;
+                    pathButtonBorder = value;
                     RaisePropertyChanged("PathButtonBorder");
                     RaisePropertyChanged("PathButtonBorder");
                 }
                 }
             }
             }
@@ -42,12 +42,12 @@ namespace PixiEditor.ViewModels
 
 
         public bool PathIsCorrect
         public bool PathIsCorrect
         {
         {
-            get => _pathIsCorrect;
+            get => pathIsCorrect;
             set
             set
             {
             {
-                if (_pathIsCorrect != value)
+                if (pathIsCorrect != value)
                 {
                 {
-                    _pathIsCorrect = value;
+                    pathIsCorrect = value;
                     RaisePropertyChanged("PathIsCorrect");
                     RaisePropertyChanged("PathIsCorrect");
                 }
                 }
             }
             }
@@ -55,12 +55,12 @@ namespace PixiEditor.ViewModels
 
 
         public string FilePath
         public string FilePath
         {
         {
-            get => _filePath;
+            get => filePath;
             set
             set
             {
             {
-                if (_filePath != value)
+                if (filePath != value)
                 {
                 {
-                    _filePath = value;
+                    filePath = value;
                     RaisePropertyChanged("FilePath");
                     RaisePropertyChanged("FilePath");
                 }
                 }
             }
             }
@@ -72,7 +72,7 @@ namespace PixiEditor.ViewModels
         /// <param name="parameter"></param>
         /// <param name="parameter"></param>
         private void ChoosePath(object parameter)
         private void ChoosePath(object parameter)
         {
         {
-            SaveFileDialog path = new SaveFileDialog
+            var path = new SaveFileDialog
             {
             {
                 Title = "Export path",
                 Title = "Export path",
                 CheckPathExists = true,
                 CheckPathExists = true,

+ 1 - 1
PixiEditor/ViewModels/ViewModelBase.cs

@@ -21,7 +21,7 @@ namespace PixiEditor.ViewModels
 
 
         protected void DragMove(object parameter)
         protected void DragMove(object parameter)
         {
         {
-            Window popup = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
+            var popup = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
             if (Mouse.LeftButton == MouseButtonState.Pressed) popup.DragMove();
             if (Mouse.LeftButton == MouseButtonState.Pressed) popup.DragMove();
         }
         }
     }
     }

+ 205 - 220
PixiEditor/ViewModels/ViewModelMain.cs

@@ -10,7 +10,6 @@ using System.Threading.Tasks;
 using System.Windows;
 using System.Windows;
 using System.Windows.Input;
 using System.Windows.Input;
 using System.Windows.Media;
 using System.Windows.Media;
-using System.Windows.Media.Imaging;
 using Microsoft.Win32;
 using Microsoft.Win32;
 using PixiEditor.Helpers;
 using PixiEditor.Helpers;
 using PixiEditor.Models.Controllers;
 using PixiEditor.Models.Controllers;
@@ -30,25 +29,139 @@ namespace PixiEditor.ViewModels
     public class ViewModelMain : ViewModelBase
     public class ViewModelMain : ViewModelBase
     {
     {
         private const string ConfirmationDialogMessage = "Document was modified. Do you want to save changes?";
         private const string ConfirmationDialogMessage = "Document was modified. Do you want to save changes?";
+        private Tool lastActionTool;
 
 
-        private Color _primaryColor = Colors.Black;
 
 
-        private bool _recenterZoombox;
+        private double mouseXonCanvas;
 
 
-        private Color _secondaryColor = Colors.White;
+        private double mouseYonCanvas;
 
 
-        private Selection _selection;
+        private Color primaryColor = Colors.Black;
 
 
-        private Cursor _toolCursor;
+        private bool recenterZoombox;
 
 
-        private LayerChange[] _undoChanges;
+        private bool restoreToolOnKeyUp;
 
 
-        private bool _unsavedDocumentModified;
+        private Color secondaryColor = Colors.White;
+
+        private Selection selection;
+
+        private Cursor toolCursor;
+
+        private LayerChange[] undoChanges;
+
+        private bool unsavedDocumentModified;
+
+        private bool updateReadyToInstall;
+
+        private string versionText;
+
+        private double zoomPercentage = 100;
+
+        public ViewModelMain()
+        {
+            BitmapManager = new BitmapManager();
+            BitmapManager.BitmapOperations.BitmapChanged += BitmapUtility_BitmapChanged;
+            BitmapManager.MouseController.StoppedRecordingChanges += MouseController_StoppedRecordingChanges;
+            BitmapManager.DocumentChanged += BitmapManager_DocumentChanged;
+            ChangesController = new PixelChangesController();
+            SelectToolCommand = new RelayCommand(SetTool, DocumentIsNotNull);
+            OpenNewFilePopupCommand = new RelayCommand(OpenNewFilePopup);
+            MouseMoveCommand = new RelayCommand(MouseMove);
+            MouseDownCommand = new RelayCommand(MouseDown);
+            ExportFileCommand = new RelayCommand(ExportFile, CanSave);
+            UndoCommand = new RelayCommand(Undo, CanUndo);
+            RedoCommand = new RelayCommand(Redo, CanRedo);
+            OpenFileCommand = new RelayCommand(Open);
+            SetActiveLayerCommand = new RelayCommand(SetActiveLayer);
+            NewLayerCommand = new RelayCommand(NewLayer, CanCreateNewLayer);
+            DeleteLayerCommand = new RelayCommand(DeleteLayer, CanDeleteLayer);
+            MoveToBackCommand = new RelayCommand(MoveLayerToBack, CanMoveToBack);
+            MoveToFrontCommand = new RelayCommand(MoveLayerToFront, CanMoveToFront);
+            SwapColorsCommand = new RelayCommand(SwapColors);
+            KeyDownCommand = new RelayCommand(KeyDown);
+            KeyUpCommand = new RelayCommand(KeyUp);
+            RenameLayerCommand = new RelayCommand(RenameLayer);
+            DeselectCommand = new RelayCommand(Deselect, SelectionIsNotEmpty);
+            SelectAllCommand = new RelayCommand(SelectAll, CanSelectAll);
+            CopyCommand = new RelayCommand(Copy, SelectionIsNotEmpty);
+            DuplicateCommand = new RelayCommand(Duplicate, SelectionIsNotEmpty);
+            CutCommand = new RelayCommand(Cut, SelectionIsNotEmpty);
+            PasteCommand = new RelayCommand(Paste, CanPaste);
+            ClipCanvasCommand = new RelayCommand(ClipCanvas, DocumentIsNotNull);
+            DeletePixelsCommand = new RelayCommand(DeletePixels, SelectionIsNotEmpty);
+            OpenResizePopupCommand = new RelayCommand(OpenResizePopup, DocumentIsNotNull);
+            SelectColorCommand = new RelayCommand(SelectColor);
+            RemoveSwatchCommand = new RelayCommand(RemoveSwatch);
+            SaveDocumentCommand = new RelayCommand(SaveDocument, DocumentIsNotNull);
+            OnStartupCommand = new RelayCommand(OnStartup);
+            CloseWindowCommand = new RelayCommand(CloseWindow);
+            CenterContentCommand = new RelayCommand(CenterContent, DocumentIsNotNull);
+            OpenHyperlinkCommand = new RelayCommand(OpenHyperlink);
+            ZoomCommand = new RelayCommand(ZoomViewport);
+            ChangeToolSizeCommand = new RelayCommand(ChangeToolSize);
+            RestartApplicationCommand = new RelayCommand(RestartApplication);
+            ToolSet = new ObservableCollection<Tool>
+            {
+                new MoveTool(), new PenTool(), new SelectTool(), new FloodFill(), new LineTool(),
+                new CircleTool(), new RectangleTool(), new EraserTool(), new ColorPickerTool(), new BrightnessTool(),
+                new ZoomTool()
+            };
+            ShortcutController = new ShortcutController
+            {
+                Shortcuts = new List<Shortcut>
+                {
+                    //Tools
+                    new Shortcut(Key.B, SelectToolCommand, ToolType.Pen),
+                    new Shortcut(Key.E, SelectToolCommand, ToolType.Eraser),
+                    new Shortcut(Key.O, SelectToolCommand, ToolType.ColorPicker),
+                    new Shortcut(Key.R, SelectToolCommand, ToolType.Rectangle),
+                    new Shortcut(Key.C, SelectToolCommand, ToolType.Circle),
+                    new Shortcut(Key.L, SelectToolCommand, ToolType.Line),
+                    new Shortcut(Key.G, SelectToolCommand, ToolType.Bucket),
+                    new Shortcut(Key.U, SelectToolCommand, ToolType.Brightness),
+                    new Shortcut(Key.V, SelectToolCommand, ToolType.Move),
+                    new Shortcut(Key.M, SelectToolCommand, ToolType.Select),
+                    new Shortcut(Key.Z, SelectToolCommand, ToolType.Zoom),
+                    new Shortcut(Key.OemPlus, ZoomCommand, 115),
+                    new Shortcut(Key.OemMinus, ZoomCommand, 85),
+                    new Shortcut(Key.OemOpenBrackets, ChangeToolSizeCommand, -1),
+                    new Shortcut(Key.OemCloseBrackets, ChangeToolSizeCommand, 1),
+                    //Editor
+                    new Shortcut(Key.X, SwapColorsCommand),
+                    new Shortcut(Key.Y, RedoCommand, modifier: ModifierKeys.Control),
+                    new Shortcut(Key.Z, UndoCommand, modifier: ModifierKeys.Control),
+                    new Shortcut(Key.D, DeselectCommand, modifier: ModifierKeys.Control),
+                    new Shortcut(Key.A, SelectAllCommand, modifier: ModifierKeys.Control),
+                    new Shortcut(Key.C, CopyCommand, modifier: ModifierKeys.Control),
+                    new Shortcut(Key.V, PasteCommand, modifier: ModifierKeys.Control),
+                    new Shortcut(Key.J, DuplicateCommand, modifier: ModifierKeys.Control),
+                    new Shortcut(Key.X, CutCommand, modifier: ModifierKeys.Control),
+                    new Shortcut(Key.Delete, DeletePixelsCommand),
+                    new Shortcut(Key.I, OpenResizePopupCommand, modifier: ModifierKeys.Control | ModifierKeys.Shift),
+                    new Shortcut(Key.C, OpenResizePopupCommand, "canvas", ModifierKeys.Control | ModifierKeys.Shift),
+                    new Shortcut(Key.F11, SystemCommands.MaximizeWindowCommand),
+                    //File
+                    new Shortcut(Key.O, OpenFileCommand, modifier: ModifierKeys.Control),
+                    new Shortcut(Key.S, ExportFileCommand,
+                        modifier: ModifierKeys.Control | ModifierKeys.Shift | ModifierKeys.Alt),
+                    new Shortcut(Key.S, SaveDocumentCommand, modifier: ModifierKeys.Control),
+                    new Shortcut(Key.S, SaveDocumentCommand, "AsNew", ModifierKeys.Control | ModifierKeys.Shift),
+                    new Shortcut(Key.N, OpenNewFilePopupCommand, modifier: ModifierKeys.Control)
+                }
+            };
+            UndoManager.SetMainRoot(this);
+            SetActiveTool(ToolType.Move);
+            BitmapManager.PrimaryColor = PrimaryColor;
+            ActiveSelection = new Selection(Array.Empty<Coordinates>());
+            Current = this;
+            InitUpdateChecker();
+        }
 
 
         public Action CloseAction { get; set; }
         public Action CloseAction { get; set; }
 
 
         public static ViewModelMain Current { get; set; }
         public static ViewModelMain Current { get; set; }
-        public RelayCommand SelectToolCommand { get; set; } //Command that handles tool switching 
+        public RelayCommand SelectToolCommand { get; set; } //Command that handles tool switching
         public RelayCommand OpenNewFilePopupCommand { get; set; } //Command that generates draw area
         public RelayCommand OpenNewFilePopupCommand { get; set; } //Command that generates draw area
         public RelayCommand MouseMoveCommand { get; set; } //Command that is used to draw
         public RelayCommand MouseMoveCommand { get; set; } //Command that is used to draw
         public RelayCommand MouseDownCommand { get; set; }
         public RelayCommand MouseDownCommand { get; set; }
@@ -57,6 +170,7 @@ namespace PixiEditor.ViewModels
         public RelayCommand ExportFileCommand { get; set; } //Command that is used to save file
         public RelayCommand ExportFileCommand { get; set; } //Command that is used to save file
         public RelayCommand UndoCommand { get; set; }
         public RelayCommand UndoCommand { get; set; }
         public RelayCommand RedoCommand { get; set; }
         public RelayCommand RedoCommand { get; set; }
+
         public RelayCommand OpenFileCommand { get; set; }
         public RelayCommand OpenFileCommand { get; set; }
         public RelayCommand SetActiveLayerCommand { get; set; }
         public RelayCommand SetActiveLayerCommand { get; set; }
         public RelayCommand NewLayerCommand { get; set; }
         public RelayCommand NewLayerCommand { get; set; }
@@ -85,39 +199,32 @@ namespace PixiEditor.ViewModels
         public RelayCommand ChangeToolSizeCommand { get; set; }
         public RelayCommand ChangeToolSizeCommand { get; set; }
         public RelayCommand RestartApplicationCommand { get; set; }
         public RelayCommand RestartApplicationCommand { get; set; }
 
 
-
-        private double _mouseXonCanvas;
-
-        private double _mouseYonCanvas;
-
-        public double MouseXOnCanvas //Mouse X coordinate relative to canvas
+        public double MouseXOnCanvas // Mouse X coordinate relative to canvas
         {
         {
-            get => _mouseXonCanvas;
+            get => mouseXonCanvas;
             set
             set
             {
             {
-                _mouseXonCanvas = value;
+                mouseXonCanvas = value;
                 RaisePropertyChanged("MouseXOnCanvas");
                 RaisePropertyChanged("MouseXOnCanvas");
             }
             }
         }
         }
 
 
-        public double MouseYOnCanvas //Mouse Y coordinate relative to canvas
+        public double MouseYOnCanvas // Mouse Y coordinate relative to canvas
         {
         {
-            get => _mouseYonCanvas;
+            get => mouseYonCanvas;
             set
             set
             {
             {
-                _mouseYonCanvas = value;
+                mouseYonCanvas = value;
                 RaisePropertyChanged("MouseYOnCanvas");
                 RaisePropertyChanged("MouseYOnCanvas");
             }
             }
         }
         }
 
 
-        private string _versionText;
-
         public string VersionText
         public string VersionText
         {
         {
-            get => _versionText;
+            get => versionText;
             set
             set
             {
             {
-                _versionText = value;
+                versionText = value;
                 RaisePropertyChanged(nameof(VersionText));
                 RaisePropertyChanged(nameof(VersionText));
             }
             }
         }
         }
@@ -125,22 +232,22 @@ namespace PixiEditor.ViewModels
 
 
         public bool RecenterZoombox
         public bool RecenterZoombox
         {
         {
-            get => _recenterZoombox;
+            get => recenterZoombox;
             set
             set
             {
             {
-                _recenterZoombox = value;
+                recenterZoombox = value;
                 RaisePropertyChanged("RecenterZoombox");
                 RaisePropertyChanged("RecenterZoombox");
             }
             }
         }
         }
 
 
         public Color PrimaryColor //Primary color, hooked with left mouse button
         public Color PrimaryColor //Primary color, hooked with left mouse button
         {
         {
-            get => _primaryColor;
+            get => primaryColor;
             set
             set
             {
             {
-                if (_primaryColor != value)
+                if (primaryColor != value)
                 {
                 {
-                    _primaryColor = value;
+                    primaryColor = value;
                     BitmapManager.PrimaryColor = value;
                     BitmapManager.PrimaryColor = value;
                     RaisePropertyChanged("PrimaryColor");
                     RaisePropertyChanged("PrimaryColor");
                 }
                 }
@@ -149,12 +256,12 @@ namespace PixiEditor.ViewModels
 
 
         public Color SecondaryColor
         public Color SecondaryColor
         {
         {
-            get => _secondaryColor;
+            get => secondaryColor;
             set
             set
             {
             {
-                if (_secondaryColor != value)
+                if (secondaryColor != value)
                 {
                 {
-                    _secondaryColor = value;
+                    secondaryColor = value;
                     RaisePropertyChanged("SecondaryColor");
                     RaisePropertyChanged("SecondaryColor");
                 }
                 }
             }
             }
@@ -164,45 +271,41 @@ namespace PixiEditor.ViewModels
 
 
         public LayerChange[] UndoChanges //This acts like UndoManager process, but it was implemented before process system, so it can be transformed into it
         public LayerChange[] UndoChanges //This acts like UndoManager process, but it was implemented before process system, so it can be transformed into it
         {
         {
-            get => _undoChanges;
+            get => undoChanges;
             set
             set
             {
             {
-                _undoChanges = value;
-                for (int i = 0; i < value.Length; i++)
+                undoChanges = value;
+                for (var i = 0; i < value.Length; i++)
                     BitmapManager.ActiveDocument.Layers[value[i].LayerIndex].SetPixels(value[i].PixelChanges);
                     BitmapManager.ActiveDocument.Layers[value[i].LayerIndex].SetPixels(value[i].PixelChanges);
             }
             }
         }
         }
 
 
         public Cursor ToolCursor
         public Cursor ToolCursor
         {
         {
-            get => _toolCursor;
+            get => toolCursor;
             set
             set
             {
             {
-                _toolCursor = value;
+                toolCursor = value;
                 RaisePropertyChanged("ToolCursor");
                 RaisePropertyChanged("ToolCursor");
             }
             }
         }
         }
 
 
-        private double _zoomPercentage = 100;
-
         public double ZoomPercentage
         public double ZoomPercentage
         {
         {
-            get { return _zoomPercentage; }
-            set 
+            get => zoomPercentage;
+            set
             {
             {
-                _zoomPercentage = value;
+                zoomPercentage = value;
                 RaisePropertyChanged(nameof(ZoomPercentage));
                 RaisePropertyChanged(nameof(ZoomPercentage));
             }
             }
         }
         }
 
 
-        private bool _updateReadyToInstall = false;
-
         public bool UpdateReadyToInstall
         public bool UpdateReadyToInstall
         {
         {
-            get => _updateReadyToInstall;
+            get => updateReadyToInstall;
             set
             set
             {
             {
-                _updateReadyToInstall = value;
+                updateReadyToInstall = value;
                 RaisePropertyChanged(nameof(UpdateReadyToInstall));
                 RaisePropertyChanged(nameof(UpdateReadyToInstall));
             }
             }
         }
         }
@@ -214,119 +317,16 @@ namespace PixiEditor.ViewModels
 
 
         public Selection ActiveSelection
         public Selection ActiveSelection
         {
         {
-            get => _selection;
+            get => selection;
             set
             set
             {
             {
-                _selection = value;
+                selection = value;
                 RaisePropertyChanged("ActiveSelection");
                 RaisePropertyChanged("ActiveSelection");
             }
             }
         }
         }
 
 
-        private bool _restoreToolOnKeyUp = false;
-        private Tool _lastActionTool;
-
         public UpdateChecker UpdateChecker { get; set; }
         public UpdateChecker UpdateChecker { get; set; }
 
 
-        public ViewModelMain()
-        {
-            BitmapManager = new BitmapManager();
-            BitmapManager.BitmapOperations.BitmapChanged += BitmapUtility_BitmapChanged;
-            BitmapManager.MouseController.StoppedRecordingChanges += MouseController_StoppedRecordingChanges;
-            BitmapManager.DocumentChanged += BitmapManager_DocumentChanged;
-            ChangesController = new PixelChangesController();
-            SelectToolCommand = new RelayCommand(SetTool, DocumentIsNotNull);
-            OpenNewFilePopupCommand = new RelayCommand(OpenNewFilePopup);
-            MouseMoveCommand = new RelayCommand(MouseMove);
-            MouseDownCommand = new RelayCommand(MouseDown);
-            ExportFileCommand = new RelayCommand(ExportFile, CanSave);
-            UndoCommand = new RelayCommand(Undo, CanUndo);
-            RedoCommand = new RelayCommand(Redo, CanRedo);
-            OpenFileCommand = new RelayCommand(Open);
-            SetActiveLayerCommand = new RelayCommand(SetActiveLayer);
-            NewLayerCommand = new RelayCommand(NewLayer, CanCreateNewLayer);
-            DeleteLayerCommand = new RelayCommand(DeleteLayer, CanDeleteLayer);
-            MoveToBackCommand = new RelayCommand(MoveLayerToBack, CanMoveToBack);
-            MoveToFrontCommand = new RelayCommand(MoveLayerToFront, CanMoveToFront);
-            SwapColorsCommand = new RelayCommand(SwapColors);
-            KeyDownCommand = new RelayCommand(KeyDown);
-            KeyUpCommand = new RelayCommand(KeyUp);
-            RenameLayerCommand = new RelayCommand(RenameLayer);
-            DeselectCommand = new RelayCommand(Deselect, SelectionIsNotEmpty);
-            SelectAllCommand = new RelayCommand(SelectAll, CanSelectAll);
-            CopyCommand = new RelayCommand(Copy, SelectionIsNotEmpty);
-            DuplicateCommand = new RelayCommand(Duplicate, SelectionIsNotEmpty);
-            CutCommand = new RelayCommand(Cut, SelectionIsNotEmpty);
-            PasteCommand = new RelayCommand(Paste, CanPaste);
-            ClipCanvasCommand = new RelayCommand(ClipCanvas, DocumentIsNotNull);
-            DeletePixelsCommand = new RelayCommand(DeletePixels, SelectionIsNotEmpty);
-            OpenResizePopupCommand = new RelayCommand(OpenResizePopup, DocumentIsNotNull);
-            SelectColorCommand = new RelayCommand(SelectColor);
-            RemoveSwatchCommand = new RelayCommand(RemoveSwatch);
-            SaveDocumentCommand = new RelayCommand(SaveDocument, DocumentIsNotNull);
-            OnStartupCommand = new RelayCommand(OnStartup);
-            CloseWindowCommand = new RelayCommand(CloseWindow);
-            CenterContentCommand = new RelayCommand(CenterContent, DocumentIsNotNull);
-            OpenHyperlinkCommand = new RelayCommand(OpenHyperlink);
-            ZoomCommand = new RelayCommand(ZoomViewport);
-            ChangeToolSizeCommand = new RelayCommand(ChangeToolSize);
-            RestartApplicationCommand = new RelayCommand(RestartApplication);
-            ToolSet = new ObservableCollection<Tool>
-            {
-                new MoveTool(), new PenTool(), new SelectTool(), new FloodFill(), new LineTool(),
-                new CircleTool(), new RectangleTool(), new EraserTool(), new ColorPickerTool(), new BrightnessTool(), 
-                new ZoomTool()
-            };
-            ShortcutController = new ShortcutController
-            {
-                Shortcuts = new List<Shortcut>
-                {
-                    //Tools
-                    new Shortcut(Key.B, SelectToolCommand, ToolType.Pen),
-                    new Shortcut(Key.E, SelectToolCommand, ToolType.Eraser),
-                    new Shortcut(Key.O, SelectToolCommand, ToolType.ColorPicker),
-                    new Shortcut(Key.R, SelectToolCommand, ToolType.Rectangle),
-                    new Shortcut(Key.C, SelectToolCommand, ToolType.Circle),
-                    new Shortcut(Key.L, SelectToolCommand, ToolType.Line),
-                    new Shortcut(Key.G, SelectToolCommand, ToolType.Bucket),
-                    new Shortcut(Key.U, SelectToolCommand, ToolType.Brightness),
-                    new Shortcut(Key.V, SelectToolCommand, ToolType.Move),
-                    new Shortcut(Key.M, SelectToolCommand, ToolType.Select),
-                    new Shortcut(Key.Z, SelectToolCommand, ToolType.Zoom),
-                    new Shortcut(Key.OemPlus, ZoomCommand, 115),
-                    new Shortcut(Key.OemMinus, ZoomCommand, 85),
-                    new Shortcut(Key.OemOpenBrackets, ChangeToolSizeCommand, -1),
-                    new Shortcut(Key.OemCloseBrackets, ChangeToolSizeCommand, 1),
-                    //Editor
-                    new Shortcut(Key.X, SwapColorsCommand),
-                    new Shortcut(Key.Y, RedoCommand, modifier: ModifierKeys.Control),
-                    new Shortcut(Key.Z, UndoCommand, modifier: ModifierKeys.Control),
-                    new Shortcut(Key.D, DeselectCommand, modifier: ModifierKeys.Control),
-                    new Shortcut(Key.A, SelectAllCommand, modifier: ModifierKeys.Control),
-                    new Shortcut(Key.C, CopyCommand, modifier: ModifierKeys.Control),
-                    new Shortcut(Key.V, PasteCommand, modifier: ModifierKeys.Control),
-                    new Shortcut(Key.J, DuplicateCommand, modifier: ModifierKeys.Control),
-                    new Shortcut(Key.X, CutCommand, modifier: ModifierKeys.Control),
-                    new Shortcut(Key.Delete, DeletePixelsCommand),
-                    new Shortcut(Key.I, OpenResizePopupCommand, modifier: ModifierKeys.Control | ModifierKeys.Shift),
-                    new Shortcut(Key.C, OpenResizePopupCommand, "canvas", ModifierKeys.Control | ModifierKeys.Shift),
-                    new Shortcut(Key.F11, SystemCommands.MaximizeWindowCommand),
-                    //File
-                    new Shortcut(Key.O, OpenFileCommand, modifier: ModifierKeys.Control),
-                    new Shortcut(Key.S, ExportFileCommand,
-                        modifier: ModifierKeys.Control | ModifierKeys.Shift | ModifierKeys.Alt),
-                    new Shortcut(Key.S, SaveDocumentCommand, modifier: ModifierKeys.Control),
-                    new Shortcut(Key.S, SaveDocumentCommand, "AsNew", ModifierKeys.Control | ModifierKeys.Shift),
-                    new Shortcut(Key.N, OpenNewFilePopupCommand, modifier: ModifierKeys.Control),
-                }
-            };
-            UndoManager.SetMainRoot(this);
-            SetActiveTool(ToolType.Move);
-            BitmapManager.PrimaryColor = PrimaryColor;
-            ActiveSelection = new Selection(Array.Empty<Coordinates>());
-            Current = this;
-            InitUpdateChecker();
-        }
-
         private void RestartApplication(object parameter)
         private void RestartApplication(object parameter)
         {
         {
             Process.Start(Path.Join(AppDomain.CurrentDomain.BaseDirectory, "PixiEditor.UpdateInstaller.exe"));
             Process.Start(Path.Join(AppDomain.CurrentDomain.BaseDirectory, "PixiEditor.UpdateInstaller.exe"));
@@ -337,8 +337,8 @@ namespace PixiEditor.ViewModels
         {
         {
             return await Task.Run(async () =>
             return await Task.Run(async () =>
             {
             {
-                bool updateAvailable = await UpdateChecker.CheckUpdateAvailable();
-                bool updateFileDoesNotExists = !File.Exists($"update-{UpdateChecker.LatestReleaseInfo.TagName}.zip");
+                var updateAvailable = await UpdateChecker.CheckUpdateAvailable();
+                var updateFileDoesNotExists = !File.Exists($"update-{UpdateChecker.LatestReleaseInfo.TagName}.zip");
                 if (updateAvailable && updateFileDoesNotExists)
                 if (updateAvailable && updateFileDoesNotExists)
                 {
                 {
                     VersionText = "Downloading update...";
                     VersionText = "Downloading update...";
@@ -347,6 +347,7 @@ namespace PixiEditor.ViewModels
                     UpdateReadyToInstall = true;
                     UpdateReadyToInstall = true;
                     return true;
                     return true;
                 }
                 }
+
                 return false;
                 return false;
             });
             });
         }
         }
@@ -354,33 +355,30 @@ namespace PixiEditor.ViewModels
         private void InitUpdateChecker()
         private void InitUpdateChecker()
         {
         {
             var assembly = Assembly.GetExecutingAssembly();
             var assembly = Assembly.GetExecutingAssembly();
-            FileVersionInfo info = FileVersionInfo.GetVersionInfo(assembly.Location);
+            var info = FileVersionInfo.GetVersionInfo(assembly.Location);
             UpdateChecker = new UpdateChecker(info.FileVersion);
             UpdateChecker = new UpdateChecker(info.FileVersion);
             VersionText = $"Version {info.FileVersion}";
             VersionText = $"Version {info.FileVersion}";
         }
         }
 
 
         private void ZoomViewport(object parameter)
         private void ZoomViewport(object parameter)
         {
         {
-            double zoom = (int)parameter;
+            double zoom = (int) parameter;
             ZoomPercentage = zoom;
             ZoomPercentage = zoom;
             ZoomPercentage = 100;
             ZoomPercentage = 100;
         }
         }
 
 
         private void ChangeToolSize(object parameter)
         private void ChangeToolSize(object parameter)
         {
         {
-            int increment = (int)parameter;
-            int newSize = BitmapManager.ToolSize + increment;
-            if (newSize > 0)
-            {
-                BitmapManager.ToolSize = newSize;
-            }
+            var increment = (int) parameter;
+            var newSize = BitmapManager.ToolSize + increment;
+            if (newSize > 0) BitmapManager.ToolSize = newSize;
         }
         }
 
 
         private void OpenHyperlink(object parameter)
         private void OpenHyperlink(object parameter)
         {
         {
             if (parameter == null) return;
             if (parameter == null) return;
-            string url = (string) parameter;
-            var processInfo = new ProcessStartInfo()
+            var url = (string) parameter;
+            var processInfo = new ProcessStartInfo
             {
             {
                 FileName = url,
                 FileName = url,
                 UseShellExecute = true
                 UseShellExecute = true
@@ -399,8 +397,8 @@ namespace PixiEditor.ViewModels
 
 
             ((CancelEventArgs) property).Cancel = true;
             ((CancelEventArgs) property).Cancel = true;
 
 
-            ConfirmationType result = ConfirmationType.No;
-            if (_unsavedDocumentModified)
+            var result = ConfirmationType.No;
+            if (unsavedDocumentModified)
             {
             {
                 result = ConfirmationDialog.Show(ConfirmationDialogMessage);
                 result = ConfirmationDialog.Show(ConfirmationDialogMessage);
                 if (result == ConfirmationType.Yes) SaveDocument(null);
                 if (result == ConfirmationType.Yes) SaveDocument(null);
@@ -413,13 +411,9 @@ namespace PixiEditor.ViewModels
         {
         {
             var lastArg = Environment.GetCommandLineArgs().Last();
             var lastArg = Environment.GetCommandLineArgs().Last();
             if (Importer.IsSupportedFile(lastArg) && File.Exists(lastArg))
             if (Importer.IsSupportedFile(lastArg) && File.Exists(lastArg))
-            {
                 Open(lastArg);
                 Open(lastArg);
-            }
             else
             else
-            {
                 OpenNewFilePopup(null);
                 OpenNewFilePopup(null);
-            }
             await CheckForUpdate();
             await CheckForUpdate();
         }
         }
 
 
@@ -430,7 +424,7 @@ namespace PixiEditor.ViewModels
 
 
         private void Open(object property)
         private void Open(object property)
         {
         {
-            OpenFileDialog dialog = new OpenFileDialog
+            var dialog = new OpenFileDialog
             {
             {
                 Filter = "All Files|*.*|PixiEditor Files | *.pixi|PNG Files|*.png",
                 Filter = "All Files|*.*|PixiEditor Files | *.pixi|PNG Files|*.png",
                 DefaultExt = "pixi"
                 DefaultExt = "pixi"
@@ -445,17 +439,12 @@ namespace PixiEditor.ViewModels
 
 
         private void Open(string path)
         private void Open(string path)
         {
         {
-            if (_unsavedDocumentModified)
+            if (unsavedDocumentModified)
             {
             {
                 var result = ConfirmationDialog.Show(ConfirmationDialogMessage);
                 var result = ConfirmationDialog.Show(ConfirmationDialogMessage);
                 if (result == ConfirmationType.Yes)
                 if (result == ConfirmationType.Yes)
-                {
                     SaveDocument(null);
                     SaveDocument(null);
-                }
-                else if (result == ConfirmationType.Canceled)
-                {
-                    return;
-                }
+                else if (result == ConfirmationType.Canceled) return;
             }
             }
 
 
             ResetProgramStateValues();
             ResetProgramStateValues();
@@ -469,28 +458,28 @@ namespace PixiEditor.ViewModels
         {
         {
             BitmapManager.ActiveDocument = Importer.ImportDocument(path);
             BitmapManager.ActiveDocument = Importer.ImportDocument(path);
             Exporter.SaveDocumentPath = path;
             Exporter.SaveDocumentPath = path;
-            _unsavedDocumentModified = false;
+            unsavedDocumentModified = false;
         }
         }
 
 
         private void SaveDocument(object parameter)
         private void SaveDocument(object parameter)
         {
         {
-            bool paramIsAsNew = parameter != null && parameter.ToString()?.ToLower() == "asnew";
+            var paramIsAsNew = parameter != null && parameter.ToString()?.ToLower() == "asnew";
             if (paramIsAsNew || Exporter.SaveDocumentPath == null)
             if (paramIsAsNew || Exporter.SaveDocumentPath == null)
             {
             {
                 var saved = Exporter.SaveAsEditableFileWithDialog(BitmapManager.ActiveDocument, !paramIsAsNew);
                 var saved = Exporter.SaveAsEditableFileWithDialog(BitmapManager.ActiveDocument, !paramIsAsNew);
-                _unsavedDocumentModified = _unsavedDocumentModified && !saved;
+                unsavedDocumentModified = unsavedDocumentModified && !saved;
             }
             }
             else
             else
             {
             {
                 Exporter.SaveAsEditableFile(BitmapManager.ActiveDocument, Exporter.SaveDocumentPath);
                 Exporter.SaveAsEditableFile(BitmapManager.ActiveDocument, Exporter.SaveDocumentPath);
-                _unsavedDocumentModified = false;
+                unsavedDocumentModified = false;
             }
             }
         }
         }
 
 
         private void RemoveSwatch(object parameter)
         private void RemoveSwatch(object parameter)
         {
         {
             if (!(parameter is Color)) throw new ArgumentException();
             if (!(parameter is Color)) throw new ArgumentException();
-            Color color = (Color) parameter;
+            var color = (Color) parameter;
             if (BitmapManager.ActiveDocument.Swatches.Contains(color))
             if (BitmapManager.ActiveDocument.Swatches.Contains(color))
                 BitmapManager.ActiveDocument.Swatches.Remove(color);
                 BitmapManager.ActiveDocument.Swatches.Remove(color);
         }
         }
@@ -504,7 +493,7 @@ namespace PixiEditor.ViewModels
         {
         {
             ActiveSelection = new Selection(Array.Empty<Coordinates>());
             ActiveSelection = new Selection(Array.Empty<Coordinates>());
             RecenterZoombox = !RecenterZoombox;
             RecenterZoombox = !RecenterZoombox;
-            _unsavedDocumentModified = true;
+            unsavedDocumentModified = true;
         }
         }
 
 
         public void AddSwatch(Color color)
         public void AddSwatch(Color color)
@@ -515,8 +504,8 @@ namespace PixiEditor.ViewModels
 
 
         private void OpenResizePopup(object parameter)
         private void OpenResizePopup(object parameter)
         {
         {
-            bool isCanvasDialog = (string) parameter == "canvas";
-            ResizeDocumentDialog dialog = new ResizeDocumentDialog(BitmapManager.ActiveDocument.Width,
+            var isCanvasDialog = (string) parameter == "canvas";
+            var dialog = new ResizeDocumentDialog(BitmapManager.ActiveDocument.Width,
                 BitmapManager.ActiveDocument.Height, isCanvasDialog);
                 BitmapManager.ActiveDocument.Height, isCanvasDialog);
             if (dialog.ShowDialog())
             if (dialog.ShowDialog())
             {
             {
@@ -570,7 +559,7 @@ namespace PixiEditor.ViewModels
 
 
         public void SelectAll(object parameter)
         public void SelectAll(object parameter)
         {
         {
-            SelectTool select = new SelectTool();
+            var select = new SelectTool();
             ActiveSelection.SetSelection(select.GetAllSelection(), SelectionType.New);
             ActiveSelection.SetSelection(select.GetAllSelection(), SelectionType.New);
         }
         }
 
 
@@ -606,29 +595,30 @@ namespace PixiEditor.ViewModels
 
 
         private void KeyUp(object parameter)
         private void KeyUp(object parameter)
         {
         {
-            KeyEventArgs args = (KeyEventArgs)parameter;
-            if (_restoreToolOnKeyUp && ShortcutController.LastShortcut != null && ShortcutController.LastShortcut.ShortcutKey == args.Key)
+            var args = (KeyEventArgs) parameter;
+            if (restoreToolOnKeyUp && ShortcutController.LastShortcut != null && ShortcutController.LastShortcut.ShortcutKey == args.Key)
             {
             {
-                _restoreToolOnKeyUp = false;
-                SetActiveTool(_lastActionTool);
+                restoreToolOnKeyUp = false;
+                SetActiveTool(lastActionTool);
                 ShortcutController.BlockShortcutExecution = false;
                 ShortcutController.BlockShortcutExecution = false;
             }
             }
         }
         }
 
 
         public void KeyDown(object parameter)
         public void KeyDown(object parameter)
         {
         {
-            KeyEventArgs args = (KeyEventArgs)parameter;
-            if (args.IsRepeat && !_restoreToolOnKeyUp && ShortcutController.LastShortcut != null && ShortcutController.LastShortcut.Command == SelectToolCommand)
+            var args = (KeyEventArgs) parameter;
+            if (args.IsRepeat && !restoreToolOnKeyUp && ShortcutController.LastShortcut != null && ShortcutController.LastShortcut.Command == SelectToolCommand)
             {
             {
-                _restoreToolOnKeyUp = true;
+                restoreToolOnKeyUp = true;
                 ShortcutController.BlockShortcutExecution = true;
                 ShortcutController.BlockShortcutExecution = true;
             }
             }
+
             ShortcutController.KeyPressed(args.Key, Keyboard.Modifiers);
             ShortcutController.KeyPressed(args.Key, Keyboard.Modifiers);
         }
         }
 
 
         private void MouseController_StoppedRecordingChanges(object sender, EventArgs e)
         private void MouseController_StoppedRecordingChanges(object sender, EventArgs e)
         {
         {
-           TriggerNewUndoChange(BitmapManager.SelectedTool);
+            TriggerNewUndoChange(BitmapManager.SelectedTool);
         }
         }
 
 
         public void TriggerNewUndoChange(Tool toolUsed)
         public void TriggerNewUndoChange(Tool toolUsed)
@@ -636,11 +626,11 @@ namespace PixiEditor.ViewModels
             if (BitmapManager.IsOperationTool(toolUsed)
             if (BitmapManager.IsOperationTool(toolUsed)
                 && ((BitmapOperationTool) toolUsed).UseDefaultUndoMethod)
                 && ((BitmapOperationTool) toolUsed).UseDefaultUndoMethod)
             {
             {
-                Tuple<LayerChange, LayerChange>[] changes = ChangesController.PopChanges();
+                var changes = ChangesController.PopChanges();
                 if (changes != null && changes.Length > 0)
                 if (changes != null && changes.Length > 0)
                 {
                 {
-                    LayerChange[] newValues = changes.Select(x => x.Item1).ToArray();
-                    LayerChange[] oldValues = changes.Select(x => x.Item2).ToArray();
+                    var newValues = changes.Select(x => x.Item1).ToArray();
+                    var oldValues = changes.Select(x => x.Item2).ToArray();
                     UndoManager.AddUndoChange(new Change("UndoChanges", oldValues, newValues));
                     UndoManager.AddUndoChange(new Change("UndoChanges", oldValues, newValues));
                     toolUsed.AfterAddedUndo();
                     toolUsed.AfterAddedUndo();
                 }
                 }
@@ -651,7 +641,7 @@ namespace PixiEditor.ViewModels
         {
         {
             ChangesController.AddChanges(new LayerChange(e.PixelsChanged, e.ChangedLayerIndex),
             ChangesController.AddChanges(new LayerChange(e.PixelsChanged, e.ChangedLayerIndex),
                 new LayerChange(e.OldPixelsValues, e.ChangedLayerIndex));
                 new LayerChange(e.OldPixelsValues, e.ChangedLayerIndex));
-            _unsavedDocumentModified = true;
+            unsavedDocumentModified = true;
             if (BitmapManager.IsOperationTool())
             if (BitmapManager.IsOperationTool())
                 AddSwatch(PrimaryColor);
                 AddSwatch(PrimaryColor);
         }
         }
@@ -665,14 +655,14 @@ namespace PixiEditor.ViewModels
 
 
         public void MoveLayerToFront(object parameter)
         public void MoveLayerToFront(object parameter)
         {
         {
-            int oldIndex = (int) parameter;
+            var oldIndex = (int) parameter;
             BitmapManager.ActiveDocument.Layers.Move(oldIndex, oldIndex + 1);
             BitmapManager.ActiveDocument.Layers.Move(oldIndex, oldIndex + 1);
             if (BitmapManager.ActiveDocument.ActiveLayerIndex == oldIndex) BitmapManager.SetActiveLayer(oldIndex + 1);
             if (BitmapManager.ActiveDocument.ActiveLayerIndex == oldIndex) BitmapManager.SetActiveLayer(oldIndex + 1);
         }
         }
 
 
         public void MoveLayerToBack(object parameter)
         public void MoveLayerToBack(object parameter)
         {
         {
-            int oldIndex = (int) parameter;
+            var oldIndex = (int) parameter;
             BitmapManager.ActiveDocument.Layers.Move(oldIndex, oldIndex - 1);
             BitmapManager.ActiveDocument.Layers.Move(oldIndex, oldIndex - 1);
             if (BitmapManager.ActiveDocument.ActiveLayerIndex == oldIndex) BitmapManager.SetActiveLayer(oldIndex - 1);
             if (BitmapManager.ActiveDocument.ActiveLayerIndex == oldIndex) BitmapManager.SetActiveLayer(oldIndex - 1);
         }
         }
@@ -704,22 +694,22 @@ namespace PixiEditor.ViewModels
 
 
         public void SetActiveTool(ToolType tool)
         public void SetActiveTool(ToolType tool)
         {
         {
-            Tool foundTool = ToolSet.First(x => x.ToolType == tool);
+            var foundTool = ToolSet.First(x => x.ToolType == tool);
             SetActiveTool(foundTool);
             SetActiveTool(foundTool);
         }
         }
 
 
         public void SetActiveTool(Tool tool)
         public void SetActiveTool(Tool tool)
         {
         {
-            Tool activeTool = ToolSet.FirstOrDefault(x => x.IsActive);
+            var activeTool = ToolSet.FirstOrDefault(x => x.IsActive);
             if (activeTool != null) activeTool.IsActive = false;
             if (activeTool != null) activeTool.IsActive = false;
 
 
             tool.IsActive = true;
             tool.IsActive = true;
-            _lastActionTool = BitmapManager.SelectedTool;
+            lastActionTool = BitmapManager.SelectedTool;
             BitmapManager.SetActiveTool(tool);
             BitmapManager.SetActiveTool(tool);
             SetToolCursor(tool.ToolType);
             SetToolCursor(tool.ToolType);
         }
         }
 
 
-            private void SetToolCursor(ToolType tool)
+        private void SetToolCursor(ToolType tool)
         {
         {
             if (tool != ToolType.None)
             if (tool != ToolType.None)
                 ToolCursor = BitmapManager.SelectedTool.Cursor;
                 ToolCursor = BitmapManager.SelectedTool.Cursor;
@@ -731,15 +721,13 @@ namespace PixiEditor.ViewModels
         {
         {
             if (BitmapManager.ActiveDocument.Layers.Count == 0) return;
             if (BitmapManager.ActiveDocument.Layers.Count == 0) return;
             if (Mouse.LeftButton == MouseButtonState.Pressed)
             if (Mouse.LeftButton == MouseButtonState.Pressed)
-            {
                 if (!BitmapManager.MouseController.IsRecordingChanges)
                 if (!BitmapManager.MouseController.IsRecordingChanges)
                 {
                 {
-                    bool clickedOnCanvas = MouseXOnCanvas >= 0 && MouseXOnCanvas <= BitmapManager.ActiveDocument.Width &&
-                        MouseYOnCanvas >= 0 && MouseYOnCanvas <= BitmapManager.ActiveDocument.Height;
+                    var clickedOnCanvas = MouseXOnCanvas >= 0 && MouseXOnCanvas <= BitmapManager.ActiveDocument.Width &&
+                                          MouseYOnCanvas >= 0 && MouseYOnCanvas <= BitmapManager.ActiveDocument.Height;
                     BitmapManager.MouseController.StartRecordingMouseMovementChanges(clickedOnCanvas);
                     BitmapManager.MouseController.StartRecordingMouseMovementChanges(clickedOnCanvas);
                     BitmapManager.MouseController.RecordMouseMovementChange(MousePositionConverter.CurrentCoordinates);
                     BitmapManager.MouseController.RecordMouseMovementChange(MousePositionConverter.CurrentCoordinates);
                 }
                 }
-            }
 
 
             // Mouse down is guaranteed to only be raised from within this application, so by subscribing here we
             // Mouse down is guaranteed to only be raised from within this application, so by subscribing here we
             // only listen for mouse up events that occurred as a result of a mouse down within this application.
             // only listen for mouse up events that occurred as a result of a mouse down within this application.
@@ -760,15 +748,12 @@ namespace PixiEditor.ViewModels
         /// <param name="parameter"></param>
         /// <param name="parameter"></param>
         private void MouseMove(object parameter)
         private void MouseMove(object parameter)
         {
         {
-            Coordinates cords = new Coordinates((int)MouseXOnCanvas, (int)MouseYOnCanvas);
+            var cords = new Coordinates((int) MouseXOnCanvas, (int) MouseYOnCanvas);
             MousePositionConverter.CurrentCoordinates = cords;
             MousePositionConverter.CurrentCoordinates = cords;
 
 
 
 
-            if (BitmapManager.MouseController.IsRecordingChanges && Mouse.LeftButton == MouseButtonState.Pressed)
-            {
-                BitmapManager.MouseController.RecordMouseMovementChange(cords);
-            }
-                BitmapManager.MouseController.MouseMoved(cords);
+            if (BitmapManager.MouseController.IsRecordingChanges && Mouse.LeftButton == MouseButtonState.Pressed) BitmapManager.MouseController.RecordMouseMovementChange(cords);
+            BitmapManager.MouseController.MouseMoved(cords);
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -777,7 +762,7 @@ namespace PixiEditor.ViewModels
         /// <param name="parameter"></param>
         /// <param name="parameter"></param>
         public void OpenNewFilePopup(object parameter)
         public void OpenNewFilePopup(object parameter)
         {
         {
-            NewFileDialog newFile = new NewFileDialog();
+            var newFile = new NewFileDialog();
             if (newFile.ShowDialog()) NewDocument(newFile.Width, newFile.Height);
             if (newFile.ShowDialog()) NewDocument(newFile.Width, newFile.Height);
         }
         }
 
 
@@ -787,7 +772,7 @@ namespace PixiEditor.ViewModels
         /// <param name="path"></param>
         /// <param name="path"></param>
         public void OpenFile(string path)
         public void OpenFile(string path)
         {
         {
-            ImportFileDialog dialog = new ImportFileDialog();
+            var dialog = new ImportFileDialog();
 
 
             if (path != null && File.Exists(path))
             if (path != null && File.Exists(path))
                 dialog.FilePath = path;
                 dialog.FilePath = path;
@@ -795,14 +780,14 @@ namespace PixiEditor.ViewModels
             if (dialog.ShowDialog())
             if (dialog.ShowDialog())
             {
             {
                 NewDocument(dialog.FileWidth, dialog.FileHeight, false);
                 NewDocument(dialog.FileWidth, dialog.FileHeight, false);
-                BitmapManager.AddNewLayer("Image",Importer.ImportImage(dialog.FilePath, dialog.FileWidth, dialog.FileHeight));
+                BitmapManager.AddNewLayer("Image", Importer.ImportImage(dialog.FilePath, dialog.FileWidth, dialog.FileHeight));
             }
             }
         }
         }
 
 
         public void NewDocument(int width, int height, bool addBaseLayer = true)
         public void NewDocument(int width, int height, bool addBaseLayer = true)
         {
         {
             BitmapManager.ActiveDocument = new Document(width, height);
             BitmapManager.ActiveDocument = new Document(width, height);
-            if(addBaseLayer)
+            if (addBaseLayer)
                 BitmapManager.AddNewLayer("Base Layer");
                 BitmapManager.AddNewLayer("Base Layer");
             ResetProgramStateValues();
             ResetProgramStateValues();
         }
         }
@@ -818,7 +803,7 @@ namespace PixiEditor.ViewModels
             ActiveSelection = new Selection(Array.Empty<Coordinates>());
             ActiveSelection = new Selection(Array.Empty<Coordinates>());
             RecenterZoombox = !RecenterZoombox;
             RecenterZoombox = !RecenterZoombox;
             Exporter.SaveDocumentPath = null;
             Exporter.SaveDocumentPath = null;
-            _unsavedDocumentModified = false;
+            unsavedDocumentModified = false;
         }
         }
 
 
         public void NewLayer(object parameter)
         public void NewLayer(object parameter)
@@ -882,7 +867,7 @@ namespace PixiEditor.ViewModels
         /// <param name="parameter"></param>
         /// <param name="parameter"></param>
         private void ExportFile(object parameter)
         private void ExportFile(object parameter)
         {
         {
-            WriteableBitmap bitmap = BitmapManager.GetCombinedLayersBitmap();
+            var bitmap = BitmapManager.GetCombinedLayersBitmap();
             Exporter.Export(bitmap, new Size(bitmap.PixelWidth, bitmap.PixelHeight));
             Exporter.Export(bitmap, new Size(bitmap.PixelWidth, bitmap.PixelHeight));
         }
         }
 
 

+ 4 - 4
PixiEditor/Views/AnchorPointPicker.xaml.cs

@@ -16,7 +16,7 @@ namespace PixiEditor.Views
                 new PropertyMetadata());
                 new PropertyMetadata());
 
 
 
 
-        private ToggleButton _selectedToggleButton;
+        private ToggleButton selectedToggleButton;
 
 
         public AnchorPointPicker()
         public AnchorPointPicker()
         {
         {
@@ -31,10 +31,10 @@ namespace PixiEditor.Views
 
 
         private void ToggleButton_Checked(object sender, RoutedEventArgs e)
         private void ToggleButton_Checked(object sender, RoutedEventArgs e)
         {
         {
-            ToggleButton btn = (ToggleButton) sender;
+            var btn = (ToggleButton) sender;
             AnchorPoint = (AnchorPoint) (1 << (Grid.GetRow(btn) + 3)) | (AnchorPoint) (1 << Grid.GetColumn(btn));
             AnchorPoint = (AnchorPoint) (1 << (Grid.GetRow(btn) + 3)) | (AnchorPoint) (1 << Grid.GetColumn(btn));
-            if (_selectedToggleButton != null) _selectedToggleButton.IsChecked = false;
-            _selectedToggleButton = btn;
+            if (selectedToggleButton != null) selectedToggleButton.IsChecked = false;
+            selectedToggleButton = btn;
         }
         }
 
 
         private void ToggleButton_Click(object sender, RoutedEventArgs e)
         private void ToggleButton_Click(object sender, RoutedEventArgs e)

+ 1 - 1
PixiEditor/Views/ConfirmationPopup.xaml.cs

@@ -43,7 +43,7 @@ namespace PixiEditor.Views
 
 
         private void SetResultAndClose(object property)
         private void SetResultAndClose(object property)
         {
         {
-            bool result = (bool) property;
+            var result = (bool) property;
             Result = result;
             Result = result;
             DialogResult = true;
             DialogResult = true;
             Close();
             Close();

+ 1 - 2
PixiEditor/Views/EditableTextBlock.xaml.cs

@@ -1,7 +1,6 @@
 using System.Windows;
 using System.Windows;
 using System.Windows.Controls;
 using System.Windows.Controls;
 using System.Windows.Input;
 using System.Windows.Input;
-using PixiEditor.Models.Controllers;
 using PixiEditor.Models.Controllers.Shortcuts;
 using PixiEditor.Models.Controllers.Shortcuts;
 
 
 namespace PixiEditor.Views
 namespace PixiEditor.Views
@@ -56,7 +55,7 @@ namespace PixiEditor.Views
         {
         {
             if ((bool) e.NewValue)
             if ((bool) e.NewValue)
             {
             {
-                EditableTextBlock tb = (EditableTextBlock) d;
+                var tb = (EditableTextBlock) d;
                 tb.EnableEditing();
                 tb.EnableEditing();
             }
             }
         }
         }

+ 1 - 4
PixiEditor/Views/ImportFilePopup.xaml

@@ -6,15 +6,12 @@
         xmlns:local="clr-namespace:PixiEditor.Views"
         xmlns:local="clr-namespace:PixiEditor.Views"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:vm="clr-namespace:PixiEditor.ViewModels"
         xmlns:vm="clr-namespace:PixiEditor.ViewModels"
-        xmlns:behaviors="clr-namespace:PixiEditor.Helpers.Behaviours"
-        xmlns:helpers="clr-namespace:PixiEditor.Helpers"
         mc:Ignorable="d"
         mc:Ignorable="d"
         Title="ImportFilePopup" Topmost="True" ShowInTaskbar="False" Height="350" Width="300" WindowStyle="None"
         Title="ImportFilePopup" Topmost="True" ShowInTaskbar="False" Height="350" Width="300" WindowStyle="None"
         ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Name="importFilePopup"
         ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Name="importFilePopup"
         DataContext="{DynamicResource ImportFilePopupViewModel}">
         DataContext="{DynamicResource ImportFilePopupViewModel}">
     <Window.Resources>
     <Window.Resources>
         <vm:ImportFilePopupViewModel x:Key="ImportFilePopupViewModel" />
         <vm:ImportFilePopupViewModel x:Key="ImportFilePopupViewModel" />
-        <helpers:ToolSizeToIntConverter x:Key="ToolSizeToIntConverter" />
     </Window.Resources>
     </Window.Resources>
     <Border BorderBrush="Black" BorderThickness="1">
     <Border BorderBrush="Black" BorderThickness="1">
         <Grid Background="{StaticResource AccentColor}">
         <Grid Background="{StaticResource AccentColor}">
@@ -36,7 +33,7 @@
             <StackPanel Grid.Row="1">
             <StackPanel Grid.Row="1">
                 <Label Height="40" Width="120" VerticalAlignment="Top" Content="Open" Foreground="Snow"
                 <Label Height="40" Width="120" VerticalAlignment="Top" Content="Open" Foreground="Snow"
                        HorizontalContentAlignment="Center" FontSize="24" Margin="0,10,0,0" />
                        HorizontalContentAlignment="Center" FontSize="24" Margin="0,10,0,0" />
-                <Button Grid.Row="1" BorderThickness="1" Foreground="Snow" Height="40" Width="160" Margin="0,30,0,0"
+                <Button BorderThickness="1" Foreground="Snow" Height="40" Width="160" Margin="0,30,0,0"
                         Content="File Path" Background="#303030" BorderBrush="{Binding PathButtonBorder}"
                         Content="File Path" Background="#303030" BorderBrush="{Binding PathButtonBorder}"
                         Command="{Binding ChoosePathCommand}" />
                         Command="{Binding ChoosePathCommand}" />
                 <StackPanel Background="{StaticResource MainColor}" Height="120" Width="225" Margin="0,30,0,0">
                 <StackPanel Background="{StaticResource MainColor}" Height="120" Width="225" Margin="0,30,0,0">

+ 19 - 17
PixiEditor/Views/LayerItem.xaml

@@ -1,12 +1,12 @@
 <UserControl x:Class="PixiEditor.Views.LayerItem"
 <UserControl x:Class="PixiEditor.Views.LayerItem"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
-             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
              xmlns:local="clr-namespace:PixiEditor.Views"
              xmlns:local="clr-namespace:PixiEditor.Views"
              xmlns:converters="clr-namespace:PixiEditor.Helpers.Converters"
              xmlns:converters="clr-namespace:PixiEditor.Helpers.Converters"
              xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
              xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
-             mc:Ignorable="d" 
+             mc:Ignorable="d"
              d:DesignHeight="60" d:DesignWidth="250" Name="uc" MouseLeave="LayerItem_OnMouseLeave" MouseEnter="LayerItem_OnMouseEnter">
              d:DesignHeight="60" d:DesignWidth="250" Name="uc" MouseLeave="LayerItem_OnMouseLeave" MouseEnter="LayerItem_OnMouseEnter">
     <UserControl.Resources>
     <UserControl.Resources>
         <converters:BoolToColorConverter x:Key="BoolToColorConverter" />
         <converters:BoolToColorConverter x:Key="BoolToColorConverter" />
@@ -17,32 +17,34 @@
             <i:EventTrigger EventName="MouseDown">
             <i:EventTrigger EventName="MouseDown">
                 <i:InvokeCommandAction Command="{Binding ElementName=uc, 
                 <i:InvokeCommandAction Command="{Binding ElementName=uc, 
                             Path=SetActiveLayerCommand}"
                             Path=SetActiveLayerCommand}"
-                                       CommandParameter="{Binding Path=LayerIndex, ElementName=uc}"/>
+                                       CommandParameter="{Binding Path=LayerIndex, ElementName=uc}" />
             </i:EventTrigger>
             </i:EventTrigger>
         </i:Interaction.Triggers>
         </i:Interaction.Triggers>
         <Grid>
         <Grid>
             <Grid.ColumnDefinitions>
             <Grid.ColumnDefinitions>
-                <ColumnDefinition Width="35"/>
-                <ColumnDefinition Width="199*"/>
-                <ColumnDefinition Width="35"/>
+                <ColumnDefinition Width="35" />
+                <ColumnDefinition Width="199*" />
+                <ColumnDefinition Width="35" />
             </Grid.ColumnDefinitions>
             </Grid.ColumnDefinitions>
             <CheckBox VerticalAlignment="Center"
             <CheckBox VerticalAlignment="Center"
                       IsThreeState="False" HorizontalAlignment="Center"
                       IsThreeState="False" HorizontalAlignment="Center"
                       IsChecked="{Binding Path=IsVisible, Mode=TwoWay}" Grid.Column="0" Height="16" />
                       IsChecked="{Binding Path=IsVisible, Mode=TwoWay}" Grid.Column="0" Height="16" />
             <local:EditableTextBlock
             <local:EditableTextBlock
-                    IsEditing="{Binding IsRenaming, ElementName=uc, Mode=TwoWay}" Grid.Column="1" FontSize="16" HorizontalAlignment="Center"
-                    VerticalAlignment="Center"
-                    Text="{Binding LayerName, ElementName=uc, Mode=TwoWay}" />
-            <StackPanel Visibility="{Binding Path=ControlButtonsVisible, ElementName=uc}" 
-                        Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center" Width="15" 
+                IsEditing="{Binding IsRenaming, ElementName=uc, Mode=TwoWay}" Grid.Column="1" FontSize="16" HorizontalAlignment="Center"
+                VerticalAlignment="Center"
+                Text="{Binding LayerName, ElementName=uc, Mode=TwoWay}" />
+            <StackPanel Visibility="{Binding Path=ControlButtonsVisible, ElementName=uc}"
+                        Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center" Width="15"
                         Grid.Column="2">
                         Grid.Column="2">
-                <Button CommandParameter="{Binding LayerIndex, ElementName=uc}" Command="{Binding Path=MoveToFrontCommand, ElementName=uc}" Background="Transparent" Style="{StaticResource OpacityButtonStyle}" Foreground="White" HorizontalAlignment="Center" BorderThickness="0">
-                    <TextBlock Text="&#9650;"/>
+                <Button CommandParameter="{Binding LayerIndex, ElementName=uc}" Command="{Binding Path=MoveToFrontCommand, ElementName=uc}" Background="Transparent"
+                        Style="{StaticResource OpacityButtonStyle}" Foreground="White" HorizontalAlignment="Center" BorderThickness="0">
+                    <TextBlock Text="&#9650;" />
                 </Button>
                 </Button>
-                <Button CommandParameter="{Binding LayerIndex, ElementName=uc}" Command="{Binding Path=MoveToBackCommand, ElementName=uc}" Background="Transparent" HorizontalAlignment="Center" Style="{StaticResource OpacityButtonStyle}" Foreground="White" BorderThickness="0">
-                    <TextBlock Text="&#9660;"/>
+                <Button CommandParameter="{Binding LayerIndex, ElementName=uc}" Command="{Binding Path=MoveToBackCommand, ElementName=uc}" Background="Transparent"
+                        HorizontalAlignment="Center" Style="{StaticResource OpacityButtonStyle}" Foreground="White" BorderThickness="0">
+                    <TextBlock Text="&#9660;" />
                 </Button>
                 </Button>
             </StackPanel>
             </StackPanel>
         </Grid>
         </Grid>
     </Border>
     </Border>
-</UserControl>
+</UserControl>

+ 44 - 55
PixiEditor/Views/LayerItem.xaml.cs

@@ -1,102 +1,92 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Windows;
+using System.Windows;
 using System.Windows.Controls;
 using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
 using System.Windows.Input;
 using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Navigation;
-using System.Windows.Shapes;
 using PixiEditor.Helpers;
 using PixiEditor.Helpers;
 
 
 namespace PixiEditor.Views
 namespace PixiEditor.Views
 {
 {
     /// <summary>
     /// <summary>
-    /// Interaction logic for LayerItem.xaml
+    ///     Interaction logic for LayerItem.xaml
     /// </summary>
     /// </summary>
     public partial class LayerItem : UserControl
     public partial class LayerItem : UserControl
     {
     {
+        public static readonly DependencyProperty IsRenamingProperty = DependencyProperty.Register(
+            "IsRenaming", typeof(bool), typeof(LayerItem), new PropertyMetadata(default(bool)));
+
+        public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register(
+            "IsActive", typeof(bool), typeof(LayerItem), new PropertyMetadata(default(bool)));
+
+        public static readonly DependencyProperty SetActiveLayerCommandProperty = DependencyProperty.Register(
+            "SetActiveLayerCommand", typeof(RelayCommand), typeof(LayerItem), new PropertyMetadata(default(RelayCommand)));
+
+        public static readonly DependencyProperty LayerIndexProperty = DependencyProperty.Register(
+            "LayerIndex", typeof(int), typeof(LayerItem), new PropertyMetadata(default(int)));
+
+        public static readonly DependencyProperty LayerNameProperty = DependencyProperty.Register(
+            "LayerName", typeof(string), typeof(LayerItem), new PropertyMetadata(default(string)));
+
+        public static readonly DependencyProperty ControlButtonsVisibleProperty = DependencyProperty.Register(
+            "ControlButtonsVisible", typeof(Visibility), typeof(LayerItem), new PropertyMetadata(Visibility.Hidden));
+
+        // Using a DependencyProperty as the backing store for MoveToBackCommand.  This enables animation, styling, binding, etc...
+        public static readonly DependencyProperty MoveToBackCommandProperty =
+            DependencyProperty.Register("MoveToBackCommand", typeof(RelayCommand), typeof(LayerItem), new PropertyMetadata(default(RelayCommand)));
+
+        public static readonly DependencyProperty MoveToFrontCommandProperty = DependencyProperty.Register(
+            "MoveToFrontCommand", typeof(RelayCommand), typeof(LayerItem), new PropertyMetadata(default(RelayCommand)));
+
         public LayerItem()
         public LayerItem()
         {
         {
             InitializeComponent();
             InitializeComponent();
         }
         }
 
 
-        public static readonly DependencyProperty IsRenamingProperty = DependencyProperty.Register(
-            "IsRenaming", typeof(bool), typeof(LayerItem), new PropertyMetadata(default(bool)));
-
         public bool IsRenaming
         public bool IsRenaming
         {
         {
-            get { return (bool) GetValue(IsRenamingProperty); }
-            set { SetValue(IsRenamingProperty, value); }
+            get => (bool) GetValue(IsRenamingProperty);
+            set => SetValue(IsRenamingProperty, value);
         }
         }
 
 
-        public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register(
-            "IsActive", typeof(bool), typeof(LayerItem), new PropertyMetadata(default(bool)));
-
         public bool IsActive
         public bool IsActive
         {
         {
-            get { return (bool) GetValue(IsActiveProperty); }
-            set { SetValue(IsActiveProperty, value); }
+            get => (bool) GetValue(IsActiveProperty);
+            set => SetValue(IsActiveProperty, value);
         }
         }
 
 
-        public static readonly DependencyProperty SetActiveLayerCommandProperty = DependencyProperty.Register(
-            "SetActiveLayerCommand", typeof(RelayCommand), typeof(LayerItem), new PropertyMetadata(default(RelayCommand)));
-
         public RelayCommand SetActiveLayerCommand
         public RelayCommand SetActiveLayerCommand
         {
         {
-            get { return (RelayCommand) GetValue(SetActiveLayerCommandProperty); }
-            set { SetValue(SetActiveLayerCommandProperty, value); }
+            get => (RelayCommand) GetValue(SetActiveLayerCommandProperty);
+            set => SetValue(SetActiveLayerCommandProperty, value);
         }
         }
 
 
-        public static readonly DependencyProperty LayerIndexProperty = DependencyProperty.Register(
-            "LayerIndex", typeof(int), typeof(LayerItem), new PropertyMetadata(default(int)));
-
         public int LayerIndex
         public int LayerIndex
         {
         {
-            get { return (int) GetValue(LayerIndexProperty); }
-            set { SetValue(LayerIndexProperty, value); }
+            get => (int) GetValue(LayerIndexProperty);
+            set => SetValue(LayerIndexProperty, value);
         }
         }
 
 
-        public static readonly DependencyProperty LayerNameProperty = DependencyProperty.Register(
-            "LayerName", typeof(string), typeof(LayerItem), new PropertyMetadata(default(string)));
-
         public string LayerName
         public string LayerName
         {
         {
-            get { return (string) GetValue(LayerNameProperty); }
-            set { SetValue(LayerNameProperty, value); }
+            get => (string) GetValue(LayerNameProperty);
+            set => SetValue(LayerNameProperty, value);
         }
         }
 
 
-        public static readonly DependencyProperty ControlButtonsVisibleProperty = DependencyProperty.Register(
-            "ControlButtonsVisible", typeof(Visibility), typeof(LayerItem), new PropertyMetadata(System.Windows.Visibility.Hidden));
-
         public Visibility ControlButtonsVisible
         public Visibility ControlButtonsVisible
         {
         {
-            get { return (Visibility) GetValue(ControlButtonsVisibleProperty); }
-            set { SetValue(ControlButtonsVisibleProperty, value); }
+            get => (Visibility) GetValue(ControlButtonsVisibleProperty);
+            set => SetValue(ControlButtonsVisibleProperty, value);
         }
         }
 
 
 
 
-
         public RelayCommand MoveToBackCommand
         public RelayCommand MoveToBackCommand
         {
         {
-            get { return (RelayCommand)GetValue(MoveToBackCommandProperty); }
-            set { SetValue(MoveToBackCommandProperty, value); }
+            get => (RelayCommand) GetValue(MoveToBackCommandProperty);
+            set => SetValue(MoveToBackCommandProperty, value);
         }
         }
 
 
-        // Using a DependencyProperty as the backing store for MoveToBackCommand.  This enables animation, styling, binding, etc...
-        public static readonly DependencyProperty MoveToBackCommandProperty =
-            DependencyProperty.Register("MoveToBackCommand", typeof(RelayCommand), typeof(LayerItem), new PropertyMetadata(default(RelayCommand)));
-
-        public static readonly DependencyProperty MoveToFrontCommandProperty = DependencyProperty.Register(
-            "MoveToFrontCommand", typeof(RelayCommand), typeof(LayerItem), new PropertyMetadata(default(RelayCommand)));
-
         public RelayCommand MoveToFrontCommand
         public RelayCommand MoveToFrontCommand
         {
         {
-            get { return (RelayCommand) GetValue(MoveToFrontCommandProperty); }
-            set { SetValue(MoveToFrontCommandProperty, value); }
+            get => (RelayCommand) GetValue(MoveToFrontCommandProperty);
+            set => SetValue(MoveToFrontCommandProperty, value);
         }
         }
 
 
 
 
@@ -108,7 +98,6 @@ namespace PixiEditor.Views
         private void LayerItem_OnMouseLeave(object sender, MouseEventArgs e)
         private void LayerItem_OnMouseLeave(object sender, MouseEventArgs e)
         {
         {
             ControlButtonsVisible = Visibility.Hidden;
             ControlButtonsVisible = Visibility.Hidden;
-
         }
         }
     }
     }
-}
+}

+ 0 - 2
PixiEditor/Views/MainDrawingPanel.xaml

@@ -3,9 +3,7 @@
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
-             xmlns:local="clr-namespace:PixiEditor.Views"
              xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
              xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
-             xmlns:helpers="clr-namespace:PixiEditor.Helpers"
              xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
              xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
              mc:Ignorable="d" PreviewMouseDown="mainDrawingPanel_MouseDown" PreviewMouseUp="mainDrawingPanel_PreviewMouseUp"
              mc:Ignorable="d" PreviewMouseDown="mainDrawingPanel_MouseDown" PreviewMouseUp="mainDrawingPanel_PreviewMouseUp"
              d:DesignHeight="450" d:DesignWidth="800" x:Name="mainDrawingPanel" PreviewMouseWheel="Zoombox_MouseWheel">
              d:DesignHeight="450" d:DesignWidth="800" x:Name="mainDrawingPanel" PreviewMouseWheel="Zoombox_MouseWheel">

+ 26 - 33
PixiEditor/Views/MainDrawingPanel.xaml.cs

@@ -1,10 +1,9 @@
-using PixiEditor.ViewModels;
-using System;
+using System;
 using System.Windows;
 using System.Windows;
-using System.Windows.Automation;
 using System.Windows.Controls;
 using System.Windows.Controls;
 using System.Windows.Input;
 using System.Windows.Input;
 using PixiEditor.Models.Tools.Tools;
 using PixiEditor.Models.Tools.Tools;
+using PixiEditor.ViewModels;
 using Xceed.Wpf.Toolkit.Core.Input;
 using Xceed.Wpf.Toolkit.Core.Input;
 using Xceed.Wpf.Toolkit.Zoombox;
 using Xceed.Wpf.Toolkit.Zoombox;
 
 
@@ -46,16 +45,24 @@ namespace PixiEditor.Views
         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));
 
 
-        public double ZoomPercentage
+        public double ClickScale;
+
+        public MainDrawingPanel()
         {
         {
-            get { return (double)GetValue(ZoomPercentageProperty); }
-            set { SetValue(ZoomPercentageProperty, value); }
+            InitializeComponent();
+            Zoombox.ZoomToSelectionModifiers = new KeyModifierCollection {KeyModifier.RightAlt};
         }
         }
 
 
-        // 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 double ZoomPercentage
+        {
+            get => (double) GetValue(ZoomPercentageProperty);
+            set => SetValue(ZoomPercentageProperty, value);
+        }
 
 
 
 
         public bool Center
         public bool Center
@@ -105,35 +112,21 @@ namespace PixiEditor.Views
 
 
         private static void ZoomPercentegeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
         private static void ZoomPercentegeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
         {
         {
-            MainDrawingPanel panel = (MainDrawingPanel)d;
-            double percentage = (double)e.NewValue;
-            if(percentage == 100)
-            {
-                panel.SetClickValues();
-            }
-            panel.Zoombox.ZoomTo(panel.ClickScale * ((double)e.NewValue / 100.0));
-        }
-
-        public double ClickScale;
-
-        public MainDrawingPanel()
-        {
-            InitializeComponent();
-            Zoombox.ZoomToSelectionModifiers = new KeyModifierCollection() { KeyModifier.RightAlt };
+            var panel = (MainDrawingPanel) d;
+            var percentage = (double) e.NewValue;
+            if (percentage == 100) panel.SetClickValues();
+            panel.Zoombox.ZoomTo(panel.ClickScale * ((double) e.NewValue / 100.0));
         }
         }
 
 
         private void Zoombox_CurrentViewChanged(object sender, ZoomboxViewChangedEventArgs e)
         private void Zoombox_CurrentViewChanged(object sender, ZoomboxViewChangedEventArgs e)
         {
         {
-            Zoombox.MinScale = 32 / ((FrameworkElement)Item).Width;
+            Zoombox.MinScale = 32 / ((FrameworkElement) Item).Width;
             Zoombox.KeepContentInBounds = !(Zoombox.Scale > Zoombox.MinScale * 35.0);
             Zoombox.KeepContentInBounds = !(Zoombox.Scale > Zoombox.MinScale * 35.0);
         }
         }
 
 
         private void Zoombox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
         private void Zoombox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
         {
         {
-            if (ZoomPercentage == 100)
-            {
-                SetClickValues();
-            }
+            if (ZoomPercentage == 100) SetClickValues();
         }
         }
 
 
         private void SetClickValues()
         private void SetClickValues()
@@ -145,7 +138,7 @@ namespace PixiEditor.Views
 
 
         private void SetZoomOrigin()
         private void SetZoomOrigin()
         {
         {
-            var item = (FrameworkElement)Item;
+            var item = (FrameworkElement) Item;
             if (item == null) return;
             if (item == null) return;
             var mousePos = Mouse.GetPosition(item);
             var mousePos = Mouse.GetPosition(item);
             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));
@@ -153,7 +146,7 @@ namespace PixiEditor.Views
 
 
         private static void OnCenterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
         private static void OnCenterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
         {
         {
-            MainDrawingPanel panel = (MainDrawingPanel) d;
+            var panel = (MainDrawingPanel) d;
             panel.Zoombox.CenterContent();
             panel.Zoombox.CenterContent();
         }
         }
 
 
@@ -172,13 +165,13 @@ namespace PixiEditor.Views
         private void mainDrawingPanel_MouseDown(object sender, MouseButtonEventArgs e)
         private void mainDrawingPanel_MouseDown(object sender, MouseButtonEventArgs e)
         {
         {
             IsUsingZoomTool = ViewModelMain.Current.BitmapManager.SelectedTool is ZoomTool;
             IsUsingZoomTool = ViewModelMain.Current.BitmapManager.SelectedTool is ZoomTool;
-            Mouse.Capture((IInputElement)sender, CaptureMode.SubTree);
+            Mouse.Capture((IInputElement) sender, CaptureMode.SubTree);
             SetClickValues();
             SetClickValues();
         }
         }
 
 
         private void mainDrawingPanel_PreviewMouseUp(object sender, MouseButtonEventArgs e)
         private void mainDrawingPanel_PreviewMouseUp(object sender, MouseButtonEventArgs e)
         {
         {
-            ((IInputElement)sender).ReleaseMouseCapture();
+            ((IInputElement) sender).ReleaseMouseCapture();
         }
         }
     }
     }
 }
 }

Some files were not shown because too many files changed in this diff