diff --git a/.editorconfig b/.editorconfig index 11a0bcdf62c..e1b8ed79e57 100644 --- a/.editorconfig +++ b/.editorconfig @@ -58,7 +58,7 @@ dotnet_style_prefer_conditional_expression_over_return = true:silent ############################### # Style Definitions dotnet_naming_style.pascal_case_style.capitalization = pascal_case -# Use PascalCase for constant fields +# Use PascalCase for constant fields dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style @@ -134,7 +134,7 @@ csharp_preserve_single_line_statements = true csharp_preserve_single_line_blocks = true csharp_using_directive_placement = outside_namespace:silent csharp_prefer_simple_using_statement = true:suggestion -csharp_style_namespace_declarations = block_scoped:silent +csharp_style_namespace_declarations = file_scoped:silent csharp_style_prefer_method_group_conversion = true:silent csharp_style_expression_bodied_lambdas = true:silent csharp_style_expression_bodied_local_functions = false:silent diff --git a/Flow.Launcher/Converters/BoolToIMEConversionModeConverter.cs b/Flow.Launcher/Converters/BoolToIMEConversionModeConverter.cs index ffb7d65b804..41e87991317 100644 --- a/Flow.Launcher/Converters/BoolToIMEConversionModeConverter.cs +++ b/Flow.Launcher/Converters/BoolToIMEConversionModeConverter.cs @@ -3,39 +3,38 @@ using System.Windows.Data; using System.Windows.Input; -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +internal class BoolToIMEConversionModeConverter : IValueConverter { - internal class BoolToIMEConversionModeConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + return value switch { - return value switch - { - true => ImeConversionModeValues.Alphanumeric, - _ => ImeConversionModeValues.DoNotCare - }; - } + true => ImeConversionModeValues.Alphanumeric, + _ => ImeConversionModeValues.DoNotCare + }; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } +} - internal class BoolToIMEStateConverter : IValueConverter +internal class BoolToIMEStateConverter : IValueConverter +{ + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + return value switch { - return value switch - { - true => InputMethodState.Off, - _ => InputMethodState.DoNotCare - }; - } + true => InputMethodState.Off, + _ => InputMethodState.DoNotCare + }; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Flow.Launcher/Converters/BoolToVisibilityConverter.cs b/Flow.Launcher/Converters/BoolToVisibilityConverter.cs index ac3b2cfd03c..c0fe6ab5592 100644 --- a/Flow.Launcher/Converters/BoolToVisibilityConverter.cs +++ b/Flow.Launcher/Converters/BoolToVisibilityConverter.cs @@ -2,40 +2,39 @@ using System.Windows; using System.Windows.Data; -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +public class BoolToVisibilityConverter : IValueConverter { - public class BoolToVisibilityConverter : IValueConverter + public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) + return (value, parameter) switch { - return (value, parameter) switch - { - (true, not null) => Visibility.Collapsed, - (_, not null) => Visibility.Visible, - - (true, null) => Visibility.Visible, - (_, null) => Visibility.Collapsed - }; - } + (true, not null) => Visibility.Collapsed, + (_, not null) => Visibility.Visible, - public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) => throw new System.InvalidOperationException(); + (true, null) => Visibility.Visible, + (_, null) => Visibility.Collapsed + }; } - public class SplitterConverter : IValueConverter - /* Prevents the dragging part of the preview area from working when preview is turned off. */ + public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) => throw new System.InvalidOperationException(); +} + +public class SplitterConverter : IValueConverter +/* Prevents the dragging part of the preview area from working when preview is turned off. */ +{ + public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) + return (value, parameter) switch { - return (value, parameter) switch - { - (true, not null) => 0, - (_, not null) => 5, - - (true, null) => 5, - (_, null) => 0 - }; - } + (true, not null) => 0, + (_, not null) => 5, - public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) => throw new System.InvalidOperationException(); + (true, null) => 5, + (_, null) => 0 + }; } + + public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) => throw new System.InvalidOperationException(); } diff --git a/Flow.Launcher/Converters/BorderClipConverter.cs b/Flow.Launcher/Converters/BorderClipConverter.cs index a8d9b34c6d6..9b0579c335b 100644 --- a/Flow.Launcher/Converters/BorderClipConverter.cs +++ b/Flow.Launcher/Converters/BorderClipConverter.cs @@ -7,43 +7,41 @@ // For Clipping inside listbox item -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +public class BorderClipConverter : IMultiValueConverter { - public class BorderClipConverter : IMultiValueConverter + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + if (values is not [double width, double height, CornerRadius radius]) { - if (values is not [double width, double height, CornerRadius radius]) - { - return DependencyProperty.UnsetValue; - } - - Path myPath = new Path(); - if (width < Double.Epsilon || height < Double.Epsilon) - { - return Geometry.Empty; - } - var radiusHeight = radius.TopLeft; - - // Drawing Round box for bottom round, and rect for top area of listbox. - var corner = new RectangleGeometry(new Rect(0, 0, width, height), radius.TopLeft, radius.TopLeft); - var box = new RectangleGeometry(new Rect(0, 0, width, radiusHeight), 0, 0); - - GeometryGroup myGeometryGroup = new GeometryGroup(); - myGeometryGroup.Children.Add(corner); - myGeometryGroup.Children.Add(box); - - CombinedGeometry c1 = new CombinedGeometry(GeometryCombineMode.Union, corner, box); - myPath.Data = c1; - - myPath.Data.Freeze(); - return myPath.Data; + return DependencyProperty.UnsetValue; } - public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + Path myPath = new Path(); + if (width < Double.Epsilon || height < Double.Epsilon) { - throw new NotSupportedException(); + return Geometry.Empty; } + var radiusHeight = radius.TopLeft; + + // Drawing Round box for bottom round, and rect for top area of listbox. + var corner = new RectangleGeometry(new Rect(0, 0, width, height), radius.TopLeft, radius.TopLeft); + var box = new RectangleGeometry(new Rect(0, 0, width, radiusHeight), 0, 0); + + GeometryGroup myGeometryGroup = new GeometryGroup(); + myGeometryGroup.Children.Add(corner); + myGeometryGroup.Children.Add(box); + + CombinedGeometry c1 = new CombinedGeometry(GeometryCombineMode.Union, corner, box); + myPath.Data = c1; + + myPath.Data.Freeze(); + return myPath.Data; } + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotSupportedException(); + } } diff --git a/Flow.Launcher/Converters/DateTimeFormatToNowConverter.cs b/Flow.Launcher/Converters/DateTimeFormatToNowConverter.cs index 3c46fd01a09..7d75ffd5c63 100644 --- a/Flow.Launcher/Converters/DateTimeFormatToNowConverter.cs +++ b/Flow.Launcher/Converters/DateTimeFormatToNowConverter.cs @@ -2,18 +2,17 @@ using System.Globalization; using System.Windows.Data; -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +public class DateTimeFormatToNowConverter : IValueConverter { - public class DateTimeFormatToNowConverter : IValueConverter - { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value is not string format ? null : DateTime.Now.ToString(format); - } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return value is not string format ? null : DateTime.Now.ToString(format); + } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Flow.Launcher/Converters/DiameterToCenterPointConverter.cs b/Flow.Launcher/Converters/DiameterToCenterPointConverter.cs index e81bb250790..24a316603a3 100644 --- a/Flow.Launcher/Converters/DiameterToCenterPointConverter.cs +++ b/Flow.Launcher/Converters/DiameterToCenterPointConverter.cs @@ -3,23 +3,22 @@ using System.Windows; using System.Windows.Data; -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +public class DiameterToCenterPointConverter : IValueConverter { - public class DiameterToCenterPointConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + if (value is double d) { - if (value is double d) - { - return new Point(d / 2, d / 2); - } - - return new Point(0, 0); + return new Point(d / 2, d / 2); } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotSupportedException(); - } + return new Point(0, 0); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotSupportedException(); } } diff --git a/Flow.Launcher/Converters/HighlightTextConverter.cs b/Flow.Launcher/Converters/HighlightTextConverter.cs index 3f02443e2e7..436f5fed53f 100644 --- a/Flow.Launcher/Converters/HighlightTextConverter.cs +++ b/Flow.Launcher/Converters/HighlightTextConverter.cs @@ -5,45 +5,44 @@ using System.Windows.Data; using System.Windows.Documents; -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +public class HighlightTextConverter : IMultiValueConverter { - public class HighlightTextConverter : IMultiValueConverter + public object Convert(object[] value, Type targetType, object parameter, CultureInfo cultureInfo) { - public object Convert(object[] value, Type targetType, object parameter, CultureInfo cultureInfo) + if (value.Length < 2) + return new Run(string.Empty); + + if (value[0] is not string text) + return new Run(string.Empty); + + if (value[1] is not List { Count: > 0 } highlightData) + // No highlight data, just return the text + return new Run(text); + + var highlightStyle = (Style)Application.Current.FindResource("HighlightStyle"); + var textBlock = new Span(); + + for (var i = 0; i < text.Length; i++) { - if (value.Length < 2) - return new Run(string.Empty); - - if (value[0] is not string text) - return new Run(string.Empty); - - if (value[1] is not List { Count: > 0 } highlightData) - // No highlight data, just return the text - return new Run(text); - - var highlightStyle = (Style)Application.Current.FindResource("HighlightStyle"); - var textBlock = new Span(); - - for (var i = 0; i < text.Length; i++) + var currentCharacter = text.Substring(i, 1); + var run = new Run(currentCharacter) { - var currentCharacter = text.Substring(i, 1); - var run = new Run(currentCharacter) - { - Style = ShouldHighlight(highlightData, i) ? highlightStyle : null - }; - textBlock.Inlines.Add(run); - } - return textBlock; + Style = ShouldHighlight(highlightData, i) ? highlightStyle : null + }; + textBlock.Inlines.Add(run); } + return textBlock; + } - public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture) - { - return new[] { DependencyProperty.UnsetValue, DependencyProperty.UnsetValue }; - } + public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture) + { + return new[] { DependencyProperty.UnsetValue, DependencyProperty.UnsetValue }; + } - private bool ShouldHighlight(List highlightData, int index) - { - return highlightData.Contains(index); - } + private bool ShouldHighlight(List highlightData, int index) + { + return highlightData.Contains(index); } } diff --git a/Flow.Launcher/Converters/IconRadiusConverter.cs b/Flow.Launcher/Converters/IconRadiusConverter.cs index d0bdc9d1c23..d26b39d6b1f 100644 --- a/Flow.Launcher/Converters/IconRadiusConverter.cs +++ b/Flow.Launcher/Converters/IconRadiusConverter.cs @@ -2,20 +2,19 @@ using System.Globalization; using System.Windows.Data; -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +public class IconRadiusConverter : IMultiValueConverter { - public class IconRadiusConverter : IMultiValueConverter + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) - { - if (values is not [double size, bool isIconCircular]) - throw new ArgumentException("IconRadiusConverter must have 2 parameters: [double, bool]"); + if (values is not [double size, bool isIconCircular]) + throw new ArgumentException("IconRadiusConverter must have 2 parameters: [double, bool]"); - return isIconCircular ? size / 2 : size; - } - public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) - { - throw new NotSupportedException(); - } + return isIconCircular ? size / 2 : size; + } + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotSupportedException(); } } diff --git a/Flow.Launcher/Converters/OpenResultHotkeyVisibilityConverter.cs b/Flow.Launcher/Converters/OpenResultHotkeyVisibilityConverter.cs index 7b7bd090631..7ab13190a3a 100644 --- a/Flow.Launcher/Converters/OpenResultHotkeyVisibilityConverter.cs +++ b/Flow.Launcher/Converters/OpenResultHotkeyVisibilityConverter.cs @@ -4,24 +4,23 @@ using System.Windows.Controls; using System.Windows.Data; -namespace Flow.Launcher.Converters -{ - [ValueConversion(typeof(bool), typeof(Visibility))] - public class OpenResultHotkeyVisibilityConverter : IValueConverter - { - private const int MaxVisibleHotkeys = 10; +namespace Flow.Launcher.Converters; - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - var number = int.MaxValue; +[ValueConversion(typeof(bool), typeof(Visibility))] +public class OpenResultHotkeyVisibilityConverter : IValueConverter +{ + private const int MaxVisibleHotkeys = 10; - if (value is ListBoxItem listBoxItem - && ItemsControl.ItemsControlFromItemContainer(listBoxItem) is ListBox listBox) - number = listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem) + 1; + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + var number = int.MaxValue; - return number <= MaxVisibleHotkeys ? Visibility.Visible : Visibility.Collapsed; - } + if (value is ListBoxItem listBoxItem + && ItemsControl.ItemsControlFromItemContainer(listBoxItem) is ListBox listBox) + number = listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem) + 1; - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new InvalidOperationException(); + return number <= MaxVisibleHotkeys ? Visibility.Visible : Visibility.Collapsed; } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new InvalidOperationException(); } diff --git a/Flow.Launcher/Converters/OrdinalConverter.cs b/Flow.Launcher/Converters/OrdinalConverter.cs index 438d4effa48..9aed2e07ba3 100644 --- a/Flow.Launcher/Converters/OrdinalConverter.cs +++ b/Flow.Launcher/Converters/OrdinalConverter.cs @@ -3,23 +3,22 @@ using System.Windows.Controls; using System.Windows.Data; -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +public class OrdinalConverter : IValueConverter { - public class OrdinalConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + if (value is not ListBoxItem listBoxItem + || ItemsControl.ItemsControlFromItemContainer(listBoxItem) is not ListBox listBox) { - if (value is not ListBoxItem listBoxItem - || ItemsControl.ItemsControlFromItemContainer(listBoxItem) is not ListBox listBox) - { - return 0; - } - - var res = listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem) + 1; - return res == 10 ? 0 : res; // 10th item => HOTKEY+0 - + return 0; } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new InvalidOperationException(); + var res = listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem) + 1; + return res == 10 ? 0 : res; // 10th item => HOTKEY+0 + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new InvalidOperationException(); } diff --git a/Flow.Launcher/Converters/QuerySuggestionBoxConverter.cs b/Flow.Launcher/Converters/QuerySuggestionBoxConverter.cs index 4a8c9e92ba3..fabd01a24d1 100644 --- a/Flow.Launcher/Converters/QuerySuggestionBoxConverter.cs +++ b/Flow.Launcher/Converters/QuerySuggestionBoxConverter.cs @@ -6,63 +6,62 @@ using Flow.Launcher.Infrastructure.Logger; using Flow.Launcher.ViewModel; -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +public class QuerySuggestionBoxConverter : IMultiValueConverter { - public class QuerySuggestionBoxConverter : IMultiValueConverter + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) - { - // values[0] is TextBox: The textbox displaying the autocomplete suggestion - // values[1] is ResultViewModel: Currently selected item in the list - // values[2] is string: Query text - if ( - values.Length != 3 || - values[0] is not TextBox queryTextBox || - values[1] is null || - values[2] is not string queryText || - string.IsNullOrEmpty(queryText) - ) - return string.Empty; - - if (values[1] is not ResultViewModel selectedItem) - return Binding.DoNothing; + // values[0] is TextBox: The textbox displaying the autocomplete suggestion + // values[1] is ResultViewModel: Currently selected item in the list + // values[2] is string: Query text + if ( + values.Length != 3 || + values[0] is not TextBox queryTextBox || + values[1] is null || + values[2] is not string queryText || + string.IsNullOrEmpty(queryText) + ) + return string.Empty; - try - { - var selectedResult = selectedItem.Result; - var selectedResultActionKeyword = string.IsNullOrEmpty(selectedResult.ActionKeywordAssigned) ? "" : selectedResult.ActionKeywordAssigned + " "; - var selectedResultPossibleSuggestion = selectedResultActionKeyword + selectedResult.Title; + if (values[1] is not ResultViewModel selectedItem) + return Binding.DoNothing; - if (!selectedResultPossibleSuggestion.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase)) - return string.Empty; + try + { + var selectedResult = selectedItem.Result; + var selectedResultActionKeyword = string.IsNullOrEmpty(selectedResult.ActionKeywordAssigned) ? "" : selectedResult.ActionKeywordAssigned + " "; + var selectedResultPossibleSuggestion = selectedResultActionKeyword + selectedResult.Title; + if (!selectedResultPossibleSuggestion.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase)) + return string.Empty; - // For AutocompleteQueryCommand. - // When user typed lower case and result title is uppercase, we still want to display suggestion - selectedItem.QuerySuggestionText = queryText + selectedResultPossibleSuggestion.Substring(queryText.Length); - // Check if Text will be larger than our QueryTextBox - Typeface typeface = new Typeface(queryTextBox.FontFamily, queryTextBox.FontStyle, queryTextBox.FontWeight, queryTextBox.FontStretch); - // TODO: Obsolete warning? - var ft = new FormattedText(queryTextBox.Text, CultureInfo.DefaultThreadCurrentCulture, System.Windows.FlowDirection.LeftToRight, typeface, queryTextBox.FontSize, Brushes.Black); + // For AutocompleteQueryCommand. + // When user typed lower case and result title is uppercase, we still want to display suggestion + selectedItem.QuerySuggestionText = queryText + selectedResultPossibleSuggestion.Substring(queryText.Length); - var offset = queryTextBox.Padding.Right; + // Check if Text will be larger than our QueryTextBox + Typeface typeface = new Typeface(queryTextBox.FontFamily, queryTextBox.FontStyle, queryTextBox.FontWeight, queryTextBox.FontStretch); + // TODO: Obsolete warning? + var ft = new FormattedText(queryTextBox.Text, CultureInfo.DefaultThreadCurrentCulture, System.Windows.FlowDirection.LeftToRight, typeface, queryTextBox.FontSize, Brushes.Black); - if (ft.Width + offset > queryTextBox.ActualWidth || queryTextBox.HorizontalOffset != 0) - return string.Empty; + var offset = queryTextBox.Padding.Right; - return selectedItem.QuerySuggestionText; - } - catch (Exception e) - { - Log.Exception(nameof(QuerySuggestionBoxConverter), "fail to convert text for suggestion box", e); + if (ft.Width + offset > queryTextBox.ActualWidth || queryTextBox.HorizontalOffset != 0) return string.Empty; - } - } - public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + return selectedItem.QuerySuggestionText; + } + catch (Exception e) { - throw new NotImplementedException(); + Log.Exception(nameof(QuerySuggestionBoxConverter), "fail to convert text for suggestion box", e); + return string.Empty; } } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } } diff --git a/Flow.Launcher/Converters/StringToKeyBindingConverter.cs b/Flow.Launcher/Converters/StringToKeyBindingConverter.cs index 22526bd82d7..21bf584e7a9 100644 --- a/Flow.Launcher/Converters/StringToKeyBindingConverter.cs +++ b/Flow.Launcher/Converters/StringToKeyBindingConverter.cs @@ -3,28 +3,27 @@ using System.Windows.Data; using System.Windows.Input; -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +class StringToKeyBindingConverter : IValueConverter { - class StringToKeyBindingConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (parameter is not string mode || value is not string hotkeyStr) - return null; - - var converter = new KeyGestureConverter(); - var key = (KeyGesture)converter.ConvertFromString(hotkeyStr); - return mode switch - { - "key" => key?.Key, - "modifiers" => key?.Modifiers, - _ => null - }; - } + if (parameter is not string mode || value is not string hotkeyStr) + return null; - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + var converter = new KeyGestureConverter(); + var key = (KeyGesture)converter.ConvertFromString(hotkeyStr); + return mode switch { - throw new NotImplementedException(); - } + "key" => key?.Key, + "modifiers" => key?.Modifiers, + _ => null + }; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Flow.Launcher/Converters/TextConverter.cs b/Flow.Launcher/Converters/TextConverter.cs index c0b34d053a3..5f0e1ea82c2 100644 --- a/Flow.Launcher/Converters/TextConverter.cs +++ b/Flow.Launcher/Converters/TextConverter.cs @@ -4,28 +4,27 @@ using Flow.Launcher.Core.Resource; using Flow.Launcher.ViewModel; -namespace Flow.Launcher.Converters +namespace Flow.Launcher.Converters; + +public class TextConverter : IValueConverter { - public class TextConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + var id = value?.ToString(); + var translationKey = id switch { - var id = value?.ToString(); - var translationKey = id switch - { - PluginStoreItemViewModel.NewRelease => "pluginStore_NewRelease", - PluginStoreItemViewModel.RecentlyUpdated => "pluginStore_RecentlyUpdated", - PluginStoreItemViewModel.None => "pluginStore_None", - PluginStoreItemViewModel.Installed => "pluginStore_Installed", - _ => null - }; - - if (translationKey is null) - return id; - - return InternationalizationManager.Instance.GetTranslation(translationKey); - } + PluginStoreItemViewModel.NewRelease => "pluginStore_NewRelease", + PluginStoreItemViewModel.RecentlyUpdated => "pluginStore_RecentlyUpdated", + PluginStoreItemViewModel.None => "pluginStore_None", + PluginStoreItemViewModel.Installed => "pluginStore_Installed", + _ => null + }; + + if (translationKey is null) + return id; - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new InvalidOperationException(); + return InternationalizationManager.Instance.GetTranslation(translationKey); } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new InvalidOperationException(); } diff --git a/Flow.Launcher/Helper/AutoStartup.cs b/Flow.Launcher/Helper/AutoStartup.cs index bf36b7f6f7a..4bff30caf03 100644 --- a/Flow.Launcher/Helper/AutoStartup.cs +++ b/Flow.Launcher/Helper/AutoStartup.cs @@ -3,57 +3,56 @@ using Flow.Launcher.Infrastructure.Logger; using Microsoft.Win32; -namespace Flow.Launcher.Helper -{ - public class AutoStartup - { - private const string StartupPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"; +namespace Flow.Launcher.Helper; - public static bool IsEnabled - { - get - { - try - { - using var key = Registry.CurrentUser.OpenSubKey(StartupPath, true); - var path = key?.GetValue(Constant.FlowLauncher) as string; - return path == Constant.ExecutablePath; - } - catch (Exception e) - { - Log.Error("AutoStartup", $"Ignoring non-critical registry error (querying if enabled): {e}"); - } - - return false; - } - } +public class AutoStartup +{ + private const string StartupPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; - public static void Disable() + public static bool IsEnabled + { + get { try { using var key = Registry.CurrentUser.OpenSubKey(StartupPath, true); - key?.DeleteValue(Constant.FlowLauncher, false); + var path = key?.GetValue(Constant.FlowLauncher) as string; + return path == Constant.ExecutablePath; } catch (Exception e) { - Log.Error("AutoStartup", $"Failed to disable auto-startup: {e}"); - throw; + Log.Error("AutoStartup", $"Ignoring non-critical registry error (querying if enabled): {e}"); } + + return false; } + } - internal static void Enable() + public static void Disable() + { + try { - try - { - using var key = Registry.CurrentUser.OpenSubKey(StartupPath, true); - key?.SetValue(Constant.FlowLauncher, $"\"{Constant.ExecutablePath}\""); - } - catch (Exception e) - { - Log.Error("AutoStartup", $"Failed to enable auto-startup: {e}"); - throw; - } + using var key = Registry.CurrentUser.OpenSubKey(StartupPath, true); + key?.DeleteValue(Constant.FlowLauncher, false); + } + catch (Exception e) + { + Log.Error("AutoStartup", $"Failed to disable auto-startup: {e}"); + throw; + } + } + + internal static void Enable() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(StartupPath, true); + key?.SetValue(Constant.FlowLauncher, $"\"{Constant.ExecutablePath}\""); + } + catch (Exception e) + { + Log.Error("AutoStartup", $"Failed to enable auto-startup: {e}"); + throw; } } } diff --git a/Flow.Launcher/Helper/DWMDropShadow.cs b/Flow.Launcher/Helper/DWMDropShadow.cs index 3a1f82d6fd8..e448acd4c9e 100644 --- a/Flow.Launcher/Helper/DWMDropShadow.cs +++ b/Flow.Launcher/Helper/DWMDropShadow.cs @@ -4,70 +4,69 @@ using System.Windows; using System.Windows.Interop; -namespace Flow.Launcher.Helper +namespace Flow.Launcher.Helper; + +public class DwmDropShadow { - public class DwmDropShadow - { - [DllImport("dwmapi.dll", PreserveSig = true)] - private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize); + [DllImport("dwmapi.dll", PreserveSig = true)] + private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize); - [DllImport("dwmapi.dll")] - private static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMarInset); + [DllImport("dwmapi.dll")] + private static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMarInset); - /// - /// Drops a standard shadow to a WPF Window, even if the window isborderless. Only works with DWM (Vista and Seven). - /// This method is much more efficient than setting AllowsTransparency to true and using the DropShadow effect, - /// as AllowsTransparency involves a huge permormance issue (hardware acceleration is turned off for all the window). - /// - /// Window to which the shadow will be applied - public static void DropShadowToWindow(Window window) + /// + /// Drops a standard shadow to a WPF Window, even if the window isborderless. Only works with DWM (Vista and Seven). + /// This method is much more efficient than setting AllowsTransparency to true and using the DropShadow effect, + /// as AllowsTransparency involves a huge permormance issue (hardware acceleration is turned off for all the window). + /// + /// Window to which the shadow will be applied + public static void DropShadowToWindow(Window window) + { + if (!DropShadow(window)) { - if (!DropShadow(window)) - { - window.SourceInitialized += window_SourceInitialized; - } + window.SourceInitialized += window_SourceInitialized; } + } - private static void window_SourceInitialized(object sender, EventArgs e) //fixed typo - { - Window window = (Window)sender; + private static void window_SourceInitialized(object sender, EventArgs e) //fixed typo + { + Window window = (Window)sender; - DropShadow(window); + DropShadow(window); - window.SourceInitialized -= window_SourceInitialized; - } + window.SourceInitialized -= window_SourceInitialized; + } - /// - /// The actual method that makes API calls to drop the shadow to the window - /// - /// Window to which the shadow will be applied - /// True if the method succeeded, false if not - private static bool DropShadow(Window window) + /// + /// The actual method that makes API calls to drop the shadow to the window + /// + /// Window to which the shadow will be applied + /// True if the method succeeded, false if not + private static bool DropShadow(Window window) + { + try { - try - { - WindowInteropHelper helper = new WindowInteropHelper(window); - int val = 2; - int ret1 = DwmSetWindowAttribute(helper.Handle, 2, ref val, 4); + WindowInteropHelper helper = new WindowInteropHelper(window); + int val = 2; + int ret1 = DwmSetWindowAttribute(helper.Handle, 2, ref val, 4); - if (ret1 == 0) - { - Margins m = new Margins { Bottom = 0, Left = 0, Right = 0, Top = 0 }; - int ret2 = DwmExtendFrameIntoClientArea(helper.Handle, ref m); - return ret2 == 0; - } - else - { - return false; - } + if (ret1 == 0) + { + Margins m = new Margins { Bottom = 0, Left = 0, Right = 0, Top = 0 }; + int ret2 = DwmExtendFrameIntoClientArea(helper.Handle, ref m); + return ret2 == 0; } - catch (Exception) + else { - // Probably dwmapi.dll not found (incompatible OS) return false; } } - + catch (Exception) + { + // Probably dwmapi.dll not found (incompatible OS) + return false; + } } -} \ No newline at end of file + +} diff --git a/Flow.Launcher/Helper/DataWebRequestFactory.cs b/Flow.Launcher/Helper/DataWebRequestFactory.cs index b3b7e9c6398..2e72ee240fd 100644 --- a/Flow.Launcher/Helper/DataWebRequestFactory.cs +++ b/Flow.Launcher/Helper/DataWebRequestFactory.cs @@ -2,68 +2,67 @@ using System.IO; using System.Net; -namespace Flow.Launcher.Helper +namespace Flow.Launcher.Helper; + +public class DataWebRequestFactory : IWebRequestCreate { - public class DataWebRequestFactory : IWebRequestCreate + class DataWebRequest : WebRequest { - class DataWebRequest : WebRequest - { - private readonly Uri m_uri; - - public DataWebRequest(Uri uri) - { - m_uri = uri; - } + private readonly Uri _uri; - public override WebResponse GetResponse() - { - return new DataWebResponse(m_uri); - } + public DataWebRequest(Uri uri) + { + _uri = uri; } - class DataWebResponse : WebResponse + public override WebResponse GetResponse() { - private readonly string m_contentType; - private readonly byte[] m_data; + return new DataWebResponse(_uri); + } + } - public DataWebResponse(Uri uri) - { - string uriString = uri.AbsoluteUri; + class DataWebResponse : WebResponse + { + private readonly string _contentType; + private readonly byte[] _data; - int commaIndex = uriString.IndexOf(','); - var headers = uriString.Substring(0, commaIndex).Split(';'); - m_contentType = headers[0]; - string dataString = uriString.Substring(commaIndex + 1); - m_data = Convert.FromBase64String(dataString); - } + public DataWebResponse(Uri uri) + { + string uriString = uri.AbsoluteUri; - public override string ContentType - { - get { return m_contentType; } - set - { - throw new NotSupportedException(); - } - } + int commaIndex = uriString.IndexOf(','); + var headers = uriString.Substring(0, commaIndex).Split(';'); + _contentType = headers[0]; + string dataString = uriString.Substring(commaIndex + 1); + _data = Convert.FromBase64String(dataString); + } - public override long ContentLength + public override string ContentType + { + get { return _contentType; } + set { - get { return m_data.Length; } - set - { - throw new NotSupportedException(); - } + throw new NotSupportedException(); } + } - public override Stream GetResponseStream() + public override long ContentLength + { + get { return _data.Length; } + set { - return new MemoryStream(m_data); + throw new NotSupportedException(); } } - public WebRequest Create(Uri uri) + public override Stream GetResponseStream() { - return new DataWebRequest(uri); + return new MemoryStream(_data); } } + + public WebRequest Create(Uri uri) + { + return new DataWebRequest(uri); + } } diff --git a/Flow.Launcher/Helper/ErrorReporting.cs b/Flow.Launcher/Helper/ErrorReporting.cs index b5da2efadba..5b79c520d60 100644 --- a/Flow.Launcher/Helper/ErrorReporting.cs +++ b/Flow.Launcher/Helper/ErrorReporting.cs @@ -4,45 +4,52 @@ using Flow.Launcher.Infrastructure; using Flow.Launcher.Infrastructure.Exception; -namespace Flow.Launcher.Helper +namespace Flow.Launcher.Helper; + +public static class ErrorReporting { - public static class ErrorReporting + private static void Report(Exception e) + { + var logger = LogManager.GetLogger("UnHandledException"); + logger.Fatal(ExceptionFormatter.FormatExcpetion(e)); + var reportWindow = new ReportWindow(e); + reportWindow.Show(); + } + + public static void UnhandledExceptionHandle(object sender, UnhandledExceptionEventArgs e) { - private static void Report(Exception e) - { - var logger = LogManager.GetLogger("UnHandledException"); - logger.Fatal(ExceptionFormatter.FormatExcpetion(e)); - var reportWindow = new ReportWindow(e); - reportWindow.Show(); - } - - public static void UnhandledExceptionHandle(object sender, UnhandledExceptionEventArgs e) - { - //handle non-ui thread exceptions - Report((Exception)e.ExceptionObject); - } - - public static void DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) - { - //handle ui thread exceptions - Report(e.Exception); - //prevent application exist, so the user can copy prompted error info - e.Handled = true; - } - - public static string RuntimeInfo() - { - var info = $"\nFlow Launcher version: {Constant.Version}" + - $"\nOS Version: {ExceptionFormatter.GetWindowsFullVersionFromRegistry()}" + - $"\nIntPtr Length: {IntPtr.Size}" + - $"\nx64: {Environment.Is64BitOperatingSystem}"; - return info; - } - - public static string DependenciesInfo() - { - var info = $"\nPython Path: {Constant.PythonPath}\nNode Path: {Constant.NodePath}"; - return info; - } + //handle non-ui thread exceptions + Report((Exception)e.ExceptionObject); + } + + public static void DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) + { + //handle ui thread exceptions + Report(e.Exception); + //prevent application exist, so the user can copy prompted error info + e.Handled = true; + } + + public static string RuntimeInfo() + { + var info = + $""" + + Flow Launcher version: {Constant.Version} + OS Version: {ExceptionFormatter.GetWindowsFullVersionFromRegistry()} + IntPtr Length: {IntPtr.Size} + x64: {Environment.Is64BitOperatingSystem} + """; + return info; + } + + public static string DependenciesInfo() + { + var info = $""" + + Python Path: {Constant.PythonPath} + Node Path: {Constant.NodePath} + """; + return info; } } diff --git a/Flow.Launcher/Helper/HotKeyMapper.cs b/Flow.Launcher/Helper/HotKeyMapper.cs index 3949d282885..21ddf276ad3 100644 --- a/Flow.Launcher/Helper/HotKeyMapper.cs +++ b/Flow.Launcher/Helper/HotKeyMapper.cs @@ -7,97 +7,96 @@ using System.Windows; using Flow.Launcher.ViewModel; -namespace Flow.Launcher.Helper +namespace Flow.Launcher.Helper; + +internal static class HotKeyMapper { - internal static class HotKeyMapper + private static Settings _settings; + private static MainViewModel _mainViewModel; + + internal static void Initialize(MainViewModel mainVM) { - private static Settings settings; - private static MainViewModel mainViewModel; + _mainViewModel = mainVM; + _settings = _mainViewModel.Settings; - internal static void Initialize(MainViewModel mainVM) - { - mainViewModel = mainVM; - settings = mainViewModel.Settings; + SetHotkey(_settings.Hotkey, OnToggleHotkey); + LoadCustomPluginHotkey(); + } - SetHotkey(settings.Hotkey, OnToggleHotkey); - LoadCustomPluginHotkey(); - } + internal static void OnToggleHotkey(object sender, HotkeyEventArgs args) + { + if (!_mainViewModel.ShouldIgnoreHotkeys()) + _mainViewModel.ToggleFlowLauncher(); + } - internal static void OnToggleHotkey(object sender, HotkeyEventArgs args) + private static void SetHotkey(string hotkeyStr, EventHandler action) + { + var hotkey = new HotkeyModel(hotkeyStr); + SetHotkey(hotkey, action); + } + + internal static void SetHotkey(HotkeyModel hotkey, EventHandler action) + { + string hotkeyStr = hotkey.ToString(); + try { - if (!mainViewModel.ShouldIgnoreHotkeys()) - mainViewModel.ToggleFlowLauncher(); + HotkeyManager.Current.AddOrReplace(hotkeyStr, hotkey.CharKey, hotkey.ModifierKeys, action); } - - private static void SetHotkey(string hotkeyStr, EventHandler action) + catch (Exception) { - var hotkey = new HotkeyModel(hotkeyStr); - SetHotkey(hotkey, action); + string errorMsg = string.Format(InternationalizationManager.Instance.GetTranslation("registerHotkeyFailed"), hotkeyStr); + string errorMsgTitle = InternationalizationManager.Instance.GetTranslation("MessageBoxTitle"); + MessageBox.Show(errorMsg,errorMsgTitle); } + } - internal static void SetHotkey(HotkeyModel hotkey, EventHandler action) + internal static void RemoveHotkey(string hotkeyStr) + { + if (!string.IsNullOrEmpty(hotkeyStr)) { - string hotkeyStr = hotkey.ToString(); - try - { - HotkeyManager.Current.AddOrReplace(hotkeyStr, hotkey.CharKey, hotkey.ModifierKeys, action); - } - catch (Exception) - { - string errorMsg = string.Format(InternationalizationManager.Instance.GetTranslation("registerHotkeyFailed"), hotkeyStr); - string errorMsgTitle = InternationalizationManager.Instance.GetTranslation("MessageBoxTitle"); - MessageBox.Show(errorMsg,errorMsgTitle); - } + HotkeyManager.Current.Remove(hotkeyStr); } + } + + internal static void LoadCustomPluginHotkey() + { + if (_settings.CustomPluginHotkeys == null) + return; - internal static void RemoveHotkey(string hotkeyStr) + foreach (CustomPluginHotkey hotkey in _settings.CustomPluginHotkeys) { - if (!string.IsNullOrEmpty(hotkeyStr)) - { - HotkeyManager.Current.Remove(hotkeyStr); - } + SetCustomQueryHotkey(hotkey); } + } - internal static void LoadCustomPluginHotkey() + internal static void SetCustomQueryHotkey(CustomPluginHotkey hotkey) + { + SetHotkey(hotkey.Hotkey, (s, e) => { - if (settings.CustomPluginHotkeys == null) + if (_mainViewModel.ShouldIgnoreHotkeys()) return; - foreach (CustomPluginHotkey hotkey in settings.CustomPluginHotkeys) - { - SetCustomQueryHotkey(hotkey); - } - } + _mainViewModel.Show(); + _mainViewModel.ChangeQueryText(hotkey.ActionKeyword, true); + }); + } - internal static void SetCustomQueryHotkey(CustomPluginHotkey hotkey) + internal static bool CheckAvailability(HotkeyModel currentHotkey) + { + try { - SetHotkey(hotkey.Hotkey, (s, e) => - { - if (mainViewModel.ShouldIgnoreHotkeys()) - return; + HotkeyManager.Current.AddOrReplace("HotkeyAvailabilityTest", currentHotkey.CharKey, currentHotkey.ModifierKeys, (sender, e) => { }); - mainViewModel.Show(); - mainViewModel.ChangeQueryText(hotkey.ActionKeyword, true); - }); + return true; } - - internal static bool CheckAvailability(HotkeyModel currentHotkey) + catch { - try - { - HotkeyManager.Current.AddOrReplace("HotkeyAvailabilityTest", currentHotkey.CharKey, currentHotkey.ModifierKeys, (sender, e) => { }); - - return true; - } - catch - { - } - finally - { - HotkeyManager.Current.Remove("HotkeyAvailabilityTest"); - } - - return false; } + finally + { + HotkeyManager.Current.Remove("HotkeyAvailabilityTest"); + } + + return false; } } diff --git a/Flow.Launcher/Helper/SingleInstance.cs b/Flow.Launcher/Helper/SingleInstance.cs index 739fed378e0..380da164751 100644 --- a/Flow.Launcher/Helper/SingleInstance.cs +++ b/Flow.Launcher/Helper/SingleInstance.cs @@ -12,375 +12,374 @@ // http://blogs.microsoft.co.il/arik/2010/05/28/wpf-single-instance-application/ // modified to allow single instace restart -namespace Flow.Launcher.Helper +namespace Flow.Launcher.Helper; + +internal enum WM { - internal enum WM - { - NULL = 0x0000, - CREATE = 0x0001, - DESTROY = 0x0002, - MOVE = 0x0003, - SIZE = 0x0005, - ACTIVATE = 0x0006, - SETFOCUS = 0x0007, - KILLFOCUS = 0x0008, - ENABLE = 0x000A, - SETREDRAW = 0x000B, - SETTEXT = 0x000C, - GETTEXT = 0x000D, - GETTEXTLENGTH = 0x000E, - PAINT = 0x000F, - CLOSE = 0x0010, - QUERYENDSESSION = 0x0011, - QUIT = 0x0012, - QUERYOPEN = 0x0013, - ERASEBKGND = 0x0014, - SYSCOLORCHANGE = 0x0015, - SHOWWINDOW = 0x0018, - ACTIVATEAPP = 0x001C, - SETCURSOR = 0x0020, - MOUSEACTIVATE = 0x0021, - CHILDACTIVATE = 0x0022, - QUEUESYNC = 0x0023, - GETMINMAXINFO = 0x0024, - - WINDOWPOSCHANGING = 0x0046, - WINDOWPOSCHANGED = 0x0047, - - CONTEXTMENU = 0x007B, - STYLECHANGING = 0x007C, - STYLECHANGED = 0x007D, - DISPLAYCHANGE = 0x007E, - GETICON = 0x007F, - SETICON = 0x0080, - NCCREATE = 0x0081, - NCDESTROY = 0x0082, - NCCALCSIZE = 0x0083, - NCHITTEST = 0x0084, - NCPAINT = 0x0085, - NCACTIVATE = 0x0086, - GETDLGCODE = 0x0087, - SYNCPAINT = 0x0088, - NCMOUSEMOVE = 0x00A0, - NCLBUTTONDOWN = 0x00A1, - NCLBUTTONUP = 0x00A2, - NCLBUTTONDBLCLK = 0x00A3, - NCRBUTTONDOWN = 0x00A4, - NCRBUTTONUP = 0x00A5, - NCRBUTTONDBLCLK = 0x00A6, - NCMBUTTONDOWN = 0x00A7, - NCMBUTTONUP = 0x00A8, - NCMBUTTONDBLCLK = 0x00A9, - - SYSKEYDOWN = 0x0104, - SYSKEYUP = 0x0105, - SYSCHAR = 0x0106, - SYSDEADCHAR = 0x0107, - COMMAND = 0x0111, - SYSCOMMAND = 0x0112, - - MOUSEMOVE = 0x0200, - LBUTTONDOWN = 0x0201, - LBUTTONUP = 0x0202, - LBUTTONDBLCLK = 0x0203, - RBUTTONDOWN = 0x0204, - RBUTTONUP = 0x0205, - RBUTTONDBLCLK = 0x0206, - MBUTTONDOWN = 0x0207, - MBUTTONUP = 0x0208, - MBUTTONDBLCLK = 0x0209, - MOUSEWHEEL = 0x020A, - XBUTTONDOWN = 0x020B, - XBUTTONUP = 0x020C, - XBUTTONDBLCLK = 0x020D, - MOUSEHWHEEL = 0x020E, - - - CAPTURECHANGED = 0x0215, - - ENTERSIZEMOVE = 0x0231, - EXITSIZEMOVE = 0x0232, - - IME_SETCONTEXT = 0x0281, - IME_NOTIFY = 0x0282, - IME_CONTROL = 0x0283, - IME_COMPOSITIONFULL = 0x0284, - IME_SELECT = 0x0285, - IME_CHAR = 0x0286, - IME_REQUEST = 0x0288, - IME_KEYDOWN = 0x0290, - IME_KEYUP = 0x0291, - - NCMOUSELEAVE = 0x02A2, - - DWMCOMPOSITIONCHANGED = 0x031E, - DWMNCRENDERINGCHANGED = 0x031F, - DWMCOLORIZATIONCOLORCHANGED = 0x0320, - DWMWINDOWMAXIMIZEDCHANGE = 0x0321, - - #region Windows 7 - DWMSENDICONICTHUMBNAIL = 0x0323, - DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326, - #endregion - - USER = 0x0400, - - // This is the hard-coded message value used by WinForms for Shell_NotifyIcon. - // It's relatively safe to reuse. - TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024 - APP = 0x8000 - } + NULL = 0x0000, + CREATE = 0x0001, + DESTROY = 0x0002, + MOVE = 0x0003, + SIZE = 0x0005, + ACTIVATE = 0x0006, + SETFOCUS = 0x0007, + KILLFOCUS = 0x0008, + ENABLE = 0x000A, + SETREDRAW = 0x000B, + SETTEXT = 0x000C, + GETTEXT = 0x000D, + GETTEXTLENGTH = 0x000E, + PAINT = 0x000F, + CLOSE = 0x0010, + QUERYENDSESSION = 0x0011, + QUIT = 0x0012, + QUERYOPEN = 0x0013, + ERASEBKGND = 0x0014, + SYSCOLORCHANGE = 0x0015, + SHOWWINDOW = 0x0018, + ACTIVATEAPP = 0x001C, + SETCURSOR = 0x0020, + MOUSEACTIVATE = 0x0021, + CHILDACTIVATE = 0x0022, + QUEUESYNC = 0x0023, + GETMINMAXINFO = 0x0024, + + WINDOWPOSCHANGING = 0x0046, + WINDOWPOSCHANGED = 0x0047, + + CONTEXTMENU = 0x007B, + STYLECHANGING = 0x007C, + STYLECHANGED = 0x007D, + DISPLAYCHANGE = 0x007E, + GETICON = 0x007F, + SETICON = 0x0080, + NCCREATE = 0x0081, + NCDESTROY = 0x0082, + NCCALCSIZE = 0x0083, + NCHITTEST = 0x0084, + NCPAINT = 0x0085, + NCACTIVATE = 0x0086, + GETDLGCODE = 0x0087, + SYNCPAINT = 0x0088, + NCMOUSEMOVE = 0x00A0, + NCLBUTTONDOWN = 0x00A1, + NCLBUTTONUP = 0x00A2, + NCLBUTTONDBLCLK = 0x00A3, + NCRBUTTONDOWN = 0x00A4, + NCRBUTTONUP = 0x00A5, + NCRBUTTONDBLCLK = 0x00A6, + NCMBUTTONDOWN = 0x00A7, + NCMBUTTONUP = 0x00A8, + NCMBUTTONDBLCLK = 0x00A9, + + SYSKEYDOWN = 0x0104, + SYSKEYUP = 0x0105, + SYSCHAR = 0x0106, + SYSDEADCHAR = 0x0107, + COMMAND = 0x0111, + SYSCOMMAND = 0x0112, + + MOUSEMOVE = 0x0200, + LBUTTONDOWN = 0x0201, + LBUTTONUP = 0x0202, + LBUTTONDBLCLK = 0x0203, + RBUTTONDOWN = 0x0204, + RBUTTONUP = 0x0205, + RBUTTONDBLCLK = 0x0206, + MBUTTONDOWN = 0x0207, + MBUTTONUP = 0x0208, + MBUTTONDBLCLK = 0x0209, + MOUSEWHEEL = 0x020A, + XBUTTONDOWN = 0x020B, + XBUTTONUP = 0x020C, + XBUTTONDBLCLK = 0x020D, + MOUSEHWHEEL = 0x020E, + + + CAPTURECHANGED = 0x0215, + + ENTERSIZEMOVE = 0x0231, + EXITSIZEMOVE = 0x0232, + + IME_SETCONTEXT = 0x0281, + IME_NOTIFY = 0x0282, + IME_CONTROL = 0x0283, + IME_COMPOSITIONFULL = 0x0284, + IME_SELECT = 0x0285, + IME_CHAR = 0x0286, + IME_REQUEST = 0x0288, + IME_KEYDOWN = 0x0290, + IME_KEYUP = 0x0291, + + NCMOUSELEAVE = 0x02A2, + + DWMCOMPOSITIONCHANGED = 0x031E, + DWMNCRENDERINGCHANGED = 0x031F, + DWMCOLORIZATIONCOLORCHANGED = 0x0320, + DWMWINDOWMAXIMIZEDCHANGE = 0x0321, + + #region Windows 7 + DWMSENDICONICTHUMBNAIL = 0x0323, + DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326, + #endregion + + USER = 0x0400, + + // This is the hard-coded message value used by WinForms for Shell_NotifyIcon. + // It's relatively safe to reuse. + TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024 + APP = 0x8000 +} - [SuppressUnmanagedCodeSecurity] - internal static class NativeMethods - { - /// - /// Delegate declaration that matches WndProc signatures. - /// - public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled); +[SuppressUnmanagedCodeSecurity] +internal static class NativeMethods +{ + /// + /// Delegate declaration that matches WndProc signatures. + /// + public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled); - [DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)] - private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs); + [DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)] + private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs); - [DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)] - private static extern IntPtr _LocalFree(IntPtr hMem); + [DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)] + private static extern IntPtr _LocalFree(IntPtr hMem); - public static string[] CommandLineToArgvW(string cmdLine) + public static string[] CommandLineToArgvW(string cmdLine) + { + IntPtr argv = IntPtr.Zero; + try { - IntPtr argv = IntPtr.Zero; - try - { - int numArgs = 0; - - argv = _CommandLineToArgvW(cmdLine, out numArgs); - if (argv == IntPtr.Zero) - { - throw new Win32Exception(); - } - var result = new string[numArgs]; + int numArgs = 0; - for (int i = 0; i < numArgs; i++) - { - IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr))); - result[i] = Marshal.PtrToStringUni(currArg); - } - - return result; - } - finally + argv = _CommandLineToArgvW(cmdLine, out numArgs); + if (argv == IntPtr.Zero) { + throw new Win32Exception(); + } + var result = new string[numArgs]; - IntPtr p = _LocalFree(argv); - // Otherwise LocalFree failed. - // Assert.AreEqual(IntPtr.Zero, p); + for (int i = 0; i < numArgs; i++) + { + IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr))); + result[i] = Marshal.PtrToStringUni(currArg); } + + return result; + } + finally + { + + IntPtr p = _LocalFree(argv); + // Otherwise LocalFree failed. + // Assert.AreEqual(IntPtr.Zero, p); } + } + +} - } +public interface ISingleInstanceApp +{ + void OnSecondAppStarted(); +} - public interface ISingleInstanceApp - { - void OnSecondAppStarted(); - } +/// +/// This class checks to make sure that only one instance of +/// this application is running at a time. +/// +/// +/// Note: this class should be used with some caution, because it does no +/// security checking. For example, if one instance of an app that uses this class +/// is running as Administrator, any other instance, even if it is not +/// running as Administrator, can activate it with command line arguments. +/// For most apps, this will not be much of an issue. +/// +public static class SingleInstance + where TApplication: Application , ISingleInstanceApp + +{ + #region Private Fields /// - /// This class checks to make sure that only one instance of - /// this application is running at a time. + /// String delimiter used in channel names. /// - /// - /// Note: this class should be used with some caution, because it does no - /// security checking. For example, if one instance of an app that uses this class - /// is running as Administrator, any other instance, even if it is not - /// running as Administrator, can activate it with command line arguments. - /// For most apps, this will not be much of an issue. - /// - public static class SingleInstance - where TApplication: Application , ISingleInstanceApp - - { - #region Private Fields - - /// - /// String delimiter used in channel names. - /// - private const string Delimiter = ":"; + private const string Delimiter = ":"; - /// - /// Suffix to the channel name. - /// - private const string ChannelNameSuffix = "SingeInstanceIPCChannel"; + /// + /// Suffix to the channel name. + /// + private const string ChannelNameSuffix = "SingeInstanceIPCChannel"; - /// - /// Application mutex. - /// - internal static Mutex singleInstanceMutex; + /// + /// Application mutex. + /// + internal static Mutex singleInstanceMutex; - #endregion + #endregion - #region Public Properties + #region Public Properties - #endregion + #endregion - #region Public Methods + #region Public Methods - /// - /// Checks if the instance of the application attempting to start is the first instance. - /// If not, activates the first instance. - /// - /// True if this is the first instance of the application. - public static bool InitializeAsFirstInstance( string uniqueName ) - { - // Build unique application Id and the IPC channel name. - string applicationIdentifier = uniqueName + Environment.UserName; + /// + /// Checks if the instance of the application attempting to start is the first instance. + /// If not, activates the first instance. + /// + /// True if this is the first instance of the application. + public static bool InitializeAsFirstInstance( string uniqueName ) + { + // Build unique application Id and the IPC channel name. + string applicationIdentifier = uniqueName + Environment.UserName; - string channelName = String.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix); + string channelName = String.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix); - // Create mutex based on unique application Id to check if this is the first instance of the application. - bool firstInstance; - singleInstanceMutex = new Mutex(true, applicationIdentifier, out firstInstance); - if (firstInstance) - { - _ = CreateRemoteService(channelName); - return true; - } - else - { - _ = SignalFirstInstance(channelName); - return false; - } + // Create mutex based on unique application Id to check if this is the first instance of the application. + bool firstInstance; + singleInstanceMutex = new Mutex(true, applicationIdentifier, out firstInstance); + if (firstInstance) + { + _ = CreateRemoteService(channelName); + return true; } - - /// - /// Cleans up single-instance code, clearing shared resources, mutexes, etc. - /// - public static void Cleanup() + else { - singleInstanceMutex?.ReleaseMutex(); + _ = SignalFirstInstance(channelName); + return false; } + } - #endregion + /// + /// Cleans up single-instance code, clearing shared resources, mutexes, etc. + /// + public static void Cleanup() + { + singleInstanceMutex?.ReleaseMutex(); + } + + #endregion - #region Private Methods + #region Private Methods - /// - /// Gets command line args - for ClickOnce deployed applications, command line args may not be passed directly, they have to be retrieved. - /// - /// List of command line arg strings. - private static IList GetCommandLineArgs( string uniqueApplicationName ) + /// + /// Gets command line args - for ClickOnce deployed applications, command line args may not be passed directly, they have to be retrieved. + /// + /// List of command line arg strings. + private static IList GetCommandLineArgs( string uniqueApplicationName ) + { + string[] args = null; + + try + { + // The application was not clickonce deployed, get args from standard API's + args = Environment.GetCommandLineArgs(); + } + catch (NotSupportedException) { - string[] args = null; - try - { - // The application was not clickonce deployed, get args from standard API's - args = Environment.GetCommandLineArgs(); - } - catch (NotSupportedException) + // The application was clickonce deployed + // Clickonce deployed apps cannot recieve traditional commandline arguments + // As a workaround commandline arguments can be written to a shared location before + // the app is launched and the app can obtain its commandline arguments from the + // shared location + string appFolderPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName); + + string cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt"); + if (File.Exists(cmdLinePath)) { - - // The application was clickonce deployed - // Clickonce deployed apps cannot recieve traditional commandline arguments - // As a workaround commandline arguments can be written to a shared location before - // the app is launched and the app can obtain its commandline arguments from the - // shared location - string appFolderPath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName); - - string cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt"); - if (File.Exists(cmdLinePath)) + try { - try - { - using (TextReader reader = new StreamReader(cmdLinePath, Encoding.Unicode)) - { - args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd()); - } - - File.Delete(cmdLinePath); - } - catch (IOException) + using (TextReader reader = new StreamReader(cmdLinePath, Encoding.Unicode)) { + args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd()); } + + File.Delete(cmdLinePath); + } + catch (IOException) + { } } + } - if (args == null) - { + if (args == null) + { args = new string[] { }; - } - - return new List(args); } - /// - /// Creates a remote server pipe for communication. - /// Once receives signal from client, will activate first instance. - /// - /// Application's IPC channel name. - private static async Task CreateRemoteService(string channelName) + return new List(args); + } + + /// + /// Creates a remote server pipe for communication. + /// Once receives signal from client, will activate first instance. + /// + /// Application's IPC channel name. + private static async Task CreateRemoteService(string channelName) + { + using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(channelName, PipeDirection.In)) { - using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(channelName, PipeDirection.In)) + while(true) { - while(true) + // Wait for connection to the pipe + await pipeServer.WaitForConnectionAsync(); + if (Application.Current != null) { - // Wait for connection to the pipe - await pipeServer.WaitForConnectionAsync(); - if (Application.Current != null) - { - // Do an asynchronous call to ActivateFirstInstance function - Application.Current.Dispatcher.Invoke(ActivateFirstInstance); - } - // Disconect client - pipeServer.Disconnect(); + // Do an asynchronous call to ActivateFirstInstance function + Application.Current.Dispatcher.Invoke(ActivateFirstInstance); } + // Disconect client + pipeServer.Disconnect(); } } + } - /// - /// Creates a client pipe and sends a signal to server to launch first instance - /// - /// Application's IPC channel name. - /// - /// Command line arguments for the second instance, passed to the first instance to take appropriate action. - /// - private static async Task SignalFirstInstance(string channelName) + /// + /// Creates a client pipe and sends a signal to server to launch first instance + /// + /// Application's IPC channel name. + /// + /// Command line arguments for the second instance, passed to the first instance to take appropriate action. + /// + private static async Task SignalFirstInstance(string channelName) + { + // Create a client pipe connected to server + using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", channelName, PipeDirection.Out)) { - // Create a client pipe connected to server - using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", channelName, PipeDirection.Out)) - { - // Connect to the available pipe - await pipeClient.ConnectAsync(0); - } + // Connect to the available pipe + await pipeClient.ConnectAsync(0); } + } - /// - /// Callback for activating first instance of the application. - /// - /// Callback argument. - /// Always null. - private static object ActivateFirstInstanceCallback(object o) - { - ActivateFirstInstance(); - return null; - } + /// + /// Callback for activating first instance of the application. + /// + /// Callback argument. + /// Always null. + private static object ActivateFirstInstanceCallback(object o) + { + ActivateFirstInstance(); + return null; + } - /// - /// Activates the first instance of the application with arguments from a second instance. - /// - /// List of arguments to supply the first instance of the application. - private static void ActivateFirstInstance() + /// + /// Activates the first instance of the application with arguments from a second instance. + /// + /// List of arguments to supply the first instance of the application. + private static void ActivateFirstInstance() + { + // Set main window state and process command line args + if (Application.Current == null) { - // Set main window state and process command line args - if (Application.Current == null) - { - return; - } - - ((TApplication)Application.Current).OnSecondAppStarted(); + return; } - #endregion + ((TApplication)Application.Current).OnSecondAppStarted(); } + + #endregion } diff --git a/Flow.Launcher/Helper/SingletonWindowOpener.cs b/Flow.Launcher/Helper/SingletonWindowOpener.cs index 8efc9be9923..b5c2d8b55a7 100644 --- a/Flow.Launcher/Helper/SingletonWindowOpener.cs +++ b/Flow.Launcher/Helper/SingletonWindowOpener.cs @@ -2,27 +2,26 @@ using System.Linq; using System.Windows; -namespace Flow.Launcher.Helper +namespace Flow.Launcher.Helper; + +public static class SingletonWindowOpener { - public static class SingletonWindowOpener + public static T Open(params object[] args) where T : Window { - public static T Open(params object[] args) where T : Window - { - var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.GetType() == typeof(T)) - ?? (T)Activator.CreateInstance(typeof(T), args); + var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.GetType() == typeof(T)) + ?? (T)Activator.CreateInstance(typeof(T), args); - // Fix UI bug - // Add `window.WindowState = WindowState.Normal` - // If only use `window.Show()`, Settings-window doesn't show when minimized in taskbar - // Not sure why this works tho - // Probably because, when `.Show()` fails, `window.WindowState == Minimized` (not `Normal`) - // https://stackoverflow.com/a/59719760/4230390 - window.WindowState = WindowState.Normal; - window.Show(); + // Fix UI bug + // Add `window.WindowState = WindowState.Normal` + // If only use `window.Show()`, Settings-window doesn't show when minimized in taskbar + // Not sure why this works tho + // Probably because, when `.Show()` fails, `window.WindowState == Minimized` (not `Normal`) + // https://stackoverflow.com/a/59719760/4230390 + window.WindowState = WindowState.Normal; + window.Show(); - window.Focus(); + window.Focus(); - return (T)window; - } + return (T)window; } -} \ No newline at end of file +} diff --git a/Flow.Launcher/Helper/SyntaxSugars.cs b/Flow.Launcher/Helper/SyntaxSugars.cs index 7e034942275..41250dadf37 100644 --- a/Flow.Launcher/Helper/SyntaxSugars.cs +++ b/Flow.Launcher/Helper/SyntaxSugars.cs @@ -1,24 +1,23 @@ using System; -namespace Flow.Launcher.Helper +namespace Flow.Launcher.Helper; + +public static class SyntaxSugars { - public static class SyntaxSugars + public static TResult CallOrRescueDefault(Func callback) { - public static TResult CallOrRescueDefault(Func callback) + return CallOrRescueDefault(callback, default(TResult)); + } + + public static TResult CallOrRescueDefault(Func callback, TResult def) + { + try { - return CallOrRescueDefault(callback, default(TResult)); + return callback(); } - - public static TResult CallOrRescueDefault(Func callback, TResult def) + catch { - try - { - return callback(); - } - catch - { - return def; - } + return def; } } } diff --git a/Flow.Launcher/Helper/WallpaperPathRetrieval.cs b/Flow.Launcher/Helper/WallpaperPathRetrieval.cs index 9e5d77283c4..e08e227cc33 100644 --- a/Flow.Launcher/Helper/WallpaperPathRetrieval.cs +++ b/Flow.Launcher/Helper/WallpaperPathRetrieval.cs @@ -5,44 +5,43 @@ using System.Windows.Media; using Microsoft.Win32; -namespace Flow.Launcher.Helper +namespace Flow.Launcher.Helper; + +public static class WallpaperPathRetrieval { - public static class WallpaperPathRetrieval - { - [DllImport("user32.dll", CharSet = CharSet.Unicode)] - private static extern Int32 SystemParametersInfo(UInt32 action, - Int32 uParam, StringBuilder vParam, UInt32 winIni); - private static readonly UInt32 SPI_GETDESKWALLPAPER = 0x73; - private static int MAX_PATH = 260; + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern Int32 SystemParametersInfo(UInt32 action, + Int32 uParam, StringBuilder vParam, UInt32 winIni); + private static readonly UInt32 SPI_GETDESKWALLPAPER = 0x73; + private static int MAX_PATH = 260; - public static string GetWallpaperPath() - { - var wallpaper = new StringBuilder(MAX_PATH); - SystemParametersInfo(SPI_GETDESKWALLPAPER, MAX_PATH, wallpaper, 0); + public static string GetWallpaperPath() + { + var wallpaper = new StringBuilder(MAX_PATH); + SystemParametersInfo(SPI_GETDESKWALLPAPER, MAX_PATH, wallpaper, 0); - var str = wallpaper.ToString(); - if (string.IsNullOrEmpty(str)) - return null; + var str = wallpaper.ToString(); + if (string.IsNullOrEmpty(str)) + return null; - return str; - } + return str; + } - public static Color GetWallpaperColor() + public static Color GetWallpaperColor() + { + RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Colors", true); + var result = key?.GetValue("Background", null); + if (result is string strResult) { - RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Colors", true); - var result = key.GetValue(@"Background", null); - if (result != null && result is string) + try + { + var parts = strResult.Trim().Split(new[] {' '}, 3).Select(byte.Parse).ToList(); + return Color.FromRgb(parts[0], parts[1], parts[2]); + } + catch { - try - { - var parts = result.ToString().Trim().Split(new[] {' '}, 3).Select(byte.Parse).ToList(); - return Color.FromRgb(parts[0], parts[1], parts[2]); - } - catch - { - } } - return Colors.Transparent; } + return Colors.Transparent; } } diff --git a/Flow.Launcher/Helper/WindowsInteropHelper.cs b/Flow.Launcher/Helper/WindowsInteropHelper.cs index 16a96cd640d..89fbec967a8 100644 --- a/Flow.Launcher/Helper/WindowsInteropHelper.cs +++ b/Flow.Launcher/Helper/WindowsInteropHelper.cs @@ -8,156 +8,152 @@ using System.Windows.Media; using Point = System.Windows.Point; -namespace Flow.Launcher.Helper +namespace Flow.Launcher.Helper; + +public class WindowsInteropHelper { - public class WindowsInteropHelper + private const int GWL_STYLE = -16; //WPF's Message code for Title Bar's Style + private const int WS_SYSMENU = 0x80000; //WPF's Message code for System Menu + private static IntPtr _hwnd_shell; + private static IntPtr _hwnd_desktop; + + //Accessors for shell and desktop handlers + //Will set the variables once and then will return them + private static IntPtr HWND_SHELL { - private const int GWL_STYLE = -16; //WPF's Message code for Title Bar's Style - private const int WS_SYSMENU = 0x80000; //WPF's Message code for System Menu - private static IntPtr _hwnd_shell; - private static IntPtr _hwnd_desktop; - - //Accessors for shell and desktop handlers - //Will set the variables once and then will return them - private static IntPtr HWND_SHELL + get { - get - { - return _hwnd_shell != IntPtr.Zero ? _hwnd_shell : _hwnd_shell = GetShellWindow(); - } + return _hwnd_shell != IntPtr.Zero ? _hwnd_shell : _hwnd_shell = GetShellWindow(); } - private static IntPtr HWND_DESKTOP + } + private static IntPtr HWND_DESKTOP + { + get { - get - { - return _hwnd_desktop != IntPtr.Zero ? _hwnd_desktop : _hwnd_desktop = GetDesktopWindow(); - } + return _hwnd_desktop != IntPtr.Zero ? _hwnd_desktop : _hwnd_desktop = GetDesktopWindow(); } + } + + [DllImport("user32.dll", SetLastError = true)] + internal static extern int GetWindowLong(IntPtr hWnd, int nIndex); - [DllImport("user32.dll", SetLastError = true)] - internal static extern int GetWindowLong(IntPtr hWnd, int nIndex); - - [DllImport("user32.dll")] - internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); + [DllImport("user32.dll")] + internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); - [DllImport("user32.dll")] - internal static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] + internal static extern IntPtr GetForegroundWindow(); - [DllImport("user32.dll")] - internal static extern IntPtr GetDesktopWindow(); + [DllImport("user32.dll")] + internal static extern IntPtr GetDesktopWindow(); - [DllImport("user32.dll")] - internal static extern IntPtr GetShellWindow(); + [DllImport("user32.dll")] + internal static extern IntPtr GetShellWindow(); - [DllImport("user32.dll", SetLastError = true)] - internal static extern int GetWindowRect(IntPtr hwnd, out RECT rc); + [DllImport("user32.dll", SetLastError = true)] + internal static extern int GetWindowRect(IntPtr hwnd, out RECT rc); - [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] - internal static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] + internal static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); - [DllImport("user32.DLL")] - public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); + [DllImport("user32.DLL")] + public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); - const string WINDOW_CLASS_CONSOLE = "ConsoleWindowClass"; - const string WINDOW_CLASS_WINTAB = "Flip3D"; - const string WINDOW_CLASS_PROGMAN = "Progman"; - const string WINDOW_CLASS_WORKERW = "WorkerW"; + const string WINDOW_CLASS_CONSOLE = "ConsoleWindowClass"; + const string WINDOW_CLASS_WINTAB = "Flip3D"; + const string WINDOW_CLASS_PROGMAN = "Progman"; + const string WINDOW_CLASS_WORKERW = "WorkerW"; - public static bool IsWindowFullscreen() + public static bool IsWindowFullscreen() + { + //get current active window + IntPtr hWnd = GetForegroundWindow(); + + if (hWnd.Equals(IntPtr.Zero)) { - //get current active window - IntPtr hWnd = GetForegroundWindow(); + return false; + } - if (!hWnd.Equals(IntPtr.Zero)) - { - //if current active window is NOT desktop or shell - if (!(hWnd.Equals(HWND_DESKTOP) || hWnd.Equals(HWND_SHELL))) - { - StringBuilder sb = new StringBuilder(256); - GetClassName(hWnd, sb, sb.Capacity); - string windowClass = sb.ToString(); - - //for Win+Tab (Flip3D) - if (windowClass == WINDOW_CLASS_WINTAB) - { - return false; - } - - RECT appBounds; - GetWindowRect(hWnd, out appBounds); - - //for console (ConsoleWindowClass), we have to check for negative dimensions - if (windowClass == WINDOW_CLASS_CONSOLE) - { - return appBounds.Top < 0 && appBounds.Bottom < 0; - } - - //for desktop (Progman or WorkerW, depends on the system), we have to check - if (windowClass == WINDOW_CLASS_PROGMAN || windowClass == WINDOW_CLASS_WORKERW) - { - IntPtr hWndDesktop = FindWindowEx(hWnd, IntPtr.Zero, "SHELLDLL_DefView", null); - hWndDesktop = FindWindowEx(hWndDesktop, IntPtr.Zero, "SysListView32", "FolderView"); - if (!hWndDesktop.Equals(IntPtr.Zero)) - { - return false; - } - } - - Rectangle screenBounds = Screen.FromHandle(hWnd).Bounds; - if ((appBounds.Bottom - appBounds.Top) == screenBounds.Height && (appBounds.Right - appBounds.Left) == screenBounds.Width) - { - return true; - } - } - } + //if current active window is desktop or shell, exit early + if (hWnd.Equals(HWND_DESKTOP) || hWnd.Equals(HWND_SHELL)) + { + return false; + } + + StringBuilder sb = new StringBuilder(256); + GetClassName(hWnd, sb, sb.Capacity); + string windowClass = sb.ToString(); + //for Win+Tab (Flip3D) + if (windowClass == WINDOW_CLASS_WINTAB) + { return false; } - /// - /// disable windows toolbar's control box - /// this will also disable system menu with Alt+Space hotkey - /// - public static void DisableControlBox(Window win) + RECT appBounds; + GetWindowRect(hWnd, out appBounds); + + //for console (ConsoleWindowClass), we have to check for negative dimensions + if (windowClass == WINDOW_CLASS_CONSOLE) { - var hwnd = new WindowInteropHelper(win).Handle; - SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); + return appBounds.Top < 0 && appBounds.Bottom < 0; } - /// - /// Transforms pixels to Device Independent Pixels used by WPF - /// - /// current window, required to get presentation source - /// horizontal position in pixels - /// vertical position in pixels - /// point containing device independent pixels - public static Point TransformPixelsToDIP(Visual visual, double unitX, double unitY) + //for desktop (Progman or WorkerW, depends on the system), we have to check + if (windowClass is WINDOW_CLASS_PROGMAN or WINDOW_CLASS_WORKERW) { - Matrix matrix; - var source = PresentationSource.FromVisual(visual); - if (source != null) + IntPtr hWndDesktop = FindWindowEx(hWnd, IntPtr.Zero, "SHELLDLL_DefView", null); + hWndDesktop = FindWindowEx(hWndDesktop, IntPtr.Zero, "SysListView32", "FolderView"); + if (!hWndDesktop.Equals(IntPtr.Zero)) { - matrix = source.CompositionTarget.TransformFromDevice; + return false; } - else - { - using (var src = new HwndSource(new HwndSourceParameters())) - { - matrix = src.CompositionTarget.TransformFromDevice; - } - } - return new Point((int)(matrix.M11 * unitX), (int)(matrix.M22 * unitY)); } + Rectangle screenBounds = Screen.FromHandle(hWnd).Bounds; + return (appBounds.Bottom - appBounds.Top) == screenBounds.Height && (appBounds.Right - appBounds.Left) == screenBounds.Width; + } - [StructLayout(LayoutKind.Sequential)] - public struct RECT + /// + /// disable windows toolbar's control box + /// this will also disable system menu with Alt+Space hotkey + /// + public static void DisableControlBox(Window win) + { + var hwnd = new WindowInteropHelper(win).Handle; + SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); + } + + /// + /// Transforms pixels to Device Independent Pixels used by WPF + /// + /// current window, required to get presentation source + /// horizontal position in pixels + /// vertical position in pixels + /// point containing device independent pixels + public static Point TransformPixelsToDIP(Visual visual, double unitX, double unitY) + { + Matrix matrix; + var source = PresentationSource.FromVisual(visual); + if (source is not null) + { + matrix = source.CompositionTarget.TransformFromDevice; + } + else { - public int Left; - public int Top; - public int Right; - public int Bottom; + using var src = new HwndSource(new HwndSourceParameters()); + matrix = src.CompositionTarget.TransformFromDevice; } + return new Point((int)(matrix.M11 * unitX), (int)(matrix.M22 * unitY)); + } + + + [StructLayout(LayoutKind.Sequential)] + public struct RECT + { + public int Left; + public int Top; + public int Right; + public int Bottom; } }