diff --git a/Text-Grab/App.xaml.cs b/Text-Grab/App.xaml.cs index 35015e3e..662c6703 100644 --- a/Text-Grab/App.xaml.cs +++ b/Text-Grab/App.xaml.cs @@ -27,7 +27,7 @@ public partial class App : System.Windows.Application { #region Fields - readonly static Settings _defaultSettings = AppUtilities.TextGrabSettings; + private static readonly Settings _defaultSettings = AppUtilities.TextGrabSettings; #endregion Fields @@ -232,7 +232,7 @@ private void appExit(object sender, ExitEventArgs e) Singleton.Instance.WriteHistory(); } - async void appStartup(object sender, StartupEventArgs e) + private async void appStartup(object sender, StartupEventArgs e) { NumberOfRunningInstances = Process.GetProcessesByName("Text-Grab").Length; Current.DispatcherUnhandledException += CurrentDispatcherUnhandledException; diff --git a/Text-Grab/Controls/AddOrRemoveWindow.xaml.cs b/Text-Grab/Controls/AddOrRemoveWindow.xaml.cs index fa691054..5b086626 100644 --- a/Text-Grab/Controls/AddOrRemoveWindow.xaml.cs +++ b/Text-Grab/Controls/AddOrRemoveWindow.xaml.cs @@ -2,7 +2,6 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Input; -using Windows.Graphics.Printing.Workflow; namespace Text_Grab.Controls; diff --git a/Text-Grab/Controls/CollapsibleButton.xaml.cs b/Text-Grab/Controls/CollapsibleButton.xaml.cs index 5620c770..28c2c588 100644 --- a/Text-Grab/Controls/CollapsibleButton.xaml.cs +++ b/Text-Grab/Controls/CollapsibleButton.xaml.cs @@ -1,7 +1,6 @@ using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows; -using System.Windows.Controls; using Text_Grab.Models; using Wpf.Ui.Controls; diff --git a/Text-Grab/Controls/FindAndReplaceWindow.xaml.cs b/Text-Grab/Controls/FindAndReplaceWindow.xaml.cs index afa63844..9b570d1b 100644 --- a/Text-Grab/Controls/FindAndReplaceWindow.xaml.cs +++ b/Text-Grab/Controls/FindAndReplaceWindow.xaml.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; @@ -28,7 +27,7 @@ public partial class FindAndReplaceWindow : FluentWindow public static RoutedCommand ReplaceAllCmd = new(); public static RoutedCommand ReplaceOneCmd = new(); public static RoutedCommand TextSearchCmd = new(); - DispatcherTimer ChangeFindTextTimer = new(); + private DispatcherTimer ChangeFindTextTimer = new(); private MatchCollection? Matches; private string stringFromWindow = ""; private EditTextWindow? textEditWindow; @@ -171,11 +170,11 @@ private void CopyMatchesCmd_Executed(object sender, ExecutedRoutedEventArgs e) StringBuilder stringBuilder = new(); - var selection = ResultsListView.SelectedItems; + IList selection = ResultsListView.SelectedItems; if (selection.Count < 2) selection = ResultsListView.Items; - foreach (var item in selection) + foreach (object? item in selection) if (item is FindResult findResult) stringBuilder.AppendLine(findResult.Text); diff --git a/Text-Grab/Controls/PreviousGrabWindow.xaml.cs b/Text-Grab/Controls/PreviousGrabWindow.xaml.cs index 33550ef9..063fb0f2 100644 --- a/Text-Grab/Controls/PreviousGrabWindow.xaml.cs +++ b/Text-Grab/Controls/PreviousGrabWindow.xaml.cs @@ -20,7 +20,7 @@ public PreviousGrabWindow(Rect rect) Left = rect.Left - borderThickness; Top = rect.Top - borderThickness; - DispatcherTimer timer = new DispatcherTimer(); + DispatcherTimer timer = new(); timer.Interval = TimeSpan.FromMilliseconds(500); timer.Tick += (s, e) => { timer.Stop(); Close(); }; timer.Start(); diff --git a/Text-Grab/Controls/QrCodeWindow.xaml.cs b/Text-Grab/Controls/QrCodeWindow.xaml.cs index d80bccc9..59d96342 100644 --- a/Text-Grab/Controls/QrCodeWindow.xaml.cs +++ b/Text-Grab/Controls/QrCodeWindow.xaml.cs @@ -14,190 +14,189 @@ using static ZXing.Rendering.SvgRenderer; // using static System.Net.Mime.MediaTypeNames; -namespace Text_Grab.Controls +namespace Text_Grab.Controls; + +/// +/// Interaction logic for QrCodeWindow.xaml +/// +public partial class QrCodeWindow : FluentWindow { - /// - /// Interaction logic for QrCodeWindow.xaml - /// - public partial class QrCodeWindow : FluentWindow - { - #region Fields + #region Fields - private IntPtr hBitmap; - private string qrCodeFileName = string.Empty; - private string tempPath = string.Empty; - private DispatcherTimer textDebounceTimer = new(); - private ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; - #endregion Fields + private IntPtr hBitmap; + private string qrCodeFileName = string.Empty; + private string tempPath = string.Empty; + private DispatcherTimer textDebounceTimer = new(); + private ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; + #endregion Fields - #region Constructors + #region Constructors - public QrCodeWindow(string textOfCode) - { - InitializeComponent(); + public QrCodeWindow(string textOfCode) + { + InitializeComponent(); - textOfCode = textOfCode.MakeStringSingleLine(); - QrCodeTextBox.Text = textOfCode; - textDebounceTimer.Interval = new(0, 0, 0, 0, 200); - textDebounceTimer.Tick += TextDebounceTimer_Tick; - SetQrCodeToText(textOfCode); - } + textOfCode = textOfCode.MakeStringSingleLine(); + QrCodeTextBox.Text = textOfCode; + textDebounceTimer.Interval = new(0, 0, 0, 0, 200); + textDebounceTimer.Tick += TextDebounceTimer_Tick; + SetQrCodeToText(textOfCode); + } - private void TextDebounceTimer_Tick(object? sender, EventArgs e) - { - SetQrCodeToText(TextOfCode); - } - #endregion Constructors + private void TextDebounceTimer_Tick(object? sender, EventArgs e) + { + SetQrCodeToText(TextOfCode); + } + #endregion Constructors - #region Properties + #region Properties - public Bitmap? QrBitmap { get; set; } - public string TextOfCode { get; set; } = string.Empty; + public Bitmap? QrBitmap { get; set; } + public string TextOfCode { get; set; } = string.Empty; - #endregion Properties + #endregion Properties - #region Methods + #region Methods - private void CodeImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) + private void CodeImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (QrBitmap is null) + return; + + try { - if (QrBitmap is null) - return; - - try - { - // DoDragDrop with file thumbnail as drag image - var dataObject = DragDataObject.FromFile(tempPath); - dataObject.SetDragImage(hBitmap, QrBitmap.Width, QrBitmap.Height); - DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy); - } - catch - { - // DoDragDrop without drag image - IDataObject dataObject = new DataObject(DataFormats.FileDrop, new[] { tempPath }); - DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy); - } + // DoDragDrop with file thumbnail as drag image + System.Runtime.InteropServices.ComTypes.IDataObject dataObject = DragDataObject.FromFile(tempPath); + dataObject.SetDragImage(hBitmap, QrBitmap.Width, QrBitmap.Height); + DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy); } - - private void CopyButton_Click(object sender, RoutedEventArgs e) + catch { - Clipboard.SetData(DataFormats.Bitmap, QrBitmap); + // DoDragDrop without drag image + IDataObject dataObject = new DataObject(DataFormats.FileDrop, new[] { tempPath }); + DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy); } + } + + private void CopyButton_Click(object sender, RoutedEventArgs e) + { + Clipboard.SetData(DataFormats.Bitmap, QrBitmap); + } + + private void ErrorCorrectionComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) + { + if (sender is not ComboBox comboBox + || comboBox.SelectedItem is not ComboBoxItem selectedItem + || selectedItem.Tag is not string tagLevel) + return; - private void ErrorCorrectionComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) + errorCorrectionLevel = tagLevel switch { - if (sender is not ComboBox comboBox - || comboBox.SelectedItem is not ComboBoxItem selectedItem - || selectedItem.Tag is not string tagLevel) - return; - - errorCorrectionLevel = tagLevel switch - { - "L" => ErrorCorrectionLevel.L, - "M" => ErrorCorrectionLevel.M, - "Q" => ErrorCorrectionLevel.Q, - "H" => ErrorCorrectionLevel.H, - _ => ErrorCorrectionLevel.L - }; - - SetQrCodeToText(); - } + "L" => ErrorCorrectionLevel.L, + "M" => ErrorCorrectionLevel.M, + "Q" => ErrorCorrectionLevel.Q, + "H" => ErrorCorrectionLevel.H, + _ => ErrorCorrectionLevel.L + }; + + SetQrCodeToText(); + } - private void FluentWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) + private void FluentWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) + { + NativeMethods.DeleteObject(hBitmap); + if (File.Exists(tempPath)) { - NativeMethods.DeleteObject(hBitmap); - if (File.Exists(tempPath)) - { - try { File.Delete(tempPath); } - catch { } - } + try { File.Delete(tempPath); } + catch { } } + } - private void QrCodeTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) - { - if (!IsLoaded) - return; + private void QrCodeTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) + { + if (!IsLoaded) + return; - textDebounceTimer.Stop(); - // if (sender is not TextBox senderBox || senderBox.Text is not string textboxString) - // return; + textDebounceTimer.Stop(); + // if (sender is not TextBox senderBox || senderBox.Text is not string textboxString) + // return; - TextOfCode = QrCodeTextBox.Text; - textDebounceTimer.Start(); - } + TextOfCode = QrCodeTextBox.Text; + textDebounceTimer.Start(); + } + + private void SaveButton_Click(object sender, RoutedEventArgs e) + { + if (QrBitmap is null) + return; - private void SaveButton_Click(object sender, RoutedEventArgs e) + SaveFileDialog dialog = new() { - if (QrBitmap is null) - return; + FileName = qrCodeFileName + ".png", + Filter = "Image | *.png", + InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), + RestoreDirectory = true, + }; - SaveFileDialog dialog = new() - { - FileName = qrCodeFileName + ".png", - Filter = "Image | *.png", - InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), - RestoreDirectory = true, - }; + if (dialog.ShowDialog() is not true) + return; - if (dialog.ShowDialog() is not true) - return; + QrBitmap.Save(dialog.FileName); + } - QrBitmap.Save(dialog.FileName); - } + private void SetQrCodeToText(string textOfCode = "") + { + if (!string.IsNullOrEmpty(textOfCode)) + TextOfCode = textOfCode; + + if (string.IsNullOrEmpty(TextOfCode)) + return; - private void SetQrCodeToText(string textOfCode = "") + bool showError = false; + int maxCharLength = 2953; + if (TextOfCode.Length > maxCharLength) { - if (!string.IsNullOrEmpty(textOfCode)) - TextOfCode = textOfCode; - - if (string.IsNullOrEmpty(TextOfCode)) - return; - - bool showError = false; - int maxCharLength = 2953; - if (TextOfCode.Length > maxCharLength) - { - TextOfCode = TextOfCode.Substring(0, maxCharLength); - showError = true; - } - QrBitmap = BarcodeUtilities.GetQrCodeForText(TextOfCode, errorCorrectionLevel); - CodeImage.ToolTip = textOfCode; - CodeImage.Source = ImageMethods.BitmapToImageSource(QrBitmap); - - if (showError) - LengthErrorTextBlock.Visibility = Visibility.Visible; - - int maxLength = 50; - UiTitleBar.Title = $"QR Code: {TextOfCode.Truncate(30)}"; - int trimLength = TextOfCode.Length < maxLength ? TextOfCode.Length : maxLength; - qrCodeFileName = $"QR-{TextOfCode.Substring(0, trimLength).ReplaceReservedCharacters()}"; - tempPath = Path.Combine(Path.GetTempPath(), qrCodeFileName + ".png"); - - QrBitmap.Save(tempPath, ImageFormat.Png); - hBitmap = QrBitmap.GetHbitmap(); + TextOfCode = TextOfCode[..maxCharLength]; + showError = true; } - private async void SvgButton_Click(object sender, RoutedEventArgs e) - { - if (QrBitmap is null) - return; + QrBitmap = BarcodeUtilities.GetQrCodeForText(TextOfCode, errorCorrectionLevel); + CodeImage.ToolTip = textOfCode; + CodeImage.Source = ImageMethods.BitmapToImageSource(QrBitmap); + + if (showError) + LengthErrorTextBlock.Visibility = Visibility.Visible; + + int maxLength = 50; + UiTitleBar.Title = $"QR Code: {TextOfCode.Truncate(30)}"; + int trimLength = TextOfCode.Length < maxLength ? TextOfCode.Length : maxLength; + qrCodeFileName = $"QR-{TextOfCode[..trimLength].ReplaceReservedCharacters()}"; + tempPath = Path.Combine(Path.GetTempPath(), qrCodeFileName + ".png"); - SaveFileDialog dialog = new() - { - FileName = qrCodeFileName + ".svg", - Filter = "SVG | *.svg", - InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), - RestoreDirectory = true, - }; + QrBitmap.Save(tempPath, ImageFormat.Png); + hBitmap = QrBitmap.GetHbitmap(); + } + private async void SvgButton_Click(object sender, RoutedEventArgs e) + { + if (QrBitmap is null) + return; - if (dialog.ShowDialog() is not true) - return; + SaveFileDialog dialog = new() + { + FileName = qrCodeFileName + ".svg", + Filter = "SVG | *.svg", + InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), + RestoreDirectory = true, + }; - SvgImage svgImage = BarcodeUtilities.GetSvgQrCodeForText(TextOfCode, errorCorrectionLevel); + if (dialog.ShowDialog() is not true) + return; - if (string.IsNullOrWhiteSpace(svgImage.Content)) - return; + SvgImage svgImage = BarcodeUtilities.GetSvgQrCodeForText(TextOfCode, errorCorrectionLevel); - await FileUtilities.SaveTextFile(svgImage.Content, dialog.FileName, FileStorageKind.Absolute); - } - #endregion Methods + if (string.IsNullOrWhiteSpace(svgImage.Content)) + return; + + await FileUtilities.SaveTextFile(svgImage.Content, dialog.FileName, FileStorageKind.Absolute); } + #endregion Methods } diff --git a/Text-Grab/Controls/ShortcutControl.xaml.cs b/Text-Grab/Controls/ShortcutControl.xaml.cs index 53904cb9..9eebb6f8 100644 --- a/Text-Grab/Controls/ShortcutControl.xaml.cs +++ b/Text-Grab/Controls/ShortcutControl.xaml.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Controls; @@ -40,10 +39,8 @@ public string ShortcutName public static readonly DependencyProperty ShortcutNameProperty = DependencyProperty.Register("ShortcutName", typeof(string), typeof(ShortcutControl), new PropertyMetadata("shortcutName")); - - bool isRecording = false; - - string previousSequence = string.Empty; + private bool isRecording = false; + private string previousSequence = string.Empty; public bool HasModifier { get; set; } = false; public bool HasLetter { get; set; } = false; diff --git a/Text-Grab/Controls/WordBorder.xaml.cs b/Text-Grab/Controls/WordBorder.xaml.cs index 1d25761f..19fc45f4 100644 --- a/Text-Grab/Controls/WordBorder.xaml.cs +++ b/Text-Grab/Controls/WordBorder.xaml.cs @@ -7,10 +7,8 @@ using System.Windows.Media; using System.Windows.Threading; using Text_Grab.Models; -using Text_Grab.Properties; using Text_Grab.Utilities; using Text_Grab.Views; -using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window; namespace Text_Grab.Controls; @@ -28,10 +26,10 @@ public partial class WordBorder : UserControl, INotifyPropertyChanged public static RoutedCommand MergeWordsCommand = new(); private int contextMenuBaseSize; - private SolidColorBrush contrastingForeground = new SolidColorBrush(Colors.White); + private SolidColorBrush contrastingForeground = new(Colors.White); private DispatcherTimer debounceTimer = new(); private double left = 0; - private SolidColorBrush matchingBackground = new SolidColorBrush(Colors.Black); + private SolidColorBrush matchingBackground = new(Colors.Black); private double top = 0; #endregion Fields @@ -201,7 +199,7 @@ public void SetAsBarcode() EditWordTextBox.Height = this.Height - 2; EditWordTextBox.FontSize = 14; - if (Uri.TryCreate(Word, UriKind.Absolute, out var uri)) + if (Uri.TryCreate(Word, UriKind.Absolute, out Uri? uri)) EditWordTextBox.Background = new SolidColorBrush(Colors.Blue); } @@ -248,7 +246,7 @@ private void EditWordTextBox_ContextMenuOpening(object sender, ContextMenuEventA textBoxContextMenu.Items.RemoveAt(contextMenuBaseSize); } - if (Uri.TryCreate(Word, UriKind.Absolute, out var uri)) + if (Uri.TryCreate(Word, UriKind.Absolute, out Uri? uri)) { string headerText = $"Try to go to: {Word}"; int maxLength = 36; @@ -310,7 +308,7 @@ private void SizeHandle_MouseDown(object sender, MouseButtonEventArgs e) { if (sender is not FrameworkElement fe) return; - Enum.TryParse(typeof(Side), fe.Tag.ToString(), out var side); + Enum.TryParse(typeof(Side), fe.Tag.ToString(), out object? side); if (side is not Side sideEnum) return; diff --git a/Text-Grab/Controls/ZoomBorder.cs b/Text-Grab/Controls/ZoomBorder.cs index a3a30fa2..4f55be2d 100644 --- a/Text-Grab/Controls/ZoomBorder.cs +++ b/Text-Grab/Controls/ZoomBorder.cs @@ -22,7 +22,7 @@ private TranslateTransform GetTranslateTransform(UIElement element) => (TranslateTransform)((TransformGroup)element.RenderTransform) .Children.First(tr => tr is TranslateTransform); - private ScaleTransform GetScaleTransform(UIElement element) => + private ScaleTransform GetScaleTransform(UIElement element) => (ScaleTransform)((TransformGroup)element.RenderTransform) .Children.First(tr => tr is ScaleTransform); @@ -132,7 +132,7 @@ private void Child_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) Cursor = Cursors.Arrow; } - void Child_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) + private void Child_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) { } diff --git a/Text-Grab/DesktopNotificationManagerCompat.cs b/Text-Grab/DesktopNotificationManagerCompat.cs index 302c1b0f..e5c1a565 100644 --- a/Text-Grab/DesktopNotificationManagerCompat.cs +++ b/Text-Grab/DesktopNotificationManagerCompat.cs @@ -100,7 +100,7 @@ private static void RegisterComServer(String exePath) { // We register the EXE to start up when the notification is activated string regString = String.Format("SOFTWARE\\Classes\\CLSID\\{{{0}}}", typeof(T).GUID); - using (var key = Registry.CurrentUser.CreateSubKey(regString)) + using (RegistryKey key = Registry.CurrentUser.CreateSubKey(regString)) { // Include a flag so we know this was a toast activation and should wait for COM to process // We also wrap EXE path in quotes for extra security @@ -111,7 +111,7 @@ private static void RegisterComServer(String exePath) { // For elevated apps, we need to ensure they'll activate in existing running process by adding // some values in local machine - using (var key = Registry.LocalMachine.CreateSubKey(regString)) + using (RegistryKey key = Registry.LocalMachine.CreateSubKey(regString)) { // Same as above, except also including AppId to link to our AppId entry below key.SetValue("LocalServer32", '"' + exePath + '"' + " " + TOAST_ACTIVATED_LAUNCH_ARG); @@ -120,7 +120,7 @@ private static void RegisterComServer(String exePath) // This tells COM to match any client, so Action Center will activate our elevated process. // More info: https://docs.microsoft.com/windows/win32/com/runas - using (var key = Registry.LocalMachine.CreateSubKey(String.Format("SOFTWARE\\Classes\\AppID\\{{{0}}}", typeof(T).GUID))) + using (RegistryKey key = Registry.LocalMachine.CreateSubKey(String.Format("SOFTWARE\\Classes\\AppID\\{{{0}}}", typeof(T).GUID))) { key.SetValue("RunAs", "Interactive User"); } @@ -135,7 +135,7 @@ public static void RegisterActivator() where T : NotificationActivator, new() { // Big thanks to FrecherxDachs for figuring out the following code which works in .NET Core 3: https://github.com/FrecherxDachs/UwpNotificationNetCoreTest - var uuid = typeof(T).GUID; + Guid uuid = typeof(T).GUID; uint _cookie; CoRegisterClassObject(uuid, new NotificationActivatorClassFactory(), CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, out _cookie); @@ -160,7 +160,7 @@ private interface IClassFactory private const int CLSCTX_LOCAL_SERVER = 4; private const int REGCLS_MULTIPLEUSE = 1; private const int S_OK = 0; - private static readonly Guid IUnknownGuid = new Guid("00000000-0000-0000-C000-000000000046"); + private static readonly Guid IUnknownGuid = new("00000000-0000-0000-C000-000000000046"); private class NotificationActivatorClassFactory : IClassFactory where T : NotificationActivator, new() { @@ -277,10 +277,10 @@ private static bool IsElevated /// private class DesktopBridgeHelpers { - const long APPMODEL_ERROR_NO_PACKAGE = 15700L; + private const long APPMODEL_ERROR_NO_PACKAGE = 15700L; [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - static extern int GetCurrentPackageFullName(ref int packageFullNameLength, StringBuilder packageFullName); + private static extern int GetCurrentPackageFullName(ref int packageFullNameLength, StringBuilder packageFullName); private static bool? _isRunningAsUwp; public static bool IsRunningAsUwp() @@ -294,7 +294,7 @@ public static bool IsRunningAsUwp() else { int length = 0; - StringBuilder sb = new StringBuilder(0); + StringBuilder sb = new(0); int result = GetCurrentPackageFullName(ref length, sb); sb = new StringBuilder(length); @@ -492,7 +492,7 @@ public IEnumerator> GetEnumerator() public bool TryGetValue(string key, out string value) { - foreach (var item in _data) + foreach (NOTIFICATION_USER_INPUT_DATA item in _data) { if (item.Key == key) { diff --git a/Text-Grab/Enums.cs b/Text-Grab/Enums.cs index 9f892d44..ea00f4a3 100644 --- a/Text-Grab/Enums.cs +++ b/Text-Grab/Enums.cs @@ -83,4 +83,4 @@ public enum ScrollBehavior None = 0, Resize = 1, Zoom = 2, -} \ No newline at end of file +} diff --git a/Text-Grab/Extensions/ControlExtensions.cs b/Text-Grab/Extensions/ControlExtensions.cs index 038b7131..ec80e918 100644 --- a/Text-Grab/Extensions/ControlExtensions.cs +++ b/Text-Grab/Extensions/ControlExtensions.cs @@ -21,12 +21,12 @@ public static double GetHorizontalScaleFactor(this Viewbox viewbox) public static Rect GetAbsolutePlacement(this FrameworkElement element, bool relativeToScreen = false) { - var absolutePos = element.PointToScreen(new System.Windows.Point(0, 0)); + Point absolutePos = element.PointToScreen(new System.Windows.Point(0, 0)); if (relativeToScreen) { return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight); } - var posMW = Application.Current.MainWindow.PointToScreen(new System.Windows.Point(0, 0)); + Point posMW = Application.Current.MainWindow.PointToScreen(new System.Windows.Point(0, 0)); absolutePos = new System.Windows.Point(absolutePos.X - posMW.X, absolutePos.Y - posMW.Y); return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight); } diff --git a/Text-Grab/Extensions/ImageExtensions.cs b/Text-Grab/Extensions/ImageExtensions.cs index 055a9851..be8c0720 100644 --- a/Text-Grab/Extensions/ImageExtensions.cs +++ b/Text-Grab/Extensions/ImageExtensions.cs @@ -27,16 +27,16 @@ internal static RotateFlipType GetRotateFlipType(this Image img) return RotateFlipType.RotateNoneFlipNone; int val = BitConverter.ToUInt16(propValue, 0); - var rot = RotateFlipType.RotateNoneFlipNone; + RotateFlipType rot = RotateFlipType.RotateNoneFlipNone; - if (val == 3 || val == 4) + if (val is 3 or 4) rot = RotateFlipType.Rotate180FlipNone; - else if (val == 5 || val == 6) + else if (val is 5 or 6) rot = RotateFlipType.Rotate90FlipNone; - else if (val == 7 || val == 8) + else if (val is 7 or 8) rot = RotateFlipType.Rotate270FlipNone; - if (val == 2 || val == 4 || val == 5 || val == 7) + if (val is 2 or 4 or 5 or 7) rot |= RotateFlipType.RotateNoneFlipX; return rot; diff --git a/Text-Grab/Extensions/LanguageExtensions.cs b/Text-Grab/Extensions/LanguageExtensions.cs index 5d3d30e5..4f6fc4cf 100644 --- a/Text-Grab/Extensions/LanguageExtensions.cs +++ b/Text-Grab/Extensions/LanguageExtensions.cs @@ -27,7 +27,7 @@ public static bool IsRightToLeft(this Language language) public static bool IsLatinBased(this Language language) { // List of Latin-based languages - List LatinLanguages = new List() + List LatinLanguages = new() { "en", // English "es", // Spanish diff --git a/Text-Grab/Extensions/SettingsStorageExtensions.cs b/Text-Grab/Extensions/SettingsStorageExtensions.cs index bb873788..0c28c87c 100644 --- a/Text-Grab/Extensions/SettingsStorageExtensions.cs +++ b/Text-Grab/Extensions/SettingsStorageExtensions.cs @@ -58,7 +58,7 @@ public static void SaveString(this ApplicationDataContainer settings, string key { if (settings.Values.TryGetValue(key, out object? obj)) return await Json.ToObjectAsync((string)obj); - + return default; } @@ -68,7 +68,7 @@ public static async Task SaveFileAsync(this StorageFolder folder, b if (string.IsNullOrEmpty(fileName)) throw new ArgumentException("File name is null or empty. Specify a valid file name", nameof(fileName)); - + StorageFile storageFile = await folder.CreateFileAsync(fileName, options); await FileIO.WriteBytesAsync(storageFile, content); return storageFile; @@ -92,7 +92,7 @@ public static async Task SaveFileAsync(this StorageFolder folder, b { if (file == null) return null; - + using IRandomAccessStream stream = await file.OpenReadAsync(); using DataReader reader = new(stream.GetInputStreamAt(0)); await reader.LoadAsync((uint)stream.Size); diff --git a/Text-Grab/Extensions/ShapeExtensions.cs b/Text-Grab/Extensions/ShapeExtensions.cs index 22827206..d666960b 100644 --- a/Text-Grab/Extensions/ShapeExtensions.cs +++ b/Text-Grab/Extensions/ShapeExtensions.cs @@ -50,12 +50,12 @@ public static Rect GetScaleSizeByFraction(this Rect rect, Double scaleFactor) public static bool IsGood(this Rect rect) { - if (double.IsNaN(rect.X) + if (double.IsNaN(rect.X) || double.IsNegativeInfinity(rect.X) || double.IsPositiveInfinity(rect.X)) return false; - - if (double.IsNaN(rect.Y) + + if (double.IsNaN(rect.Y) || double.IsNegativeInfinity(rect.Y) || double.IsPositiveInfinity(rect.Y)) return false; diff --git a/Text-Grab/Models/DragDataObject.cs b/Text-Grab/Models/DragDataObject.cs index a5adc178..55d861df 100644 --- a/Text-Grab/Models/DragDataObject.cs +++ b/Text-Grab/Models/DragDataObject.cs @@ -11,7 +11,7 @@ namespace Text_Grab.Models; // based on: https://stackoverflow.com/questions/61041282/showing-image-thumbnail-with-mouse-cursor-while-dragging/61148788#61148788 public static class DragDataObject { - private static readonly Guid DataObject = new Guid("b8c0bd9f-ed24-455c-83e6-d5390c4fe8c4"); + private static readonly Guid DataObject = new("b8c0bd9f-ed24-455c-83e6-d5390c4fe8c4"); public static IDataObject FromFile(string filePath) { @@ -25,7 +25,7 @@ public static void SetDragImage(this IDataObject dataObject, IntPtr hBitmap, int ArgumentNullException.ThrowIfNull(dataObject); IDragSourceHelper dragDropHelper = (IDragSourceHelper)new DragDropHelper(); - ShDragImage dragImage = new ShDragImage + ShDragImage dragImage = new() { HBmpDragImage = hBitmap, SizeDragImage = new Size(width, height), @@ -81,7 +81,7 @@ private interface IDragSourceHelper return null; } - Bitmap bitmap = new Bitmap(source.PixelWidth, source.PixelHeight, DrawingImaging.PixelFormat.Format32bppArgb); + Bitmap bitmap = new(source.PixelWidth, source.PixelHeight, DrawingImaging.PixelFormat.Format32bppArgb); DrawingImaging.BitmapData bitmapData = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), DrawingImaging.ImageLockMode.WriteOnly, DrawingImaging.PixelFormat.Format32bppArgb); source.CopyPixels(System.Windows.Int32Rect.Empty, bitmapData.Scan0, bitmapData.Height * bitmapData.Stride, bitmapData.Stride); diff --git a/Text-Grab/Models/OcrOutput.cs b/Text-Grab/Models/OcrOutput.cs index 07677e46..27232161 100644 --- a/Text-Grab/Models/OcrOutput.cs +++ b/Text-Grab/Models/OcrOutput.cs @@ -2,7 +2,6 @@ using Text_Grab.Properties; using Text_Grab.Utilities; using Windows.Globalization; -using Windows.Media.Ocr; namespace Text_Grab.Models; diff --git a/Text-Grab/Models/ResultTable.cs b/Text-Grab/Models/ResultTable.cs index 669311b9..3a07cd9a 100644 --- a/Text-Grab/Models/ResultTable.cs +++ b/Text-Grab/Models/ResultTable.cs @@ -41,10 +41,10 @@ public ResultTable(ref List wordBorders, DpiScale dpiScale) Rectangle bordersBorder = new(); if (wordBorders.Count > 0) { - var leftsMin = wordBorders.Select(x => x.Left).Min(); - var topsMin = wordBorders.Select(x => x.Top).Min(); - var rightsMax = wordBorders.Select(x => x.Right).Max(); - var bottomsMax = wordBorders.Select(x => x.Bottom).Max(); + double leftsMin = wordBorders.Select(x => x.Left).Min(); + double topsMin = wordBorders.Select(x => x.Top).Min(); + double rightsMax = wordBorders.Select(x => x.Right).Max(); + double bottomsMax = wordBorders.Select(x => x.Bottom).Max(); bordersBorder = new() { @@ -72,13 +72,13 @@ private void ParseRowAndColumnLines() if (Rows.Count >= 1) { topBound = (int)Rows[0].Top; - bottomBound = (int)Rows[Rows.Count - 1].Bottom; + bottomBound = (int)Rows[^1].Bottom; } if (Columns.Count >= 1) { leftBound = (int)Columns[0].Left; - rightBound = (int)Columns[Columns.Count - 1].Right; + rightBound = (int)Columns[^1].Right; } BoundingRect = new() @@ -333,7 +333,7 @@ private static List FindOutlierRowIds( Canvas.SetLeft(rowBorder, tableBoundingRect.X); Canvas.SetTop(rowBorder, row.Top); - Rect rowRect = new Rect(tableBoundingRect.X, row.Top, rowBorder.Width, rowBorder.Height); + Rect rowRect = new(tableBoundingRect.X, row.Top, rowBorder.Width, rowBorder.Height); foreach (WordBorder wb in wordBorders) { @@ -375,7 +375,7 @@ private static List FindOutlierColumnIds( Canvas.SetLeft(columnBorder, column.Left); Canvas.SetTop(columnBorder, tableBoundingRect.Y); - Rect columnRect = new Rect(column.Left, tableBoundingRect.Y, columnBorder.Width, columnBorder.Height); + Rect columnRect = new(column.Left, tableBoundingRect.Y, columnBorder.Width, columnBorder.Height); foreach (WordBorder wb in wordBorders) { if (wb.IntersectsWith(columnRect)) diff --git a/Text-Grab/Models/ShortcutKeySet.cs b/Text-Grab/Models/ShortcutKeySet.cs index 9a0ee272..be0544e4 100644 --- a/Text-Grab/Models/ShortcutKeySet.cs +++ b/Text-Grab/Models/ShortcutKeySet.cs @@ -41,14 +41,14 @@ public ShortcutKeySet(string shortcutsAsString) if (!shortcutsAsString.Contains('-')) return; - var enabledSplitKeys = shortcutsAsString.Split('-'); + string[] enabledSplitKeys = shortcutsAsString.Split('-'); bool parsedEnabledSuccessfully = bool.TryParse(enabledSplitKeys[0], out bool parsedEnabled); if (!parsedEnabledSuccessfully || enabledSplitKeys.Length < 2) return; - var splitUpString = enabledSplitKeys[1].Split('+'); + string[] splitUpString = enabledSplitKeys[1].Split('+'); string? keyString = splitUpString.LastOrDefault(); if (Enum.TryParse(keyString, out Key parsedKey)) diff --git a/Text-Grab/NativeMethods.cs b/Text-Grab/NativeMethods.cs index a1feff36..cb15c71c 100644 --- a/Text-Grab/NativeMethods.cs +++ b/Text-Grab/NativeMethods.cs @@ -5,7 +5,7 @@ internal static partial class NativeMethods { // See http://msdn.microsoft.com/en-us/library/ms649021%28v=vs.85%29.aspx public const int WM_CLIPBOARDUPDATE = 0x031D; - public static IntPtr HWND_MESSAGE = new IntPtr(-3); + public static IntPtr HWND_MESSAGE = new(-3); // See http://msdn.microsoft.com/en-us/library/ms632599%28VS.85%29.aspx#message_only [LibraryImport("user32.dll", SetLastError = true)] diff --git a/Text-Grab/OSInterop.cs b/Text-Grab/OSInterop.cs index da4dc134..21b594fa 100644 --- a/Text-Grab/OSInterop.cs +++ b/Text-Grab/OSInterop.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.InteropServices; -static partial class OSInterop +internal static partial class OSInterop { [LibraryImport("user32.dll")] public static partial int GetSystemMetrics(int smIndex); @@ -38,8 +38,8 @@ public struct RECT public class MONITORINFOEX { public int cbSize = Marshal.SizeOf(typeof(MONITORINFOEX)); - public RECT rcMonitor = new RECT(); - public RECT rcWork = new RECT(); + public RECT rcMonitor = new(); + public RECT rcWork = new(); [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public char[] szDevice = new char[32]; public int dwFlags; diff --git a/Text-Grab/Pages/GeneralSettings.xaml.cs b/Text-Grab/Pages/GeneralSettings.xaml.cs index f340e2c2..3f116592 100644 --- a/Text-Grab/Pages/GeneralSettings.xaml.cs +++ b/Text-Grab/Pages/GeneralSettings.xaml.cs @@ -247,7 +247,7 @@ private void HistorySwitch_Checked(object sender, RoutedEventArgs e) { if (!settingsSet) return; - + DefaultSettings.UseHistory = true; } @@ -311,7 +311,7 @@ private async void StartupOnLoginCheckBox_Checked(object sender, RoutedEventArgs { if (!settingsSet) return; - + DefaultSettings.StartupOnLogin = true; await ImplementAppOptions.ImplementStartupOption(true); } diff --git a/Text-Grab/Pages/KeysSettings.xaml.cs b/Text-Grab/Pages/KeysSettings.xaml.cs index 84cbb3ac..4ec8532c 100644 --- a/Text-Grab/Pages/KeysSettings.xaml.cs +++ b/Text-Grab/Pages/KeysSettings.xaml.cs @@ -94,7 +94,7 @@ private bool HotKeysAllDifferent() return false; return true; - } + } private void Page_Loaded(object sender, RoutedEventArgs e) { diff --git a/Text-Grab/Services/HistoryService.cs b/Text-Grab/Services/HistoryService.cs index 10bd7b77..5271b12d 100644 --- a/Text-Grab/Services/HistoryService.cs +++ b/Text-Grab/Services/HistoryService.cs @@ -250,11 +250,11 @@ public void WriteHistory() private static async Task> LoadHistory(string fileName) { - string rawText = await FileUtilities.GetTextFileAsync($"{fileName}.json",FileStorageKind.WithHistory); + string rawText = await FileUtilities.GetTextFileAsync($"{fileName}.json", FileStorageKind.WithHistory); if (string.IsNullOrWhiteSpace(rawText)) return new List(); - var tempHistory = JsonSerializer.Deserialize>(rawText); + List? tempHistory = JsonSerializer.Deserialize>(rawText); if (tempHistory is List jsonList && jsonList.Count > 0) return tempHistory; diff --git a/Text-Grab/Services/SettingsService.cs b/Text-Grab/Services/SettingsService.cs index 05c2429e..fd1cddd8 100644 --- a/Text-Grab/Services/SettingsService.cs +++ b/Text-Grab/Services/SettingsService.cs @@ -47,7 +47,7 @@ private void MigrateLocalSettingsToClassic() throw; #endif } - + } } diff --git a/Text-Grab/TextGrabNotificationActivator.cs b/Text-Grab/TextGrabNotificationActivator.cs index f9e077a6..2ab367cb 100644 --- a/Text-Grab/TextGrabNotificationActivator.cs +++ b/Text-Grab/TextGrabNotificationActivator.cs @@ -1,27 +1,26 @@ using System; using System.Runtime.InteropServices; -namespace Text_Grab +namespace Text_Grab; + +// The GUID CLSID must be unique to your app. Create a new GUID if copying this code. +[ClassInterface(ClassInterfaceType.None)] +[ComSourceInterfaces(typeof(INotificationActivationCallback))] +[Guid("215d64d2-031c-33c7-96e3-61794cd1ee61"), ComVisible(true)] +public class TextGrabNotificationActivator : NotificationActivator { - // The GUID CLSID must be unique to your app. Create a new GUID if copying this code. - [ClassInterface(ClassInterfaceType.None)] - [ComSourceInterfaces(typeof(INotificationActivationCallback))] - [Guid("215d64d2-031c-33c7-96e3-61794cd1ee61"), ComVisible(true)] - public class TextGrabNotificationActivator : NotificationActivator + public override void OnActivated(string invokedArgs, NotificationUserInput userInput, string appUserModelId) { - public override void OnActivated(string invokedArgs, NotificationUserInput userInput, string appUserModelId) + System.Windows.Application.Current.Dispatcher.Invoke(delegate { - System.Windows.Application.Current.Dispatcher.Invoke(delegate + // Tapping on the top-level header launches with empty args + if (invokedArgs.Length != 0) { - // Tapping on the top-level header launches with empty args - if (invokedArgs.Length != 0) - { - // Perform a normal launch - EditTextWindow mtw = new EditTextWindow(invokedArgs); - mtw.Show(); - return; - } - }); - } + // Perform a normal launch + EditTextWindow mtw = new(invokedArgs); + mtw.Show(); + return; + } + }); } } diff --git a/Text-Grab/UndoRedoOperations/AddWordBorder.cs b/Text-Grab/UndoRedoOperations/AddWordBorder.cs index 889ffc9a..cfae4708 100644 --- a/Text-Grab/UndoRedoOperations/AddWordBorder.cs +++ b/Text-Grab/UndoRedoOperations/AddWordBorder.cs @@ -1,13 +1,12 @@ using System.Collections.Generic; using System.Windows.Controls; using Text_Grab.Controls; -using Text_Grab.UndoRedoOperations; namespace Text_Grab.UndoRedoOperations; internal class AddWordBorder : Operation, IUndoRedoOperation { - public AddWordBorder(uint transactionId, WordBorder wordBorder, + public AddWordBorder(uint transactionId, WordBorder wordBorder, Canvas canvas, ICollection wordBorders) : base(transactionId) { WordBorder = wordBorder; diff --git a/Text-Grab/UndoRedoOperations/ChangeWord.cs b/Text-Grab/UndoRedoOperations/ChangeWord.cs index 9d125b9f..2ba2d47c 100644 --- a/Text-Grab/UndoRedoOperations/ChangeWord.cs +++ b/Text-Grab/UndoRedoOperations/ChangeWord.cs @@ -1,19 +1,16 @@ -using System.Collections.Generic; -using System.Windows.Controls; -using Text_Grab.Controls; -using Text_Grab.UndoRedoOperations; +using Text_Grab.Controls; namespace Text_Grab.UndoRedoOperations; internal class ChangeWord : Operation, IUndoRedoOperation { - public ChangeWord(uint transactionId, WordBorder wordBorder, + public ChangeWord(uint transactionId, WordBorder wordBorder, string oldWord, string newWord) : base(transactionId) { WordBorder = wordBorder; OldWord = oldWord; NewWord = newWord; - + } private WordBorder WordBorder; diff --git a/Text-Grab/UndoRedoOperations/RemoveWordBorder.cs b/Text-Grab/UndoRedoOperations/RemoveWordBorder.cs index 9d1794c5..c8175cc2 100644 --- a/Text-Grab/UndoRedoOperations/RemoveWordBorder.cs +++ b/Text-Grab/UndoRedoOperations/RemoveWordBorder.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Windows.Controls; using Text_Grab.Controls; -using Text_Grab.UndoRedoOperations; namespace Text_Grab.UndoRedoOperations; @@ -16,7 +15,7 @@ public RemoveWordBorder(uint transactionId, List removingWordBorders } private List RemovingWordBorders; - + private Canvas Canvas; private ICollection WordBorders; diff --git a/Text-Grab/UndoRedoOperations/UndoRedo.cs b/Text-Grab/UndoRedoOperations/UndoRedo.cs index ae39b07c..ca356022 100644 --- a/Text-Grab/UndoRedoOperations/UndoRedo.cs +++ b/Text-Grab/UndoRedoOperations/UndoRedo.cs @@ -1,9 +1,8 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; namespace Text_Grab.UndoRedoOperations; -class UndoRedo +internal class UndoRedo { public const int UndoRedoTransactionCapacity = 100; @@ -112,12 +111,12 @@ public void Undo() if (UndoStack.Count == 0 || UndoStack.Last is null) return; - var operationNode = UndoStack.Last; - var currentTransactionId = operationNode.Value.TransactionId; + LinkedListNode? operationNode = UndoStack.Last; + uint currentTransactionId = operationNode.Value.TransactionId; while (operationNode != null && operationNode.Value.TransactionId == currentTransactionId) { - var prev = operationNode.Previous; - var operation = operationNode.Value; + LinkedListNode? prev = operationNode.Previous; + IUndoRedoOperation operation = operationNode.Value; operation.Undo(); // Add operation into redo stack. @@ -137,12 +136,12 @@ public void Redo() if (RedoStack.Count == 0 || RedoStack.Last is null) return; - var operationNode = RedoStack.Last; - var currentTransactionId = operationNode.Value.TransactionId; + LinkedListNode? operationNode = RedoStack.Last; + uint currentTransactionId = operationNode.Value.TransactionId; while (operationNode != null && operationNode.Value.TransactionId == currentTransactionId) { - var prev = operationNode.Previous; - var operation = RedoStack.Last.Value; + LinkedListNode? prev = operationNode.Previous; + IUndoRedoOperation operation = RedoStack.Last.Value; operation.Redo(); // Add operation into Undo Stack. diff --git a/Text-Grab/Utilities/BarcodeUtilities.cs b/Text-Grab/Utilities/BarcodeUtilities.cs index dad9b505..40385f79 100644 --- a/Text-Grab/Utilities/BarcodeUtilities.cs +++ b/Text-Grab/Utilities/BarcodeUtilities.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; using System.Drawing; -using System.Windows.Media; using Text_Grab.Models; using ZXing; using ZXing.Common; @@ -29,7 +26,7 @@ public static OcrOutput TryToReadBarcodes(Bitmap bitmap) if (result is not null) resultString = result.Text; - return new OcrOutput () + return new OcrOutput() { Kind = OcrOutputKind.Barcode, RawOutput = resultString, @@ -79,7 +76,7 @@ public static SvgImage GetSvgQrCodeForText(string text, ErrorCorrectionLevel cor }; encodingOptions.Hints.Add(ZXing.EncodeHintType.ERROR_CORRECTION, correctionLevel); barcodeWriter.Options = encodingOptions; - + SvgImage svg = barcodeWriter.Write(text); return svg; diff --git a/Text-Grab/Utilities/ClipboardUtilities.cs b/Text-Grab/Utilities/ClipboardUtilities.cs index ec3a528d..833e09ba 100644 --- a/Text-Grab/Utilities/ClipboardUtilities.cs +++ b/Text-Grab/Utilities/ClipboardUtilities.cs @@ -79,7 +79,7 @@ public static (bool, ImageSource?) TryGetImageFromClipboard() trimmedData = CleanTeamsBase64Image(trimmedData); // used some code from https://github.com/veler/DevToys - string base64 = trimmedData.Substring(trimmedData.IndexOf(',') + 1); + string base64 = trimmedData[(trimmedData.IndexOf(',') + 1)..]; byte[] bytes = Convert.FromBase64String(base64); // cannot dispose of memoryStream or the BitmapImage is empty when the view trys to render @@ -127,7 +127,7 @@ private static string CleanTeamsBase64Image(string dirtyTeamsString) return sb.ToString(); } - static string base64ImageExtension(ref string base64String) + private static string base64ImageExtension(ref string base64String) { // Copied this portion of the code from https://github.com/veler/DevToys if (base64String!.StartsWith("data:image/png;base64,", StringComparison.OrdinalIgnoreCase)) diff --git a/Text-Grab/Utilities/CursorClipper.cs b/Text-Grab/Utilities/CursorClipper.cs index f9511116..9e38ded1 100644 --- a/Text-Grab/Utilities/CursorClipper.cs +++ b/Text-Grab/Utilities/CursorClipper.cs @@ -17,7 +17,7 @@ public static bool ClipCursor(FrameworkElement element) { const double dpi96 = 96.0; - var topLeft = element.PointToScreen(new Point(0, 0)); + Point topLeft = element.PointToScreen(new Point(0, 0)); PresentationSource source = PresentationSource.FromVisual(element); if (source?.CompositionTarget == null) @@ -28,10 +28,10 @@ public static bool ClipCursor(FrameworkElement element) double dpiX = dpi96 * source.CompositionTarget.TransformToDevice.M11; double dpiY = dpi96 * source.CompositionTarget.TransformToDevice.M22; - var width = (int)((element.ActualWidth + 1) * dpiX / dpi96); - var height = (int)((element.ActualHeight + 1) * dpiY / dpi96); + int width = (int)((element.ActualWidth + 1) * dpiX / dpi96); + int height = (int)((element.ActualHeight + 1) * dpiY / dpi96); - OSInterop.RECT rect = new OSInterop.RECT + OSInterop.RECT rect = new() { left = (int)topLeft.X, top = (int)topLeft.Y, diff --git a/Text-Grab/Utilities/CustomBottomBarUtilities.cs b/Text-Grab/Utilities/CustomBottomBarUtilities.cs index 6310d034..90293561 100644 --- a/Text-Grab/Utilities/CustomBottomBarUtilities.cs +++ b/Text-Grab/Utilities/CustomBottomBarUtilities.cs @@ -3,12 +3,10 @@ using System.Reflection; using System.Text.Json; using System.Windows; -using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Text_Grab.Controls; using Text_Grab.Models; -using Text_Grab.Properties; using Wpf.Ui.Controls; namespace Text_Grab.Utilities; diff --git a/Text-Grab/Utilities/FileUtilities.cs b/Text-Grab/Utilities/FileUtilities.cs index 4bc64d0f..280827db 100644 --- a/Text-Grab/Utilities/FileUtilities.cs +++ b/Text-Grab/Utilities/FileUtilities.cs @@ -5,7 +5,6 @@ using System.IO; using System.Text; using System.Threading.Tasks; -using Windows.Media.Streaming.Adaptive; using Windows.Storage; using Windows.Storage.Streams; @@ -37,7 +36,7 @@ public static string GetImageFilter() string imageExtensions = string.Empty; string separator = ""; ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); - Dictionary imageFilters = new Dictionary(); + Dictionary imageFilters = new(); foreach (ImageCodecInfo codec in codecs) { if (codec.FilenameExtension is not string extension) @@ -73,7 +72,7 @@ public static string GetPathToLocalFile(string imageRelativePath) return Path.Combine(dirPath, imageRelativePath); } - public async static Task GetPathToHistory() + public static async Task GetPathToHistory() { if (AppUtilities.IsPackaged()) { @@ -108,7 +107,7 @@ public static Task SaveTextFile(string textContent, string filename, FileS return SaveTextFileUnpackaged(textContent, filename, storageKind); } - private async static Task GetImageFilePackaged(string fileName, FileStorageKind storageKind) + private static async Task GetImageFilePackaged(string fileName, FileStorageKind storageKind) { StorageFolder folder = await GetStorageFolderPackaged(fileName, storageKind); @@ -122,7 +121,7 @@ public static Task SaveTextFile(string textContent, string filename, FileS return null; } } - + #pragma warning disable CS1998 private static async Task GetImageFileUnpackaged(string fileName, FileStorageKind storageKind) { @@ -134,7 +133,7 @@ public static Task SaveTextFile(string textContent, string filename, FileS return new Bitmap(filePath); } - private async static Task GetTextFilePackaged(string fileName, FileStorageKind storageKind) + private static async Task GetTextFilePackaged(string fileName, FileStorageKind storageKind) { try { @@ -290,8 +289,8 @@ private static async Task SaveTextFileUnpackaged(string textContent, strin return true; } #pragma warning restore CS1998 - - public async static void TryDeleteHistoryDirectory() + + public static async void TryDeleteHistoryDirectory() { FileStorageKind historyFolderKind = FileStorageKind.WithHistory; if (AppUtilities.IsPackaged()) diff --git a/Text-Grab/Utilities/HotKeyManager.cs b/Text-Grab/Utilities/HotKeyManager.cs index 05eee7b6..0f2d0e06 100644 --- a/Text-Grab/Utilities/HotKeyManager.cs +++ b/Text-Grab/Utilities/HotKeyManager.cs @@ -3,7 +3,6 @@ using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; -using System.Windows.Input; using Text_Grab.Models; namespace Text_Grab.Utilities; @@ -37,8 +36,9 @@ public static void UnregisterHotKey(int id) _wnd?.Invoke(new UnRegisterHotKeyDelegate(UnRegisterHotKeyInternal), _hwnd, id); } - delegate void RegisterHotKeyDelegate(IntPtr hwnd, int id, uint modifiers, uint key); - delegate void UnRegisterHotKeyDelegate(IntPtr hwnd, int id); + private delegate void RegisterHotKeyDelegate(IntPtr hwnd, int id, uint modifiers, uint key); + + private delegate void UnRegisterHotKeyDelegate(IntPtr hwnd, int id); private static void RegisterHotKeyInternal(IntPtr hwnd, int id, uint modifiers, uint key) { @@ -60,10 +60,10 @@ private static void OnHotKeyPressed(HotKeyEventArgs e) private static volatile MessageWindow? _wnd; private static volatile IntPtr _hwnd; - private static ManualResetEvent? _windowReadyEvent = new ManualResetEvent(false); + private static ManualResetEvent? _windowReadyEvent = new(false); static HotKeyManager() { - Thread messageLoop = new Thread(delegate () + Thread messageLoop = new(delegate () { Application.Run(new MessageWindow()); }); @@ -85,7 +85,7 @@ protected override void WndProc(ref Message m) { if (m.Msg == WM_HOTKEY) { - HotKeyEventArgs e = new HotKeyEventArgs(m.LParam); + HotKeyEventArgs e = new(m.LParam); HotKeyManager.OnHotKeyPressed(e); } diff --git a/Text-Grab/Utilities/IoUtilities.cs b/Text-Grab/Utilities/IoUtilities.cs index ac40632c..f0544214 100644 --- a/Text-Grab/Utilities/IoUtilities.cs +++ b/Text-Grab/Utilities/IoUtilities.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Text; using System.Threading.Tasks; diff --git a/Text-Grab/Utilities/LanguageUtilities.cs b/Text-Grab/Utilities/LanguageUtilities.cs index 285340e5..faa9a7c0 100644 --- a/Text-Grab/Utilities/LanguageUtilities.cs +++ b/Text-Grab/Utilities/LanguageUtilities.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Windows.Input; -using Text_Grab.Properties; using Windows.Globalization; using Windows.Media.Ocr; diff --git a/Text-Grab/Utilities/NotificationUtilities.cs b/Text-Grab/Utilities/NotificationUtilities.cs index 00e5f335..cab4437b 100644 --- a/Text-Grab/Utilities/NotificationUtilities.cs +++ b/Text-Grab/Utilities/NotificationUtilities.cs @@ -12,17 +12,17 @@ internal static void ShowToast(string copiedText) // changed to using base64 // the padding '=' will be encoded as '%3D' in the toast XML, so remove them - string encodedString = Convert.ToBase64String(plainTextBytes).TrimEnd('='); + string encodedString = Convert.ToBase64String(plainTextBytes).TrimEnd('='); // truncate toast body text first, if it is too long string toastBody; if (copiedText.Length > 150) - toastBody = copiedText.Substring(0, 150) + "..."; + toastBody = copiedText[..150] + "..."; else toastBody = copiedText; // build the toast XML - var toast = new ToastContentBuilder() + ToastContentBuilder toast = new ToastContentBuilder() .AddArgument("text", encodedString) .AddText("Text Grab") .AddText(toastBody); diff --git a/Text-Grab/Utilities/NotifyIconUtilities.cs b/Text-Grab/Utilities/NotifyIconUtilities.cs index 5f45bd2b..968e5d86 100644 --- a/Text-Grab/Utilities/NotifyIconUtilities.cs +++ b/Text-Grab/Utilities/NotifyIconUtilities.cs @@ -49,7 +49,7 @@ private static void trayIcon_Disposed(object? sender, EventArgs e) UnregisterHotkeys(app); } - static void HotKeyManager_HotKeyPressed(object? sender, HotKeyEventArgs e) + private static void HotKeyManager_HotKeyPressed(object? sender, HotKeyEventArgs e) { if (!AppUtilities.TextGrabSettings.GlobalHotkeysEnabled) return; diff --git a/Text-Grab/Utilities/OcrUtilities.cs b/Text-Grab/Utilities/OcrUtilities.cs index 2de33ef1..11008941 100644 --- a/Text-Grab/Utilities/OcrUtilities.cs +++ b/Text-Grab/Utilities/OcrUtilities.cs @@ -1,11 +1,9 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; -using System.Runtime.Intrinsics.Arm; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; @@ -14,11 +12,9 @@ using System.Windows.Media; using System.Windows.Media.Imaging; using Text_Grab.Controls; -using Text_Grab.Extensions; using Text_Grab.Models; using Text_Grab.Properties; using Text_Grab.Services; -using Text_Grab.Views; using Windows.Globalization; using Windows.Graphics.Imaging; using Windows.Media.Ocr; @@ -30,7 +26,7 @@ namespace Text_Grab.Utilities; public static class OcrUtilities { - private readonly static Settings DefaultSettings = AppUtilities.TextGrabSettings; + private static readonly Settings DefaultSettings = AppUtilities.TextGrabSettings; public static void GetTextFromOcrLine(this OcrLine ocrLine, bool isSpaceJoiningOCRLang, StringBuilder text) { @@ -97,7 +93,7 @@ public static async Task GetRegionsTextAsync(Window passedWindow, Rectan Rectangle correctedRegion = new(thisCorrectedLeft, thisCorrectedTop, selectedRegion.Width, selectedRegion.Height); Bitmap bmp = ImageMethods.GetRegionOfScreenAsBitmap(correctedRegion); - return GetStringFromOcrOutputs( await GetTextFromImageAsync(bmp, language, languageTag)); + return GetStringFromOcrOutputs(await GetTextFromImageAsync(bmp, language, languageTag)); } public static async Task GetRegionsTextAsTableAsync(Window passedWindow, Rectangle selectedRegion, Language language) @@ -129,7 +125,7 @@ public static async Task GetRegionsTextAsTableAsync(Window passedWindow, return (ocrResult, scale); } - public async static Task GetOcrFromStreamAsync(MemoryStream memoryStream, Language language) + public static async Task GetOcrFromStreamAsync(MemoryStream memoryStream, Language language) { using WrappingStream wrapper = new(memoryStream); wrapper.Position = 0; @@ -141,7 +137,7 @@ public async static Task GetOcrFromStreamAsync(MemoryStream memoryStr return await GetOcrResultFromImageAsync(softwareBmp, language); } - public async static Task GetOcrFromStreamAsync(IRandomAccessStream stream, Language language) + public static async Task GetOcrFromStreamAsync(IRandomAccessStream stream, Language language) { BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(stream); using SoftwareBitmap softwareBmp = await bmpDecoder.GetSoftwareBitmapAsync(); @@ -149,13 +145,13 @@ public async static Task GetOcrFromStreamAsync(IRandomAccessStream st return await GetOcrResultFromImageAsync(softwareBmp, language); } - public async static Task GetOcrResultFromImageAsync(BitmapImage scaledBitmap, Language language) + public static async Task GetOcrResultFromImageAsync(BitmapImage scaledBitmap, Language language) { Bitmap bitmap = ImageMethods.BitmapImageToBitmap(scaledBitmap); return await GetOcrResultFromImageAsync(bitmap, language); } - public async static Task GetOcrResultFromImageAsync(SoftwareBitmap scaledBitmap, Language language) + public static async Task GetOcrResultFromImageAsync(SoftwareBitmap scaledBitmap, Language language) { OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(language); @@ -165,7 +161,7 @@ public async static Task GetOcrResultFromImageAsync(SoftwareBitmap sc return await ocrEngine.RecognizeAsync(scaledBitmap); } - public async static Task GetOcrResultFromImageAsync(Bitmap scaledBitmap, Language language) + public static async Task GetOcrResultFromImageAsync(Bitmap scaledBitmap, Language language) { await using MemoryStream memory = new(); using WrappingStream wrapper = new(memory); @@ -180,7 +176,7 @@ public async static Task GetOcrResultFromImageAsync(Bitmap scaledBitm return await GetOcrResultFromImageAsync(softwareBmp, language); } - public async static void GetCopyTextFromPreviousRegion() + public static async void GetCopyTextFromPreviousRegion() { HistoryInfo? lastFsg = Singleton.Instance.GetLastFullScreenGrabInfo(); @@ -211,7 +207,7 @@ public async static void GetCopyTextFromPreviousRegion() OutputUtilities.HandleTextFromOcr(grabbedText, false, lastFsg.IsTable, null); } - public async static Task GetTextFromPreviousFullscreenRegion(TextBox? destinationTextBox = null) + public static async Task GetTextFromPreviousFullscreenRegion(TextBox? destinationTextBox = null) { HistoryInfo? lastFsg = Singleton.Instance.GetLastFullScreenGrabInfo(); @@ -242,7 +238,7 @@ public async static Task GetTextFromPreviousFullscreenRegion(TextBox? destinatio OutputUtilities.HandleTextFromOcr(grabbedText, false, lastFsg.IsTable, destinationTextBox); } - public async static Task> GetTextFromRandomAccessStream(IRandomAccessStream randomAccessStream, Language language) + public static async Task> GetTextFromRandomAccessStream(IRandomAccessStream randomAccessStream, Language language) { OcrResult ocrResult = await GetOcrFromStreamAsync(randomAccessStream, language); @@ -271,7 +267,7 @@ public static Task> GetTextFromImageAsync(SoftwareBitmap softwar // Read QR Codes from software bitmaps } - public async static Task> GetTextFromImageAsync(BitmapImage bitmapImage, Language language) + public static async Task> GetTextFromImageAsync(BitmapImage bitmapImage, Language language) { Bitmap bitmap = ImageMethods.BitmapImageToBitmap(bitmapImage); return await GetTextFromImageAsync(bitmap, language); @@ -287,12 +283,12 @@ public static Task> GetTextFromStreamAsync(IRandomAccessStream s throw new NotImplementedException(); } - public async static Task> GetTextFromImageAsync(Bitmap bitmap, Language language, string tessTag = "") + public static async Task> GetTextFromImageAsync(Bitmap bitmap, Language language, string tessTag = "") { List outputs = new(); - if (DefaultSettings.UseTesseract - && TesseractHelper.CanLocateTesseractExe() + if (DefaultSettings.UseTesseract + && TesseractHelper.CanLocateTesseractExe() && !string.IsNullOrEmpty(tessTag)) { OcrOutput tesseractOutput = await TesseractHelper.GetOcrOutputFromBitmap(bitmap, language, tessTag); @@ -403,14 +399,14 @@ private static string GetTextFromClickedWord(Point singlePoint, OcrResult ocrRes return string.Empty; } - public async static Task GetIdealScaleFactorForOcrAsync(SoftwareBitmap bitmap, Language selectedLanguage) + public static async Task GetIdealScaleFactorForOcrAsync(SoftwareBitmap bitmap, Language selectedLanguage) { OcrResult ocrResult = await OcrUtilities.GetOcrResultFromImageAsync(bitmap, selectedLanguage); return GetIdealScaleFactorForOcrResult(ocrResult, bitmap.PixelHeight, bitmap.PixelWidth); } - public async static Task GetIdealScaleFactorForOcrAsync(Bitmap bitmap, Language selectedLanguage) + public static async Task GetIdealScaleFactorForOcrAsync(Bitmap bitmap, Language selectedLanguage) { OcrResult ocrResult = await OcrUtilities.GetOcrResultFromImageAsync(bitmap, selectedLanguage); diff --git a/Text-Grab/Utilities/OutputUtilities.cs b/Text-Grab/Utilities/OutputUtilities.cs index d6978487..20475866 100644 --- a/Text-Grab/Utilities/OutputUtilities.cs +++ b/Text-Grab/Utilities/OutputUtilities.cs @@ -1,6 +1,5 @@ using System.Windows; using System.Windows.Controls; -using Text_Grab.Properties; namespace Text_Grab.Utilities; diff --git a/Text-Grab/Utilities/RegistryMonitor.cs b/Text-Grab/Utilities/RegistryMonitor.cs index bd8a4766..0b907263 100644 --- a/Text-Grab/Utilities/RegistryMonitor.cs +++ b/Text-Grab/Utilities/RegistryMonitor.cs @@ -43,7 +43,8 @@ namespace RegistryUtils; /// } /// /// -public class RegistryMonitor : IDisposable { +public class RegistryMonitor : IDisposable +{ #region P/Invoke [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] @@ -90,7 +91,8 @@ private static extern int RegNotifyChangeKeyValue(IntPtr hKey, bool bWatchSubtre /// the base class's method. /// /// - protected virtual void OnRegChanged() { + protected virtual void OnRegChanged() + { RegChanged?.Invoke(this, new EventArgs()); } @@ -112,7 +114,8 @@ protected virtual void OnRegChanged() { /// the base class's method. /// /// - protected virtual void OnError(Exception e) { + protected virtual void OnError(Exception e) + { Error?.Invoke(this, new ErrorEventArgs(e)); } @@ -136,7 +139,8 @@ protected virtual void OnError(Exception e) { /// Initializes a new instance of the class. /// /// The registry key to monitor. - public RegistryMonitor(RegistryKey registryKey) { + public RegistryMonitor(RegistryKey registryKey) + { InitRegistryKey(registryKey.Name); } @@ -144,7 +148,8 @@ public RegistryMonitor(RegistryKey registryKey) { /// Initializes a new instance of the class. /// /// The name. - public RegistryMonitor(string name) { + public RegistryMonitor(string name) + { if (name == null || name.Length == 0) throw new ArgumentNullException(nameof(name)); @@ -156,14 +161,16 @@ public RegistryMonitor(string name) { /// /// The registry hive. /// The sub key. - public RegistryMonitor(RegistryHive registryHive, string subKey) { + public RegistryMonitor(RegistryHive registryHive, string subKey) + { InitRegistryKey(registryHive, subKey); } /// /// Disposes this object. /// - public void Dispose() { + public void Dispose() + { Stop(); _disposed = true; GC.SuppressFinalize(this); @@ -172,10 +179,13 @@ public void Dispose() { /// /// Gets or sets the RegChangeNotifyFilter. /// - public RegChangeNotifyFilter RegChangeNotifyFilter { + public RegChangeNotifyFilter RegChangeNotifyFilter + { get { return _regFilter; } - set { - lock (_threadLock) { + set + { + lock (_threadLock) + { if (IsMonitoring) throw new InvalidOperationException("Monitoring thread is already running"); @@ -186,8 +196,10 @@ public RegChangeNotifyFilter RegChangeNotifyFilter { #region Initialization - private void InitRegistryKey(RegistryHive hive, string name) { - _registryHive = hive switch { + private void InitRegistryKey(RegistryHive hive, string name) + { + _registryHive = hive switch + { RegistryHive.ClassesRoot => HKEY_CLASSES_ROOT, RegistryHive.CurrentConfig => HKEY_CURRENT_CONFIG, RegistryHive.CurrentUser => HKEY_CURRENT_USER, @@ -199,7 +211,8 @@ private void InitRegistryKey(RegistryHive hive, string name) { _registrySubName = name; } - private void InitRegistryKey(string name) { + private void InitRegistryKey(string name) + { string[] nameParts = name.Split('\\'); switch (nameParts[0]) @@ -241,21 +254,26 @@ private void InitRegistryKey(string name) { /// true if this object is currently monitoring; /// otherwise, false. /// - public bool IsMonitoring { + public bool IsMonitoring + { get { return _thread != null; } } /// /// Start monitoring. /// - public void Start() { + public void Start() + { if (_disposed) throw new ObjectDisposedException(null, "This instance is already disposed"); - lock (_threadLock) { - if (!IsMonitoring) { + lock (_threadLock) + { + if (!IsMonitoring) + { _eventTerminate.Reset(); - _thread = new Thread(new ThreadStart(MonitorThread)) { + _thread = new Thread(new ThreadStart(MonitorThread)) + { IsBackground = true }; _thread.Start(); @@ -266,29 +284,36 @@ public void Start() { /// /// Stops the monitoring thread. /// - public void Stop() { + public void Stop() + { if (_disposed) throw new ObjectDisposedException(null, "This instance is already disposed"); - lock (_threadLock) { - if (_thread is Thread thread) { + lock (_threadLock) + { + if (_thread is Thread thread) + { _eventTerminate.Set(); thread.Join(); } } } - private void MonitorThread() { - try { + private void MonitorThread() + { + try + { ThreadLoop(); } - catch (Exception e) { + catch (Exception e) + { OnError(e); } _thread = null; } - private void ThreadLoop() { + private void ThreadLoop() + { if (_registryHive is null || _registrySubName is null) return; @@ -300,10 +325,12 @@ private void ThreadLoop() { if (result != 0) throw new Win32Exception(result); - try { + try + { AutoResetEvent _eventNotify = new(false); WaitHandle[] waitHandles = new WaitHandle[] { _eventNotify, _eventTerminate }; - while (!_eventTerminate.WaitOne(0, true)) { + while (!_eventTerminate.WaitOne(0, true)) + { result = RegNotifyChangeKeyValue(registryKey, true, _regFilter, @@ -312,13 +339,16 @@ private void ThreadLoop() { if (result != 0) throw new Win32Exception(result); - if (WaitHandle.WaitAny(waitHandles) == 0) { + if (WaitHandle.WaitAny(waitHandles) == 0) + { OnRegChanged(); } } } - finally { - if (registryKey != IntPtr.Zero) { + finally + { + if (registryKey != IntPtr.Zero) + { RegCloseKey(registryKey); } } @@ -329,7 +359,8 @@ private void ThreadLoop() { /// Filter for notifications reported by . /// [Flags] -public enum RegChangeNotifyFilter { +public enum RegChangeNotifyFilter +{ /// Notify the caller if a subkey is added or deleted. Key = 1, /// Notify the caller of changes to the attributes of the key, diff --git a/Text-Grab/Utilities/ShortcutKeysUtilities.cs b/Text-Grab/Utilities/ShortcutKeysUtilities.cs index 8f5c12cd..5e1f133c 100644 --- a/Text-Grab/Utilities/ShortcutKeysUtilities.cs +++ b/Text-Grab/Utilities/ShortcutKeysUtilities.cs @@ -4,7 +4,6 @@ using System.Text.Json; using System.Windows.Input; using Text_Grab.Models; -using Text_Grab.Properties; namespace Text_Grab.Utilities; @@ -40,7 +39,7 @@ public static IEnumerable GetShortcutKeySetsFromSettings() if (shortcutKeySets is null || shortcutKeySets.Count == 0) return defaultKeys; - var actionsList = shortcutKeySets.Select(x => x.Action).ToList(); + List actionsList = shortcutKeySets.Select(x => x.Action).ToList(); return shortcutKeySets.Concat(defaultKeys.Where(x => !actionsList.Contains(x.Action)).ToList()).ToList(); } diff --git a/Text-Grab/Utilities/Singleton.cs b/Text-Grab/Utilities/Singleton.cs index 8f6d0776..42f56e64 100644 --- a/Text-Grab/Utilities/Singleton.cs +++ b/Text-Grab/Utilities/Singleton.cs @@ -5,7 +5,7 @@ namespace Text_Grab.Utilities; internal static class Singleton where T : new() { - private static ConcurrentDictionary _instances = new ConcurrentDictionary(); + private static ConcurrentDictionary _instances = new(); public static T Instance { diff --git a/Text-Grab/Utilities/StreamWrapper.cs b/Text-Grab/Utilities/StreamWrapper.cs index 14dbe850..460e1507 100644 --- a/Text-Grab/Utilities/StreamWrapper.cs +++ b/Text-Grab/Utilities/StreamWrapper.cs @@ -131,8 +131,7 @@ public override void EndWrite(IAsyncResult asyncResult) { ThrowIfDisposed(); - if (m_streamBase is not null) - m_streamBase.EndWrite(asyncResult); + m_streamBase?.EndWrite(asyncResult); } /// @@ -142,8 +141,7 @@ public override void Flush() { ThrowIfDisposed(); - if (m_streamBase is not null) - m_streamBase.Flush(); + m_streamBase?.Flush(); } /// @@ -197,8 +195,7 @@ public override void SetLength(long value) { ThrowIfDisposed(); - if (m_streamBase is not null) - m_streamBase.SetLength(value); + m_streamBase?.SetLength(value); } /// @@ -209,8 +206,7 @@ public override void Write(byte[] buffer, int offset, int count) { ThrowIfDisposed(); - if (m_streamBase is not null) - m_streamBase.Write(buffer, offset, count); + m_streamBase?.Write(buffer, offset, count); } /// @@ -220,8 +216,7 @@ public override void WriteByte(byte value) { ThrowIfDisposed(); - if (m_streamBase is not null) - m_streamBase.WriteByte(value); + m_streamBase?.WriteByte(value); } /// @@ -253,5 +248,6 @@ private void ThrowIfDisposed() if (m_streamBase == null) throw new ObjectDisposedException(GetType().Name); } - Stream? m_streamBase; + + private Stream? m_streamBase; } \ No newline at end of file diff --git a/Text-Grab/Utilities/StringMethods.cs b/Text-Grab/Utilities/StringMethods.cs index d53ed248..686d111d 100644 --- a/Text-Grab/Utilities/StringMethods.cs +++ b/Text-Grab/Utilities/StringMethods.cs @@ -507,7 +507,7 @@ private static string ShortenRegexPattern(this string pattern) return possibleShortenedPatterns.First(); } - static IEnumerable Split(string str, int chunkSize) + private static IEnumerable Split(string str, int chunkSize) { return Enumerable.Range(0, str.Length / chunkSize) .Select(i => str.Substring(i * chunkSize, chunkSize)); @@ -662,7 +662,7 @@ public static string LimitCharactersPerLine(this string stringToEdit, int charac continue; } - if (spotInLine== SpotInLine.Beginning) + if (spotInLine == SpotInLine.Beginning) returnStringBuilder.AppendLine(line[..lineLimit]); else returnStringBuilder.AppendLine(line.Substring(line.Length - (lineLimit), lineLimit)); @@ -683,7 +683,7 @@ public static bool IsBasicLatin(this char c) { // Basic Latin characters are those with Unicode code points // in the range U+0000 to U+007F (inclusive) - return c >= '\u0000' && c <= '\u007F'; + return c is >= '\u0000' and <= '\u007F'; } public static string GetCharactersToLeftOfNewLine(ref string mainString, int index, int numberOfCharacters) diff --git a/Text-Grab/Utilities/SystemThemeUtility.cs b/Text-Grab/Utilities/SystemThemeUtility.cs index 9147419d..f9706875 100644 --- a/Text-Grab/Utilities/SystemThemeUtility.cs +++ b/Text-Grab/Utilities/SystemThemeUtility.cs @@ -1,10 +1,5 @@ -using Microsoft.Toolkit.Uwp.Notifications; -using Microsoft.Win32; +using Microsoft.Win32; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Text_Grab.Utilities; @@ -26,7 +21,7 @@ public static bool IsLightTheme() if (o.ToString() == "1") return true; - + return false; } catch (Exception) diff --git a/Text-Grab/Utilities/TesseractHelper.cs b/Text-Grab/Utilities/TesseractHelper.cs index fa01e2ee..8594ba31 100644 --- a/Text-Grab/Utilities/TesseractHelper.cs +++ b/Text-Grab/Utilities/TesseractHelper.cs @@ -30,7 +30,7 @@ public static class TesseractHelper private const string rawProgramsPath = @"%LOCALAPPDATA%\Programs\Tesseract-OCR\tesseract.exe"; private const string basicPath = @"C:\Program Files\Tesseract-OCR\tesseract.exe"; - private readonly static Settings DefaultSettings = AppUtilities.TextGrabSettings; + private static readonly Settings DefaultSettings = AppUtilities.TextGrabSettings; public static bool CanLocateTesseractExe() @@ -184,7 +184,7 @@ public static string TempImagePath() return $"{exePath}\\tempImage.png"; } - public async static Task> TesseractLanguagesAsStrings() + public static async Task> TesseractLanguagesAsStrings() { List languageStrings = new(); @@ -217,7 +217,7 @@ public async static Task> TesseractLanguagesAsStrings() return languageStrings; } - public async static Task> TesseractLanguages() + public static async Task> TesseractLanguages() { List languageStrings = await TesseractLanguagesAsStrings(); List tesseractLanguages = new(); diff --git a/Text-Grab/Utilities/WindowResizer.cs b/Text-Grab/Utilities/WindowResizer.cs index 86e07fc1..d2c793fd 100644 --- a/Text-Grab/Utilities/WindowResizer.cs +++ b/Text-Grab/Utilities/WindowResizer.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; @@ -41,7 +40,7 @@ public class WindowResizer /// /// The last calculated available screen size /// - private Rect mScreenSize = new Rect(); + private Rect mScreenSize = new(); /// /// How close to the edge the window has to be to be detected as at the edge of the screen @@ -69,13 +68,13 @@ public class WindowResizer [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - static extern bool GetCursorPos(out POINT lpPoint); + private static extern bool GetCursorPos(out POINT lpPoint); [DllImport("user32.dll")] - static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi); + private static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi); [DllImport("user32.dll", SetLastError = true)] - static extern IntPtr MonitorFromPoint(POINT pt, MonitorOptions dwFlags); + private static extern IntPtr MonitorFromPoint(POINT pt, MonitorOptions dwFlags); #endregion @@ -122,7 +121,7 @@ public WindowResizer(Window window) private void GetTransform() { // Get the visual source - var source = PresentationSource.FromVisual(mWindow); + PresentationSource source = PresentationSource.FromVisual(mWindow); // Reset the transform to default mTransformToDevice = default(Matrix); @@ -143,8 +142,8 @@ private void GetTransform() private void Window_SourceInitialized(object? sender, System.EventArgs e) { // Get the handle of this window - var handle = (new WindowInteropHelper(mWindow)).Handle; - var handleSource = HwndSource.FromHwnd(handle); + nint handle = (new WindowInteropHelper(mWindow)).Handle; + HwndSource handleSource = HwndSource.FromHwnd(handle); // If not found, end if (handleSource == null) @@ -171,26 +170,26 @@ private void Window_SizeChanged(object sender, SizeChangedEventArgs e) return; // Get the WPF size - var size = e.NewSize; + Size size = e.NewSize; // Get window rectangle - var top = mWindow.Top; - var left = mWindow.Left; - var bottom = top + size.Height; - var right = left + mWindow.Width; + double top = mWindow.Top; + double left = mWindow.Left; + double bottom = top + size.Height; + double right = left + mWindow.Width; // Get window position/size in device pixels - var windowTopLeft = mTransformToDevice.Transform(new Point(left, top)); - var windowBottomRight = mTransformToDevice.Transform(new Point(right, bottom)); + Point windowTopLeft = mTransformToDevice.Transform(new Point(left, top)); + Point windowBottomRight = mTransformToDevice.Transform(new Point(right, bottom)); // Check for edges docked - var edgedTop = windowTopLeft.Y <= (mScreenSize.Top + mEdgeTolerance); - var edgedLeft = windowTopLeft.X <= (mScreenSize.Left + mEdgeTolerance); - var edgedBottom = windowBottomRight.Y >= (mScreenSize.Bottom - mEdgeTolerance); - var edgedRight = windowBottomRight.X >= (mScreenSize.Right - mEdgeTolerance); + bool edgedTop = windowTopLeft.Y <= (mScreenSize.Top + mEdgeTolerance); + bool edgedLeft = windowTopLeft.X <= (mScreenSize.Left + mEdgeTolerance); + bool edgedBottom = windowBottomRight.Y >= (mScreenSize.Bottom - mEdgeTolerance); + bool edgedRight = windowBottomRight.X >= (mScreenSize.Right - mEdgeTolerance); // Get docked position - var dock = WindowDockPosition.Undocked; + WindowDockPosition dock = WindowDockPosition.Undocked; // Left docking if (edgedTop && edgedBottom && edgedLeft) @@ -234,7 +233,7 @@ private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, re break; } - return (IntPtr)0; + return 0; } #endregion @@ -255,15 +254,15 @@ private void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam) GetCursorPos(out lMousePosition); // Get the primary monitor at cursor position 0,0 - var lPrimaryScreen = MonitorFromPoint(new POINT(0, 0), MonitorOptions.MONITOR_DEFAULTTOPRIMARY); + nint lPrimaryScreen = MonitorFromPoint(new POINT(0, 0), MonitorOptions.MONITOR_DEFAULTTOPRIMARY); // Try and get the primary screen information - var lPrimaryScreenInfo = new MONITORINFO(); + MONITORINFO lPrimaryScreenInfo = new(); if (!GetMonitorInfo(lPrimaryScreen, lPrimaryScreenInfo)) return; // Now get the current screen - var lCurrentScreen = MonitorFromPoint(lMousePosition, MonitorOptions.MONITOR_DEFAULTTONEAREST); + nint lCurrentScreen = MonitorFromPoint(lMousePosition, MonitorOptions.MONITOR_DEFAULTTONEAREST); // If this has changed from the last one, update the transform if (lCurrentScreen != mLastScreen || mTransformToDevice == default(Matrix)) @@ -273,11 +272,11 @@ private void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam) mLastScreen = lCurrentScreen; // Get min/max structure to fill with information - var lMmiTmp = (MINMAXINFO?)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO)); + MINMAXINFO? lMmiTmp = (MINMAXINFO?)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO)); if (lMmiTmp == null) return; - var lMmi = lMmiTmp.Value; + MINMAXINFO lMmi = lMmiTmp.Value; lMmi.ptMaxPosition.X = lPrimaryScreenInfo.rcWork.Left; lMmi.ptMaxPosition.Y = lPrimaryScreenInfo.rcWork.Top; @@ -285,7 +284,7 @@ private void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam) lMmi.ptMaxSize.Y = lPrimaryScreenInfo.rcWork.Bottom - lPrimaryScreenInfo.rcWork.Top; // Set min size - var minSize = mTransformToDevice.Transform(new Point(mWindow.MinWidth, mWindow.MinHeight)); + Point minSize = mTransformToDevice.Transform(new Point(mWindow.MinWidth, mWindow.MinHeight)); lMmi.ptMinTrackSize.X = (int)minSize.X; lMmi.ptMinTrackSize.Y = (int)minSize.Y; @@ -300,7 +299,7 @@ private void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam) #region Dll Helper Structures -enum MonitorOptions : uint +internal enum MonitorOptions : uint { MONITOR_DEFAULTTONULL = 0x00000000, MONITOR_DEFAULTTOPRIMARY = 0x00000001, @@ -312,8 +311,8 @@ enum MonitorOptions : uint public class MONITORINFO { public int cbSize = Marshal.SizeOf(typeof(MONITORINFO)); - public Rectangle rcMonitor = new Rectangle(); - public Rectangle rcWork = new Rectangle(); + public Rectangle rcMonitor = new(); + public Rectangle rcWork = new(); public int dwFlags = 0; } diff --git a/Text-Grab/Utilities/WindowUtilities.cs b/Text-Grab/Utilities/WindowUtilities.cs index eefae058..0210fc92 100644 --- a/Text-Grab/Utilities/WindowUtilities.cs +++ b/Text-Grab/Utilities/WindowUtilities.cs @@ -242,7 +242,7 @@ private static void TryInjectModifierKeyUp(ref List inputs, VirtualKeySho // Most significant bit is set if key is down if ((GetAsyncKeyState((int)modifier) & 0x8000) != 0) { - var inputEvent = default(INPUT); + INPUT inputEvent = default(INPUT); inputEvent.Type = OSInterop.InputType.INPUT_KEYBOARD; inputEvent.U.Ki.WVk = modifier; inputEvent.U.Ki.DwFlags = KEYEVENTF.KEYUP; @@ -299,7 +299,7 @@ public static void ShouldShutDown() if (shouldShutDown) Application.Current.Shutdown(); } - + public static bool GetMousePosition(out Point mousePosition) { if (GetCursorPos(out POINT point)) @@ -327,7 +327,7 @@ public static bool IsMouseInWindow(this Window window) [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - static extern bool GetCursorPos(out POINT lpPoint); + private static extern bool GetCursorPos(out POINT lpPoint); #endregion } \ No newline at end of file diff --git a/Text-Grab/Views/EditTextWindow.xaml.cs b/Text-Grab/Views/EditTextWindow.xaml.cs index 3699d038..f6e1378a 100644 --- a/Text-Grab/Views/EditTextWindow.xaml.cs +++ b/Text-Grab/Views/EditTextWindow.xaml.cs @@ -50,7 +50,7 @@ public partial class EditTextWindow : Wpf.Ui.Controls.FluentWindow public static RoutedCommand UnstackCmd = new(); public static RoutedCommand UnstackGroupCmd = new(); public bool LaunchedFromNotification = false; - CancellationTokenSource? cancellationTokenForDirOCR; + private CancellationTokenSource? cancellationTokenForDirOCR; private string historyId = string.Empty; private int numberOfContextMenuItems; private string? OpenedFilePath; @@ -718,8 +718,8 @@ private void EditTextWindow_PreviewKeyDown(object sender, System.Windows.Input.K // D9 is 43 // D0 is 34 - if (keyNumberPressed < -1 - || keyNumberPressed > 8) + if (keyNumberPressed is < (-1) + or > 8) return; // since D9 is next to D0 it makes sense @@ -894,8 +894,8 @@ private void InsertSelectionOnEveryLine(object? sender = null, ExecutedRoutedEve int selectionPositionInLine = PassedTextControl.SelectionStart; for (int i = initialSelectionStart; i >= 0; i--) { - if (PassedTextControl.Text[i] == '\n' - || PassedTextControl.Text[i] == '\r') + if (PassedTextControl.Text[i] is '\n' + or '\r') { selectionPositionInLine = initialSelectionStart - i - 1; break; @@ -1184,7 +1184,7 @@ private void DuplicateSelectedLine(object sender, ExecutedRoutedEventArgs e) SelectLine(); string lineText = PassedTextControl.SelectedText; bool lineEndsInNewLine = lineText.EndsWithNewline(); - PassedTextControl.SelectedText = $"{ lineText}{(lineEndsInNewLine ? "" : Environment.NewLine)}{ lineText}"; + PassedTextControl.SelectedText = $"{lineText}{(lineEndsInNewLine ? "" : Environment.NewLine)}{lineText}"; int length = lineText.Length; if (!lineEndsInNewLine) length += Environment.NewLine.Length; @@ -2101,12 +2101,12 @@ private void WrapTextCHBOX_Checked(object sender, RoutedEventArgs e) if (!IsLoaded) return; - if ((bool)WrapTextMenuItem.IsChecked) + if (WrapTextMenuItem.IsChecked) PassedTextControl.TextWrapping = TextWrapping.Wrap; else PassedTextControl.TextWrapping = TextWrapping.NoWrap; - DefaultSettings.EditWindowIsWordWrapOn = (bool)WrapTextMenuItem.IsChecked; + DefaultSettings.EditWindowIsWordWrapOn = WrapTextMenuItem.IsChecked; } #endregion Methods } diff --git a/Text-Grab/Views/FirstRunWindow.xaml.cs b/Text-Grab/Views/FirstRunWindow.xaml.cs index 6c4cf31d..b4b4f78b 100644 --- a/Text-Grab/Views/FirstRunWindow.xaml.cs +++ b/Text-Grab/Views/FirstRunWindow.xaml.cs @@ -113,7 +113,7 @@ private void OkayButton_Click(object sender, RoutedEventArgs e) { int windowsCount = Application.Current.Windows.Count; - if (windowsCount == 2 || windowsCount == 1) + if (windowsCount is 2 or 1) { TextGrabMode defaultLaunchSetting = Enum.Parse(DefaultSettings.DefaultLaunch, true); switch (defaultLaunchSetting) diff --git a/Text-Grab/Views/FullscreenGrab.xaml.cs b/Text-Grab/Views/FullscreenGrab.xaml.cs index 84557286..7087ae44 100644 --- a/Text-Grab/Views/FullscreenGrab.xaml.cs +++ b/Text-Grab/Views/FullscreenGrab.xaml.cs @@ -39,8 +39,8 @@ public partial class FullscreenGrab : Window private double xShiftDelta; private double yShiftDelta; private HistoryInfo? historyInfo; - bool usingTesseract; - private readonly static Settings DefaultSettings = AppUtilities.TextGrabSettings; + private bool usingTesseract; + private static readonly Settings DefaultSettings = AppUtilities.TextGrabSettings; #endregion Fields @@ -232,7 +232,7 @@ private async void FreezeUnfreeze(bool Activate) RegionClickCanvas.ContextMenu.IsOpen = false; await Task.Delay(150); SetImageToBackground(); - + if (this.IsMouseInWindow()) TopButtonsStackPanel.Visibility = Visibility.Visible; } diff --git a/Text-Grab/Views/GrabFrame.xaml.cs b/Text-Grab/Views/GrabFrame.xaml.cs index b6529676..2a37b046 100644 --- a/Text-Grab/Views/GrabFrame.xaml.cs +++ b/Text-Grab/Views/GrabFrame.xaml.cs @@ -5,7 +5,6 @@ using System.Diagnostics; using System.IO; using System.Linq; -using System.Linq.Expressions; using System.Runtime.InteropServices; using System.Text; using System.Text.Json; @@ -72,7 +71,7 @@ public partial class GrabFrame : Window private bool wasAltHeld = false; private double windowFrameImageScale = 1; private ObservableCollection wordBorders = new(); - private readonly static Settings DefaultSettings = AppUtilities.TextGrabSettings; + private static readonly Settings DefaultSettings = AppUtilities.TextGrabSettings; private ScrollBehavior scrollBehavior = ScrollBehavior.Resize; #endregion Fields @@ -1363,7 +1362,7 @@ private void HandlePreviewMouseWheel(object sender, MouseWheelEventArgs e) // Source: StackOverflow, read on Sep. 10, 2021 // https://stackoverflow.com/a/53698638/7438031 - if (WindowState == WindowState.Maximized + if (WindowState == WindowState.Maximized || scrollBehavior == ScrollBehavior.None) return; diff --git a/Text-Grab/Views/QuickSimpleLookup.xaml.cs b/Text-Grab/Views/QuickSimpleLookup.xaml.cs index c5045ca7..0b85f879 100644 --- a/Text-Grab/Views/QuickSimpleLookup.xaml.cs +++ b/Text-Grab/Views/QuickSimpleLookup.xaml.cs @@ -30,7 +30,7 @@ public partial class QuickSimpleLookup : Wpf.Ui.Controls.FluentWindow private LookupItem? lastSelection; private int rowCount = 0; private string valueUnderEdit = string.Empty; - private readonly static Settings DefaultSettings = AppUtilities.TextGrabSettings; + private static readonly Settings DefaultSettings = AppUtilities.TextGrabSettings; #endregion Fields @@ -57,12 +57,12 @@ public QuickSimpleLookup() private static LookupItem ParseStringToLookupItem(char splitChar, string row) { List cells = row.Split(splitChar).ToList(); - LookupItem newRow = new LookupItem(); + LookupItem newRow = new(); if (cells.FirstOrDefault() is String firstCell) newRow.shortValue = firstCell; newRow.longValue = ""; - if (cells.Count > 1 && cells[1] is String) + if (cells.Count > 1 && cells[1] is not null) newRow.longValue = String.Join(" ", cells.Skip(1).ToArray()); return newRow; } @@ -186,9 +186,7 @@ private void FluentWindow_Closed(object sender, EventArgs e) private List GetMainDataGridSelection() { - var selectedItems = MainDataGrid.SelectedItems as List; - - if (selectedItems is null || selectedItems.Count == 0) + if (MainDataGrid.SelectedItems is not List selectedItems || selectedItems.Count == 0) { selectedItems = new List(); if (MainDataGrid.SelectedItem is not LookupItem selectedLookupItem) @@ -236,7 +234,7 @@ private void MainDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEv if (e.EditAction == DataGridEditAction.Cancel) return; - var child = VisualTreeHelper.GetChild(e.EditingElement, 0); + DependencyObject child = VisualTreeHelper.GetChild(e.EditingElement, 0); if (child is TextBox editedBox && valueUnderEdit != editedBox.Text) { @@ -283,7 +281,7 @@ private void ParseBTN_Click(object sender, RoutedEventArgs e) private async void ParseCSVFileMenuItem_Click(object sender, RoutedEventArgs e) { // Create OpenFileDialog - Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); + Microsoft.Win32.OpenFileDialog dlg = new(); // Set filter for file extension and default file extension dlg.DefaultExt = ".csv"; @@ -324,7 +322,7 @@ private async void PickSaveLocation_Click(object sender, RoutedEventArgs e) dlg.FileName = Path.GetFileName(DefaultSettings.LookupFileLocation); } - var result = dlg.ShowDialog(); + bool? result = dlg.ShowDialog(); if (result is false) return; @@ -399,7 +397,7 @@ private async void PutValueIntoClipboard(KeyboardModifiersDown? keysDown = null) if (selectedLookupItems.FirstOrDefault() is not LookupItem lookupItem) return; - if (Uri.TryCreate(lookupItem.longValue, UriKind.Absolute, out var uri)) + if (Uri.TryCreate(lookupItem.longValue, UriKind.Absolute, out Uri? uri)) { Process.Start(new ProcessStartInfo(lookupItem.longValue) { UseShellExecute = true }); this.Close(); @@ -567,7 +565,7 @@ private async Task ReadCsvFileIntoQuickSimpleLookup(string csvToOpenPath) private void RowDeleted() { - var currentItemSource = MainDataGrid.ItemsSource; + System.Collections.IEnumerable currentItemSource = MainDataGrid.ItemsSource; if (currentItemSource is not List filteredLookupList) return; @@ -652,14 +650,14 @@ private async void SearchBox_TextChanged(object sender, TextChangedEventArgs e) List searchArray = SearchBox.Text.ToLower().Split().ToList(); searchArray.Sort(); - List filteredList = new List(); + List filteredList = new(); foreach (LookupItem lItem in ItemsDictionary) { string lItemAsString = lItem.ToString().ToLower(); bool matchAllSearchWords = true; - foreach (var searchWord in searchArray) + foreach (string searchWord in searchArray) { if (!lItemAsString.Contains(searchWord)) matchAllSearchWords = false; diff --git a/Text-Grab/WPFExtensionMethods.cs b/Text-Grab/WPFExtensionMethods.cs index cdb79b79..8c3f6a0b 100644 --- a/Text-Grab/WPFExtensionMethods.cs +++ b/Text-Grab/WPFExtensionMethods.cs @@ -1,10 +1,9 @@ using System; +using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; -using System.Runtime.InteropServices; - -static class WPFExtensionMethods +internal static class WPFExtensionMethods { public static Point GetAbsolutePosition(this Window w) { @@ -15,15 +14,15 @@ public static Point GetAbsolutePosition(this Window w) bool multimonSupported = OSInterop.GetSystemMetrics(OSInterop.SM_CMONITORS) != 0; if (!multimonSupported) { - OSInterop.RECT rc = new OSInterop.RECT(); + OSInterop.RECT rc = new(); OSInterop.SystemParametersInfo(48, 0, ref rc, 0); r = new Int32Rect(rc.left, rc.top, rc.width, rc.height); } else { - WindowInteropHelper helper = new WindowInteropHelper(w); + WindowInteropHelper helper = new(w); IntPtr hmonitor = OSInterop.MonitorFromWindow(new HandleRef(null, helper.EnsureHandle()), 2); - OSInterop.MONITORINFOEX info = new OSInterop.MONITORINFOEX(); + OSInterop.MONITORINFOEX info = new(); OSInterop.GetMonitorInfo(new HandleRef(null, hmonitor), info); r = new Int32Rect(info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.width, info.rcMonitor.height); }