[fxcop] Wox.Infrastructure (#7590)

* CA1052: Static holder types should be Static or NotInheritable

* CA1041: Provide ObsoleteAttribute message

* CA1062: Validate arguments of public methods

* CA1304: Specify CultureInfo / CA1305: Specify IFormatProvider / CA1307: Specify StringComparison for clarity

* CA1802: Use Literals Where Appropriate

* CA1820: Test for empty strings using string length

* CA1707: Identifiers should not contain underscores

* CA1805: Do not initialize unnecessarily.

* CA1822: Mark members as static

* CA2227: Collection properties should be read only

* CA1054: URI parameters should not be strings

* CA1031: Do not catch general exception types

* CA1060: Move P/Invokes to NativeMethods class

* CA1308: Normalize strings to uppercase

* CA2000: Dispose objects before losing scope / CA2234: Pass System.Uri objects instead of strings

* CA2234: Pass System.Uri objects instead of strings

* CA1044: Properties should not be write only

* CA1716: Identifiers should not match keywords

* CA2007: Do not directly await a Task

* CA2007: Do not directly await a Task (Suppressed)

* CA5350: Do Not Use Weak Cryptographic Algorithms (Suppressed)

* CA1724: Type names should not match namespaces (renamed Settings.cs to PowerToysRunSettings.cs)

* CA1033: Interface methods should be callable by child types (Added sealed modifier to class)

* CA1724: Type names should not match namespaces (Renamed Plugin.cs to RunPlugin.cs)

* CA1724: Type names should not match namespaces (Renamed Http.cs to HttpClient.cs)

* CA5364: Do not use deprecated security protocols (Remove unused code)

* Enabled FxCopAnalyzer for Wox.Infrastructure

* fixed comment

* Addressed comments

- Changed Ordinal to InvariantCulture
- Added comments
- Removed unused obsolete code
- Removed unused method (CA2007: Do not directly await a Task)

* Addressed comments - fixed justification for CA1031 suppression

* Addressed comments - Fixed justification for CA1031 suppression in Wox.Core/Wox.Plugin
This commit is contained in:
Avneet Kaur
2020-10-29 17:52:35 -07:00
committed by GitHub
parent 5015642b6d
commit ec8ead8183
41 changed files with 293 additions and 227 deletions

View File

@@ -80,7 +80,7 @@ namespace Microsoft.Plugin.Program.Storage
var support = Environment.OSVersion.Version.Major >= windows10.Major;
var applications = support ? Programs.UWP.All() : Array.Empty<UWPApplication>();
Set(applications);
SetList(applications);
}
public void Save()
@@ -91,7 +91,7 @@ namespace Microsoft.Plugin.Program.Storage
public void Load()
{
var items = _storage.TryLoad(Array.Empty<UWPApplication>());
Set(items);
SetList(items);
}
}
}

View File

@@ -225,7 +225,7 @@ namespace Microsoft.Plugin.Program.Storage
public void IndexPrograms()
{
var applications = Programs.Win32Program.All(_settings);
Set(applications);
SetList(applications);
}
public void Save()
@@ -236,7 +236,7 @@ namespace Microsoft.Plugin.Program.Storage
public void Load()
{
var items = _storage.TryLoad(Array.Empty<Win32Program>());
Set(items);
SetList(items);
}
}
}

View File

@@ -29,7 +29,7 @@ namespace PowerLauncher
private const string Unique = "PowerLauncher_Unique_Application_Mutex";
private static bool _disposed;
private Settings _settings;
private PowerToysRunSettings _settings;
private MainViewModel _mainVM;
private MainWindow _mainWindow;
private ThemeManager _themeManager;
@@ -107,7 +107,7 @@ namespace PowerLauncher
Current.MainWindow.Title = Constant.ExeFileName;
// main windows needs initialized before theme change because of blur settings
Http.Proxy = _settings.Proxy;
HttpClient.Proxy = _settings.Proxy;
RegisterExitEvents();

View File

@@ -22,14 +22,14 @@ namespace PowerLauncher
{
public partial class MainWindow : IDisposable
{
private readonly Settings _settings;
private readonly PowerToysRunSettings _settings;
private readonly MainViewModel _viewModel;
private bool _isTextSetProgrammatically;
private bool _deletePressed;
private Timer _firstDeleteTimer = new Timer();
private bool _coldStateHotkeyPressed;
public MainWindow(Settings settings, MainViewModel mainVM)
public MainWindow(PowerToysRunSettings settings, MainViewModel mainVM)
: this()
{
DataContext = mainVM;

View File

@@ -27,10 +27,11 @@ namespace PowerLauncher
private const int MaxRetries = 10;
private static readonly object _watcherSyncObject = new object();
private readonly FileSystemWatcher _watcher;
private readonly Settings _settings;
private readonly PowerToysRunSettings _settings;
private readonly ThemeManager _themeManager;
public SettingsWatcher(Settings settings, ThemeManager themeManager)
public SettingsWatcher(PowerToysRunSettings settings, ThemeManager themeManager)
{
_settingsUtils = new SettingsUtils(new SystemIOProvider());
_settings = settings;

View File

@@ -36,7 +36,7 @@ namespace PowerLauncher.ViewModel
private readonly WoxJsonStorage<QueryHistory> _historyItemsStorage;
private readonly WoxJsonStorage<UserSelectedRecord> _userSelectedRecordStorage;
private readonly WoxJsonStorage<TopMostRecord> _topMostRecordStorage;
private readonly Settings _settings;
private readonly PowerToysRunSettings _settings;
private readonly QueryHistory _history;
private readonly UserSelectedRecord _userSelectedRecord;
private readonly TopMostRecord _topMostRecord;
@@ -53,7 +53,7 @@ namespace PowerLauncher.ViewModel
internal HotkeyManager HotkeyManager { get; set; }
public MainViewModel(Settings settings)
public MainViewModel(PowerToysRunSettings settings)
{
_saved = false;
_queryTextBeforeLeaveResults = string.Empty;
@@ -87,7 +87,7 @@ namespace PowerLauncher.ViewModel
HotkeyManager = new HotkeyManager();
_settings.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(Settings.Hotkey))
if (e.PropertyName == nameof(PowerToysRunSettings.Hotkey))
{
Application.Current.Dispatcher.Invoke(() =>
{

View File

@@ -20,7 +20,7 @@ namespace PowerLauncher.ViewModel
{
private readonly object _collectionLock = new object();
private readonly Settings _settings;
private readonly PowerToysRunSettings _settings;
public ResultsViewModel()
{
@@ -28,7 +28,7 @@ namespace PowerLauncher.ViewModel
BindingOperations.EnableCollectionSynchronization(Results, _collectionLock);
}
public ResultsViewModel(Settings settings)
public ResultsViewModel(PowerToysRunSettings settings)
: this()
{
_settings = settings ?? throw new ArgumentNullException(nameof(settings));

View File

@@ -11,11 +11,11 @@ namespace PowerLauncher.ViewModel
{
public class SettingWindowViewModel : BaseModel
{
private readonly WoxJsonStorage<Settings> _storage;
private readonly WoxJsonStorage<PowerToysRunSettings> _storage;
public SettingWindowViewModel()
{
_storage = new WoxJsonStorage<Settings>();
_storage = new WoxJsonStorage<PowerToysRunSettings>();
Settings = _storage.Load();
Settings.PropertyChanged += (s, e) =>
{
@@ -26,7 +26,7 @@ namespace PowerLauncher.ViewModel
};
}
public Settings Settings { get; set; }
public PowerToysRunSettings Settings { get; set; }
public void Save()
{

View File

@@ -32,7 +32,7 @@ namespace Wox.Core.Plugin
return PluginMetadatas;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "All exception information is being logged")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
private static void ParsePluginConfigs(IEnumerable<string> directories)
{
// todo use linq when diable plugin is implemented since parallel.foreach + list is not thread saft
@@ -60,7 +60,7 @@ namespace Wox.Core.Plugin
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "All exception information is being logged")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
private static PluginMetadata GetPluginMetadata(string pluginDirectory)
{
string configPath = Path.Combine(pluginDirectory, PluginConfigName);

View File

@@ -98,7 +98,7 @@ namespace Wox.Core.Plugin
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "All exception information is being logged")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
private static PluginMetadata GetMetadataFromJson(string pluginDirectory)
{
string configPath = Path.Combine(pluginDirectory, "plugin.json");

View File

@@ -88,7 +88,7 @@ namespace Wox.Core.Plugin
/// <summary>
/// Call initialize for all plugins
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "All exception information is being logged")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
public static void InitializePlugins(IPublicAPI api)
{
API = api ?? throw new ArgumentNullException(nameof(api));
@@ -160,7 +160,7 @@ namespace Wox.Core.Plugin
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "All exception information is being logged")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
public static List<Result> QueryForPlugin(PluginPair pair, Query query, bool delayedExecution = false)
{
if (pair == null)
@@ -262,7 +262,7 @@ namespace Wox.Core.Plugin
return AllPlugins.Where(p => p.Plugin is T);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "All exception information is being logged")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
public static List<ContextMenuResult> GetContextMenusForPlugin(Result result)
{
var pluginPair = _contextMenuPlugins.FirstOrDefault(o => o.Metadata.ID == result.PluginID);

View File

@@ -24,7 +24,7 @@ namespace Wox.Core.Plugin
return csharpPlugins;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "All exception information is being logged")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
public static IEnumerable<PluginPair> CSharpPlugins(List<PluginMetadata> source)
{
var plugins = new List<PluginPair>();

View File

@@ -6,13 +6,15 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Win32;
using Wox.Plugin;
using Wox.Plugin.Logger;
namespace Wox.Infrastructure.Exception
{
public class ExceptionFormatter
public static class ExceptionFormatter
{
public static string FormatException(System.Exception exception)
{
@@ -110,6 +112,7 @@ namespace Wox.Infrastructure.Exception
}
// http://msdn.microsoft.com/en-us/library/hh925568%28v=vs.110%29.aspx
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
private static List<string> GetFrameworkVersionFromRegistry()
{
try
@@ -119,25 +122,28 @@ namespace Wox.Infrastructure.Exception
{
foreach (string versionKeyName in ndpKey.GetSubKeyNames())
{
if (versionKeyName.StartsWith("v"))
// Using InvariantCulture since this is internal and involves version key
if (versionKeyName.StartsWith("v", StringComparison.InvariantCulture))
{
RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
string name = (string)versionKey.GetValue("Version", string.Empty);
string sp = versionKey.GetValue("SP", string.Empty).ToString();
string install = versionKey.GetValue("Install", string.Empty).ToString();
if (install != string.Empty)
if (!string.IsNullOrEmpty(install))
{
if (sp != string.Empty && install == "1")
if (!string.IsNullOrEmpty(sp) && install == "1")
{
result.Add(string.Format("{0} {1} SP{2}", versionKeyName, name, sp));
// Using InvariantCulture since this is internal
result.Add(string.Format(CultureInfo.InvariantCulture, "{0} {1} SP{2}", versionKeyName, name, sp));
}
else
{
result.Add(string.Format("{0} {1}", versionKeyName, name));
// Using InvariantCulture since this is internal
result.Add(string.Format(CultureInfo.InvariantCulture, "{0} {1}", versionKeyName, name));
}
}
if (name != string.Empty)
if (!string.IsNullOrEmpty(name))
{
continue;
}
@@ -146,21 +152,23 @@ namespace Wox.Infrastructure.Exception
{
RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
name = (string)subKey.GetValue("Version", string.Empty);
if (name != string.Empty)
if (!string.IsNullOrEmpty(name))
{
sp = subKey.GetValue("SP", string.Empty).ToString();
}
install = subKey.GetValue("Install", string.Empty).ToString();
if (install != string.Empty)
if (!string.IsNullOrEmpty(install))
{
if (sp != string.Empty && install == "1")
if (!string.IsNullOrEmpty(sp) && install == "1")
{
result.Add(string.Format("{0} {1} {2} SP{3}", versionKeyName, subKeyName, name, sp));
// Using InvariantCulture since this is internal
result.Add(string.Format(CultureInfo.InvariantCulture, "{0} {1} {2} SP{3}", versionKeyName, subKeyName, name, sp));
}
else if (install == "1")
{
result.Add(string.Format("{0} {1} {2}", versionKeyName, subKeyName, name));
// Using InvariantCulture since this is internal
result.Add(string.Format(CultureInfo.InvariantCulture, "{0} {1} {2}", versionKeyName, subKeyName, name));
}
}
}
@@ -191,8 +199,9 @@ namespace Wox.Infrastructure.Exception
return result;
}
catch (System.Exception)
catch (System.Exception e)
{
Log.Exception("Could not get framework version from registry", e, MethodBase.GetCurrentMethod().DeclaringType);
return new List<string>();
}
}

View File

@@ -20,11 +20,21 @@ namespace Wox.Infrastructure
public static FuzzyMatcher Create(string query)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
return new FuzzyMatcher(query, new MatchOption());
}
public static FuzzyMatcher Create(string query, MatchOption opt)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
return new FuzzyMatcher(query, opt);
}

View File

@@ -80,6 +80,7 @@ namespace Wox.Infrastructure
}
// Function to run as admin for context menu items
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
public static void RunAsAdmin(string path)
{
var info = new ProcessStartInfo

View File

@@ -82,7 +82,8 @@ namespace Wox.Infrastructure.Hotkey
return;
}
List<string> keys = hotkeyString.Replace(" ", string.Empty).Split('+').ToList();
// Using InvariantCulture since this is internal and involves key codes
List<string> keys = hotkeyString.Replace(" ", string.Empty, StringComparison.InvariantCulture).Split('+').ToList();
if (keys.Contains("Alt"))
{
Alt = true;

View File

@@ -9,21 +9,21 @@ namespace Wox.Infrastructure.Hotkey
/// <summary>
/// Key down
/// </summary>
WM_KEYDOWN = 256,
WMKEYDOWN = 256,
/// <summary>
/// Key up
/// </summary>
WM_KEYUP = 257,
WMKEYUP = 257,
/// <summary>
/// System key up
/// </summary>
WM_SYSKEYUP = 261,
WMSYSKEYUP = 261,
/// <summary>
/// System key down
/// </summary>
WM_SYSKEYDOWN = 260,
WMSYSKEYDOWN = 260,
}
}

View File

@@ -1,90 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Wox.Infrastructure.UserSettings;
using Wox.Plugin.Logger;
namespace Wox.Infrastructure.Http
{
public static class Http
{
private const string UserAgent = @"Mozilla/5.0 (Trident/7.0; rv:11.0) like Gecko";
static Http()
{
// need to be added so it would work on a win10 machine
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
}
public static HttpProxy Proxy { private get; set; }
public static IWebProxy WebProxy()
{
if (Proxy != null && Proxy.Enabled && !string.IsNullOrEmpty(Proxy.Server))
{
if (string.IsNullOrEmpty(Proxy.UserName) || string.IsNullOrEmpty(Proxy.Password))
{
var webProxy = new WebProxy(Proxy.Server, Proxy.Port);
return webProxy;
}
else
{
var webProxy = new WebProxy(Proxy.Server, Proxy.Port)
{
Credentials = new NetworkCredential(Proxy.UserName, Proxy.Password),
};
return webProxy;
}
}
else
{
return WebRequest.GetSystemWebProxy();
}
}
public static void Download([NotNull] string url, [NotNull] string filePath)
{
var client = new WebClient { Proxy = WebProxy() };
client.Headers.Add("user-agent", UserAgent);
client.DownloadFile(url, filePath);
}
public static async Task<string> Get([NotNull] string url, string encoding = "UTF-8")
{
Log.Debug($"Url <{url}>", MethodBase.GetCurrentMethod().DeclaringType);
var request = WebRequest.CreateHttp(url);
request.Method = "GET";
request.Timeout = 1000;
request.Proxy = WebProxy();
request.UserAgent = UserAgent;
var response = await request.GetResponseAsync() as HttpWebResponse;
response = response.NonNull();
var stream = response.GetResponseStream().NonNull();
using (var reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{
var content = await reader.ReadToEndAsync();
if (response.StatusCode == HttpStatusCode.OK)
{
return content;
}
else
{
throw new HttpRequestException($"Error code <{response.StatusCode}> with content <{content}> returned from <{url}>");
}
}
}
}
}

View File

@@ -0,0 +1,61 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Wox.Infrastructure.UserSettings;
using Wox.Plugin.Logger;
namespace Wox.Infrastructure.Http
{
public static class HttpClient
{
private const string UserAgent = @"Mozilla/5.0 (Trident/7.0; rv:11.0) like Gecko";
public static HttpProxy Proxy { get; set; }
public static IWebProxy WebProxy()
{
if (Proxy != null && Proxy.Enabled && !string.IsNullOrEmpty(Proxy.Server))
{
if (string.IsNullOrEmpty(Proxy.UserName) || string.IsNullOrEmpty(Proxy.Password))
{
var webProxy = new WebProxy(Proxy.Server, Proxy.Port);
return webProxy;
}
else
{
var webProxy = new WebProxy(Proxy.Server, Proxy.Port)
{
Credentials = new NetworkCredential(Proxy.UserName, Proxy.Password),
};
return webProxy;
}
}
else
{
return WebRequest.GetSystemWebProxy();
}
}
public static void Download([NotNull] Uri url, [NotNull] string filePath)
{
if (url == null)
{
throw new ArgumentNullException(nameof(url));
}
var client = new WebClient { Proxy = WebProxy() };
client.Headers.Add("user-agent", UserAgent);
client.DownloadFile(url.AbsoluteUri, filePath);
client.Dispose();
}
}
}

View File

@@ -0,0 +1,41 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
namespace Wox.Infrastructure.Image
{
internal enum SIGDN : uint
{
NORMALDISPLAY = 0,
PARENTRELATIVEPARSING = 0x80018001,
PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
DESKTOPABSOLUTEPARSING = 0x80028000,
PARENTRELATIVEEDITING = 0x80031001,
DESKTOPABSOLUTEEDITING = 0x8004c000,
FILESYSPATH = 0x80058000,
URL = 0x80068000,
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
internal interface IShellItem
{
void BindToHandler(
IntPtr pbc,
[MarshalAs(UnmanagedType.LPStruct)] Guid bhid,
[MarshalAs(UnmanagedType.LPStruct)] Guid riid,
out IntPtr ppv);
void GetParent(out IShellItem ppsi);
void GetDisplayName(SIGDN sigdnName, out IntPtr ppszName);
void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
void Compare(IShellItem psi, uint hint, out int piOrder);
}
}

View File

@@ -19,7 +19,7 @@ namespace Wox.Infrastructure.Image
private readonly ConcurrentDictionary<string, ImageSource> _data = new ConcurrentDictionary<string, ImageSource>();
public ConcurrentDictionary<string, int> Usage { get; set; } = new ConcurrentDictionary<string, int>();
public ConcurrentDictionary<string, int> Usage { get; private set; } = new ConcurrentDictionary<string, int>();
public ImageSource this[string path]
{
@@ -44,7 +44,8 @@ namespace Wox.Infrastructure.Image
// To delete the images from the data dictionary based on the resizing of the Usage Dictionary.
foreach (var key in _data.Keys)
{
if (!Usage.TryGetValue(key, out _) && !(key.Equals(Constant.ErrorIcon) || key.Equals(Constant.DefaultIcon) || key.Equals(Constant.LightThemedErrorIcon) || key.Equals(Constant.LightThemedDefaultIcon)))
// Using Ordinal since this is internal
if (!Usage.TryGetValue(key, out _) && !(key.Equals(Constant.ErrorIcon, StringComparison.Ordinal) || key.Equals(Constant.DefaultIcon, StringComparison.Ordinal) || key.Equals(Constant.LightThemedErrorIcon, StringComparison.Ordinal) || key.Equals(Constant.LightThemedDefaultIcon, StringComparison.Ordinal)))
{
_data.TryRemove(key, out _);
}

View File

@@ -4,14 +4,18 @@
using System;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Wox.Plugin.Logger;
namespace Wox.Infrastructure.Image
{
public class ImageHashGenerator : IImageHashGenerator
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5350:Do Not Use Weak Cryptographic Algorithms", Justification = "Level of protection needed for the image data does not require a security guarantee")]
public string GetHashFromImage(ImageSource imageSource)
{
if (!(imageSource is BitmapSource image))
@@ -38,8 +42,9 @@ namespace Wox.Infrastructure.Image
}
}
}
catch
catch (System.Exception e)
{
Log.Exception($"Failed to get hash from image", e, MethodBase.GetCurrentMethod().DeclaringType);
return null;
}
}

View File

@@ -5,6 +5,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
@@ -113,6 +114,7 @@ namespace Wox.Infrastructure.Image
Cache,
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
private static ImageResult LoadInternal(string path, bool loadFullImage = false)
{
ImageSource image;
@@ -154,7 +156,10 @@ namespace Wox.Infrastructure.Image
}
else if (File.Exists(path))
{
var extension = Path.GetExtension(path).ToLower();
#pragma warning disable CA1308 // Normalize strings to uppercase. Reason: extension is used with the enum ImageExtensions, which contains all lowercase values
// Using InvariantCulture since this is internal
var extension = Path.GetExtension(path).ToLower(CultureInfo.InvariantCulture);
#pragma warning restore CA1308 // Normalize strings to uppercase
if (ImageExtensions.Contains(extension))
{
type = ImageType.ImageFile;
@@ -200,7 +205,7 @@ namespace Wox.Infrastructure.Image
return new ImageResult(image, type);
}
private static readonly bool _enableImageHash = true;
private const bool _enableImageHash = true;
public static ImageSource Load(string path, bool loadFullImage = false)
{

View File

@@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
namespace Wox.Infrastructure.Image
{
internal static class NativeMethods
{
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int SHCreateItemFromParsingName(
[MarshalAs(UnmanagedType.LPWStr)] string path,
IntPtr pbc,
ref Guid riid,
[MarshalAs(UnmanagedType.Interface)] out IShellItem shellItem);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);
}
}

View File

@@ -22,54 +22,11 @@ namespace Wox.Infrastructure.Image
InCacheOnly = 0x10,
}
public class WindowsThumbnailProvider
public static class WindowsThumbnailProvider
{
// Based on https://stackoverflow.com/questions/21751747/extract-thumbnail-for-any-file-in-windows
private const string IShellItem2Guid = "7E9FB0D3-919F-4307-AB2E-9B1860310C93";
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int SHCreateItemFromParsingName(
[MarshalAs(UnmanagedType.LPWStr)] string path,
IntPtr pbc,
ref Guid riid,
[MarshalAs(UnmanagedType.Interface)] out IShellItem shellItem);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
internal interface IShellItem
{
void BindToHandler(
IntPtr pbc,
[MarshalAs(UnmanagedType.LPStruct)] Guid bhid,
[MarshalAs(UnmanagedType.LPStruct)] Guid riid,
out IntPtr ppv);
void GetParent(out IShellItem ppsi);
void GetDisplayName(SIGDN sigdnName, out IntPtr ppszName);
void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
void Compare(IShellItem psi, uint hint, out int piOrder);
}
internal enum SIGDN : uint
{
NORMALDISPLAY = 0,
PARENTRELATIVEPARSING = 0x80018001,
PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
DESKTOPABSOLUTEPARSING = 0x80028000,
PARENTRELATIVEEDITING = 0x80031001,
DESKTOPABSOLUTEEDITING = 0x8004c000,
FILESYSPATH = 0x80058000,
URL = 0x80068000,
}
internal enum HResult
{
Ok = 0x0000,
@@ -128,14 +85,14 @@ namespace Wox.Infrastructure.Image
finally
{
// delete HBitmap to avoid memory leaks
DeleteObject(hBitmap);
NativeMethods.DeleteObject(hBitmap);
}
}
private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options)
{
Guid shellItem2Guid = new Guid(IShellItem2Guid);
int retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out IShellItem nativeShellItem);
int retCode = NativeMethods.SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out IShellItem nativeShellItem);
if (retCode != 0)
{

View File

@@ -53,9 +53,9 @@ namespace Wox.Infrastructure
}
/// <summary>
/// Gets or sets matched data to highlight.
/// Gets matched data to highlight.
/// </summary>
public List<int> MatchData { get; set; }
public List<int> MatchData { get; private set; }
public SearchPrecisionScore SearchPrecision { get; set; }

View File

@@ -19,6 +19,11 @@ namespace Wox.Infrastructure
/// </summary>
public static long Debug(string message, Action action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
action();
@@ -31,6 +36,11 @@ namespace Wox.Infrastructure
public static long Normal(string message, Action action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
action();
@@ -43,6 +53,11 @@ namespace Wox.Infrastructure
public static void StartCount(string name, Action action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
action();

View File

@@ -20,7 +20,7 @@ namespace Wox.Infrastructure.Storage
public class BinaryStorage<T> : IStorage<T>
{
// This storage helper returns whether or not to delete the binary storage items
private static readonly int _binaryStorage = 0;
private const int _binaryStorage = 0;
private StoragePowerToysVersionInfo _storageHelper;
public BinaryStorage(string filename)
@@ -75,6 +75,7 @@ namespace Wox.Infrastructure.Storage
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
private T Deserialize(FileStream stream, T defaultData)
{
// http://stackoverflow.com/questions/2120055/binaryformatter-deserialize-gives-serializationexception

View File

@@ -8,7 +8,7 @@ using System.IO;
namespace Wox.Infrastructure.Storage
{
// File System Watcher Wrapper class which implements the IFileSystemWatcherWrapper interface
public class FileSystemWatcherWrapper : FileSystemWatcher, IFileSystemWatcherWrapper
public sealed class FileSystemWatcherWrapper : FileSystemWatcher, IFileSystemWatcherWrapper
{
public FileSystemWatcherWrapper()
{

View File

@@ -19,6 +19,7 @@ namespace Wox.Infrastructure.Storage
event RenamedEventHandler Renamed;
// Properties of File System watcher
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Abstract properties can not have private set")]
Collection<string> Filters { get; set; }
bool EnableRaisingEvents { get; set; }

View File

@@ -14,7 +14,7 @@ namespace Wox.Infrastructure.Storage
bool Contains(T item);
void Set(IList<T> list);
void SetList(IList<T> list);
bool Any();
}

View File

@@ -27,7 +27,7 @@ namespace Wox.Infrastructure.Storage
public string DirectoryPath { get; set; }
// This storage helper returns whether or not to delete the json storage items
private static readonly int _jsonStorage = 1;
private const int _jsonStorage = 1;
private StoragePowerToysVersionInfo _storageHelper;
internal JsonStorage()
@@ -106,7 +106,8 @@ namespace Wox.Infrastructure.Storage
private void BackupOriginFile()
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fffffff", CultureInfo.CurrentUICulture);
// Using CurrentCulture since this is user facing
var timestamp = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fffffff", CultureInfo.CurrentCulture);
var directory = Path.GetDirectoryName(FilePath).NonNull();
var originName = Path.GetFileNameWithoutExtension(FilePath);
var backupName = $"{originName}-{timestamp}{FileSuffix}";

View File

@@ -29,7 +29,7 @@ namespace Wox.Infrastructure.Storage
{
}
public void Set(IList<T> items)
public void SetList(IList<T> items)
{
// enforce that internal representation
try

View File

@@ -10,7 +10,7 @@ namespace Wox.Infrastructure.Storage
public class StoragePowerToysVersionInfo
{
// This detail is accessed by the storage items and is used to decide if the cache must be deleted or not
public bool ClearCache { get; set; } = false;
public bool ClearCache { get; set; }
private readonly string currentPowerToysVersion = string.Empty;
@@ -81,7 +81,7 @@ namespace Wox.Infrastructure.Storage
}
}
private string GetFilePath(string associatedFilePath, int type)
private static string GetFilePath(string associatedFilePath, int type)
{
string suffix = string.Empty;
string cacheSuffix = ".cache";
@@ -102,6 +102,11 @@ namespace Wox.Infrastructure.Storage
public StoragePowerToysVersionInfo(string associatedFilePath, int type)
{
if (associatedFilePath == null)
{
throw new ArgumentNullException(nameof(associatedFilePath));
}
FilePath = GetFilePath(associatedFilePath, type);
// Get the previous version of PowerToys and cache Storage details from the CacheDetails.json storage file

View File

@@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
@@ -59,9 +60,16 @@ namespace Wox.Infrastructure
return new MatchResult(false, UserSettingSearchPrecision);
}
if (opt == null)
{
throw new ArgumentNullException(nameof(opt));
}
query = query.Trim();
var fullStringToCompareWithoutCase = opt.IgnoreCase ? stringToCompare.ToLower() : stringToCompare;
var queryWithoutCase = opt.IgnoreCase ? query.ToLower() : query;
// Using InvariantCulture since this is internal
var fullStringToCompareWithoutCase = opt.IgnoreCase ? stringToCompare.ToUpper(CultureInfo.InvariantCulture) : stringToCompare;
var queryWithoutCase = opt.IgnoreCase ? query.ToUpper(CultureInfo.InvariantCulture) : query;
var querySubstrings = queryWithoutCase.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int currentQuerySubstringIndex = 0;
@@ -160,7 +168,7 @@ namespace Wox.Infrastructure
}
// To get the index of the closest space which preceeds the first matching index
private int CalculateClosestSpaceIndex(List<int> spaceIndices, int firstMatchIndex)
private static int CalculateClosestSpaceIndex(List<int> spaceIndices, int firstMatchIndex)
{
if (spaceIndices.Count == 0)
{

View File

@@ -6,7 +6,7 @@ namespace Wox.Infrastructure.UserSettings
{
public class HttpProxy
{
public bool Enabled { get; set; } = false;
public bool Enabled { get; set; }
public string Server { get; set; }

View File

@@ -2,6 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Wox.Plugin;
@@ -9,30 +10,34 @@ namespace Wox.Infrastructure.UserSettings
{
public class PluginSettings : BaseModel
{
public Dictionary<string, Plugin> Plugins { get; set; } = new Dictionary<string, Plugin>();
public Dictionary<string, RunPlugin> Plugins { get; private set; } = new Dictionary<string, RunPlugin>();
public void UpdatePluginSettings(List<PluginMetadata> metadatas)
{
if (metadatas == null)
{
throw new ArgumentNullException(nameof(metadatas));
}
foreach (var metadata in metadatas)
{
if (Plugins.ContainsKey(metadata.ID))
{
var settings = Plugins[metadata.ID];
if (settings.ActionKeywords?.Count > 0)
if (settings.GetActionKeywords()?.Count > 0)
{
metadata.SetActionKeywords(settings.ActionKeywords);
metadata.ActionKeyword = settings.ActionKeywords[0];
metadata.SetActionKeywords(settings.GetActionKeywords());
metadata.ActionKeyword = settings.GetActionKeywords()[0];
}
metadata.Disabled = settings.Disabled;
}
else
{
Plugins[metadata.ID] = new Plugin
Plugins[metadata.ID] = new RunPlugin(metadata.GetActionKeywords())
{
ID = metadata.ID,
Name = metadata.Name,
ActionKeywords = metadata.GetActionKeywords(),
Disabled = metadata.Disabled,
};
}

View File

@@ -12,7 +12,7 @@ using Wox.Plugin;
namespace Wox.Infrastructure.UserSettings
{
public class Settings : BaseModel
public class PowerToysRunSettings : BaseModel
{
private string _hotkey = "Alt + Space";
private string _previousHotkey = string.Empty;
@@ -95,7 +95,7 @@ namespace Wox.Infrastructure.UserSettings
}
}
public bool AutoUpdates { get; set; } = false;
public bool AutoUpdates { get; set; }
public double WindowLeft { get; set; }
@@ -126,13 +126,7 @@ namespace Wox.Infrastructure.UserSettings
[JsonProperty(Order = 1)]
public PluginSettings PluginSettings { get; set; } = new PluginSettings();
public ObservableCollection<CustomPluginHotkey> CustomPluginHotkeys { get; set; } = new ObservableCollection<CustomPluginHotkey>();
[Obsolete]
public double Opacity { get; set; } = 1;
[Obsolete]
public OpacityMode OpacityMode { get; set; } = OpacityMode.Normal;
public ObservableCollection<CustomPluginHotkey> CustomPluginHotkeys { get; } = new ObservableCollection<CustomPluginHotkey>();
public bool DontPromptUpdateMsg { get; set; }
@@ -162,7 +156,7 @@ namespace Wox.Infrastructure.UserSettings
public bool HideWhenDeactivated { get; set; } = true;
public bool ClearInputOnLaunch { get; set; } = false;
public bool ClearInputOnLaunch { get; set; }
public bool RememberLastLaunchLocation { get; set; }
@@ -182,12 +176,4 @@ namespace Wox.Infrastructure.UserSettings
Empty,
Preserved,
}
[Obsolete]
public enum OpacityMode
{
Normal = 0,
LayeredWindow = 1,
DWM = 2,
}
}

View File

@@ -6,13 +6,28 @@ using System.Collections.Generic;
namespace Wox.Infrastructure.UserSettings
{
public class Plugin
public class RunPlugin
{
public string ID { get; set; }
public string Name { get; set; }
public List<string> ActionKeywords { get; set; } // a reference of the action keywords from plugin manager
private List<string> _actionKeywords;
public RunPlugin(List<string> actionKeywords = null)
{
_actionKeywords = actionKeywords;
}
public List<string> GetActionKeywords()
{
return _actionKeywords;
}
public void SetActionKeywords(List<string> value)
{
_actionKeywords = value;
}
/// <summary>
/// Gets or sets a value indicating whether used only to save the state of the plugin in settings

View File

@@ -56,6 +56,10 @@
<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="2020.1.0" />
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="NLog.Schema" Version="4.7.4" />
<PackageReference Include="System.Drawing.Common" Version="4.7.0" />
<PackageReference Include="System.Runtime" Version="4.3.1" />

View File

@@ -13,7 +13,7 @@ namespace Wox.Plugin.SharedCommands
{
public static class FilesFolders
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Exception has been logged")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
public static void Copy(this string sourcePath, string targetPath)
{
// Get the subdirectories for the specified directory.
@@ -67,7 +67,7 @@ namespace Wox.Plugin.SharedCommands
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Exception has been logged")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
public static bool VerifyBothFolderFilesEqual(this string fromPath, string toPath)
{
try
@@ -103,7 +103,7 @@ namespace Wox.Plugin.SharedCommands
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Exception has been logged")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
public static void RemoveFolder(this string path)
{
try