more fixes for getting styleCop up, this will need one more push to get another 15 that will require renaming of vars (#5875)

This commit is contained in:
Clint Rutkas
2020-08-11 13:40:26 -07:00
committed by GitHub
parent 90502f7553
commit 2c49df4be3
24 changed files with 255 additions and 181 deletions

View File

@@ -18,8 +18,8 @@ namespace Wox.Infrastructure
{ {
public class Alphabet : IAlphabet public class Alphabet : IAlphabet
{ {
private readonly HanyuPinyinOutputFormat Format = new HanyuPinyinOutputFormat(); private readonly HanyuPinyinOutputFormat _pinyinFormat = new HanyuPinyinOutputFormat();
private ConcurrentDictionary<string, string[][]> PinyinCache; private ConcurrentDictionary<string, string[][]> _pinyinCache;
private BinaryStorage<Dictionary<string, string[][]>> _pinyinStorage; private BinaryStorage<Dictionary<string, string[][]>> _pinyinStorage;
private Settings _settings; private Settings _settings;
@@ -31,7 +31,7 @@ namespace Wox.Infrastructure
private void InitializePinyinHelpers() private void InitializePinyinHelpers()
{ {
Format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); _pinyinFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
Stopwatch.Normal("|Wox.Infrastructure.Alphabet.Initialize|Preload pinyin cache", () => Stopwatch.Normal("|Wox.Infrastructure.Alphabet.Initialize|Preload pinyin cache", () =>
{ {
@@ -39,9 +39,9 @@ namespace Wox.Infrastructure
SetPinyinCacheAsDictionary(_pinyinStorage.TryLoad(new Dictionary<string, string[][]>())); SetPinyinCacheAsDictionary(_pinyinStorage.TryLoad(new Dictionary<string, string[][]>()));
// force pinyin library static constructor initialize // force pinyin library static constructor initialize
PinyinHelper.toHanyuPinyinStringArray('T', Format); PinyinHelper.toHanyuPinyinStringArray('T', _pinyinFormat);
}); });
Log.Info($"|Wox.Infrastructure.Alphabet.Initialize|Number of preload pinyin combination<{PinyinCache.Count}>"); Log.Info($"|Wox.Infrastructure.Alphabet.Initialize|Number of preload pinyin combination<{_pinyinCache.Count}>");
} }
public string Translate(string str) public string Translate(string str)
@@ -52,17 +52,23 @@ namespace Wox.Infrastructure
public string ConvertChineseCharactersToPinyin(string source) public string ConvertChineseCharactersToPinyin(string source)
{ {
if (!_settings.ShouldUsePinyin) if (!_settings.ShouldUsePinyin)
{
return source; return source;
}
if (string.IsNullOrEmpty(source)) if (string.IsNullOrEmpty(source))
{
return source; return source;
}
if (!ContainsChinese(source)) if (!ContainsChinese(source))
{
return source; return source;
}
var combination = PinyinCombination(source); var combination = PinyinCombination(source);
var pinyinArray = combination.Select(x => string.Join("", x)); var pinyinArray = combination.Select(x => string.Join(string.Empty, x));
var acronymArray = combination.Select(Acronym).Distinct(); var acronymArray = combination.Select(Acronym).Distinct();
var joinedSingleStringCombination = new StringBuilder(); var joinedSingleStringCombination = new StringBuilder();
@@ -85,11 +91,11 @@ namespace Wox.Infrastructure
private static string[] EmptyStringArray = new string[0]; private static string[] EmptyStringArray = new string[0];
private static string[][] Empty2DStringArray = new string[0][]; private static string[][] Empty2DStringArray = new string[0][];
[Obsolete("Not accurate, eg 音乐 will not return yinyue but returns yinle ")]
/// <summary> /// <summary>
/// replace chinese character with pinyin, non chinese character won't be modified /// replace chinese character with pinyin, non chinese character won't be modified
/// <param name="word"> should be word or sentence, instead of single character. e.g. 微软 </param> /// <param name="word"> should be word or sentence, instead of single character. e.g. 微软 </param>
/// </summary> /// </summary>
[Obsolete("Not accurate, eg 音乐 will not return yinyue but returns yinle ")]
public string[] Pinyin(string word) public string[] Pinyin(string word)
{ {
if (!_settings.ShouldUsePinyin) if (!_settings.ShouldUsePinyin)
@@ -119,12 +125,12 @@ namespace Wox.Infrastructure
return Empty2DStringArray; return Empty2DStringArray;
} }
if (!PinyinCache.ContainsKey(characters)) if (!_pinyinCache.ContainsKey(characters))
{ {
var allPinyins = new List<string[]>(); var allPinyins = new List<string[]>();
foreach (var c in characters) foreach (var c in characters)
{ {
var pinyins = PinyinHelper.toHanyuPinyinStringArray(c, Format); var pinyins = PinyinHelper.toHanyuPinyinStringArray(c, _pinyinFormat);
if (pinyins != null) if (pinyins != null)
{ {
var r = pinyins.Distinct().ToArray(); var r = pinyins.Distinct().ToArray();
@@ -138,18 +144,18 @@ namespace Wox.Infrastructure
} }
var combination = allPinyins.Aggregate(Combination).Select(c => c.Split(';')).ToArray(); var combination = allPinyins.Aggregate(Combination).Select(c => c.Split(';')).ToArray();
PinyinCache[characters] = combination; _pinyinCache[characters] = combination;
return combination; return combination;
} }
else else
{ {
return PinyinCache[characters]; return _pinyinCache[characters];
} }
} }
public string Acronym(string[] pinyin) public string Acronym(string[] pinyin)
{ {
var acronym = string.Join("", pinyin.Select(p => p[0])); var acronym = string.Join(string.Empty, pinyin.Select(p => p[0]));
return acronym; return acronym;
} }
@@ -188,12 +194,12 @@ namespace Wox.Infrastructure
private Dictionary<string, string[][]> GetPinyinCacheAsDictionary() private Dictionary<string, string[][]> GetPinyinCacheAsDictionary()
{ {
return new Dictionary<string, string[][]>(PinyinCache); return new Dictionary<string, string[][]>(_pinyinCache);
} }
private void SetPinyinCacheAsDictionary(Dictionary<string, string[][]> usage) private void SetPinyinCacheAsDictionary(Dictionary<string, string[][]> usage)
{ {
PinyinCache = new ConcurrentDictionary<string, string[][]>(usage); _pinyinCache = new ConcurrentDictionary<string, string[][]>(usage);
} }
} }
} }

View File

@@ -121,16 +121,22 @@ namespace Wox.Infrastructure.Exception
if (versionKeyName.StartsWith("v")) if (versionKeyName.StartsWith("v"))
{ {
RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName); RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
string name = (string)versionKey.GetValue("Version", ""); string name = (string)versionKey.GetValue("Version", string.Empty);
string sp = versionKey.GetValue("SP", "").ToString(); string sp = versionKey.GetValue("SP", string.Empty).ToString();
string install = versionKey.GetValue("Install", "").ToString(); string install = versionKey.GetValue("Install", string.Empty).ToString();
if (install != "") if (install != string.Empty)
if (sp != "" && install == "1") {
if (sp != string.Empty && install == "1")
{
result.Add(string.Format("{0} {1} SP{2}", versionKeyName, name, sp)); result.Add(string.Format("{0} {1} SP{2}", versionKeyName, name, sp));
}
else else
{
result.Add(string.Format("{0} {1}", versionKeyName, name)); result.Add(string.Format("{0} {1}", versionKeyName, name));
}
}
if (name != "") if (name != string.Empty)
{ {
continue; continue;
} }
@@ -138,16 +144,23 @@ namespace Wox.Infrastructure.Exception
foreach (string subKeyName in versionKey.GetSubKeyNames()) foreach (string subKeyName in versionKey.GetSubKeyNames())
{ {
RegistryKey subKey = versionKey.OpenSubKey(subKeyName); RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
name = (string)subKey.GetValue("Version", ""); name = (string)subKey.GetValue("Version", string.Empty);
if (name != "") if (name != string.Empty)
sp = subKey.GetValue("SP", "").ToString();
install = subKey.GetValue("Install", "").ToString();
if (install != "")
{ {
if (sp != "" && install == "1") sp = subKey.GetValue("SP", string.Empty).ToString();
}
install = subKey.GetValue("Install", string.Empty).ToString();
if (install != string.Empty)
{
if (sp != string.Empty && install == "1")
{
result.Add(string.Format("{0} {1} {2} SP{3}", versionKeyName, subKeyName, name, sp)); result.Add(string.Format("{0} {1} {2} SP{3}", versionKeyName, subKeyName, name, sp));
}
else if (install == "1") else if (install == "1")
{
result.Add(string.Format("{0} {1} {2}", versionKeyName, subKeyName, name)); result.Add(string.Format("{0} {1} {2}", versionKeyName, subKeyName, name));
}
} }
} }
} }
@@ -159,13 +172,19 @@ namespace Wox.Infrastructure.Exception
int releaseKey = (int)ndpKey.GetValue("Release"); int releaseKey = (int)ndpKey.GetValue("Release");
{ {
if (releaseKey == 378389) if (releaseKey == 378389)
{
result.Add("v4.5"); result.Add("v4.5");
}
if (releaseKey == 378675) if (releaseKey == 378675)
{
result.Add("v4.5.1 installed with Windows 8.1"); result.Add("v4.5.1 installed with Windows 8.1");
}
if (releaseKey == 378758) if (releaseKey == 378758)
{
result.Add("4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2"); result.Add("4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2");
}
} }
} }

View File

@@ -9,7 +9,9 @@ namespace Wox.Infrastructure.FileSystemHelper
{ {
public class FileVersionInfoWrapper : IFileVersionInfoWrapper public class FileVersionInfoWrapper : IFileVersionInfoWrapper
{ {
public FileVersionInfoWrapper() { } public FileVersionInfoWrapper()
{
}
public FileVersionInfo GetVersionInfo(string path) public FileVersionInfo GetVersionInfo(string path)
{ {

View File

@@ -2,7 +2,6 @@
// The Microsoft Corporation licenses this file to you under the MIT license. // The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information. // See the LICENSE file in the project root for more information.
using System;
using System.IO; using System.IO;
using Wox.Infrastructure.Logger; using Wox.Infrastructure.Logger;
@@ -10,7 +9,9 @@ namespace Wox.Infrastructure.FileSystemHelper
{ {
public class FileWrapper : IFileWrapper public class FileWrapper : IFileWrapper
{ {
public FileWrapper() { } public FileWrapper()
{
}
public string[] ReadAllLines(string path) public string[] ReadAllLines(string path)
{ {
@@ -21,7 +22,7 @@ namespace Wox.Infrastructure.FileSystemHelper
catch (IOException ex) catch (IOException ex)
{ {
Log.Info($"File {path} is being accessed by another process| {ex.Message}"); Log.Info($"File {path} is being accessed by another process| {ex.Message}");
return new string[] { String.Empty }; return new string[] { string.Empty };
} }
} }
} }

View File

@@ -73,11 +73,8 @@ namespace Wox.Infrastructure
public static string Formatted<T>(this T t) public static string Formatted<T>(this T t)
{ {
var formatted = JsonConvert.SerializeObject( var formatted = JsonConvert.SerializeObject(t, Formatting.Indented, new StringEnumConverter());
t,
Formatting.Indented,
new StringEnumConverter()
);
return formatted; return formatted;
} }
@@ -89,7 +86,7 @@ namespace Wox.Infrastructure
FileName = path, FileName = path,
WorkingDirectory = Path.GetDirectoryName(path), WorkingDirectory = Path.GetDirectoryName(path),
Verb = "runas", Verb = "runas",
UseShellExecute = true UseShellExecute = true,
}; };
try try
@@ -107,7 +104,7 @@ namespace Wox.Infrastructure
var processStartInfo = new ProcessStartInfo var processStartInfo = new ProcessStartInfo
{ {
WorkingDirectory = path, WorkingDirectory = path,
FileName = "cmd.exe" FileName = "cmd.exe",
}; };
return Process.Start(processStartInfo); return Process.Start(processStartInfo);

View File

@@ -24,7 +24,7 @@ namespace Wox.Infrastructure.Hotkey
Dictionary<Key, string> specialSymbolDictionary = new Dictionary<Key, string> Dictionary<Key, string> specialSymbolDictionary = new Dictionary<Key, string>
{ {
{ Key.Space, "Space" }, { Key.Space, "Space" },
{ Key.Oem3, "~" } { Key.Oem3, "~" },
}; };
public ModifierKeys ModifierKeys public ModifierKeys ModifierKeys
@@ -81,7 +81,7 @@ namespace Wox.Infrastructure.Hotkey
return; return;
} }
List<string> keys = hotkeyString.Replace(" ", "").Split('+').ToList(); List<string> keys = hotkeyString.Replace(" ", string.Empty).Split('+').ToList();
if (keys.Contains("Alt")) if (keys.Contains("Alt"))
{ {
Alt = true; Alt = true;

View File

@@ -24,6 +24,6 @@ namespace Wox.Infrastructure.Hotkey
/// <summary> /// <summary>
/// System key down /// System key down
/// </summary> /// </summary>
WM_SYSKEYDOWN = 260 WM_SYSKEYDOWN = 260,
} }
} }

View File

@@ -41,7 +41,7 @@ namespace Wox.Infrastructure.Http
{ {
var webProxy = new WebProxy(Proxy.Server, Proxy.Port) var webProxy = new WebProxy(Proxy.Server, Proxy.Port)
{ {
Credentials = new NetworkCredential(Proxy.UserName, Proxy.Password) Credentials = new NetworkCredential(Proxy.UserName, Proxy.Password),
}; };
return webProxy; return webProxy;
} }

View File

@@ -25,7 +25,6 @@ namespace Wox.Infrastructure.Image
{ {
// PngBitmapEncoder enc2 = new PngBitmapEncoder(); // PngBitmapEncoder enc2 = new PngBitmapEncoder();
// enc2.Frames.Add(BitmapFrame.Create(tt)); // enc2.Frames.Add(BitmapFrame.Create(tt));
var enc = new JpegBitmapEncoder(); var enc = new JpegBitmapEncoder();
var bitmapFrame = BitmapFrame.Create(image); var bitmapFrame = BitmapFrame.Create(image);
bitmapFrame.Freeze(); bitmapFrame.Freeze();

View File

@@ -33,7 +33,7 @@ namespace Wox.Infrastructure.Image
".gif", ".gif",
".bmp", ".bmp",
".tiff", ".tiff",
".ico" ".ico",
}; };
public static void Initialize(Theme theme) public static void Initialize(Theme theme)
@@ -104,7 +104,7 @@ namespace Wox.Infrastructure.Image
Data, Data,
ImageFile, ImageFile,
Error, Error,
Cache Cache,
} }
private static ImageResult LoadInternal(string path, bool loadFullImage = false) private static ImageResult LoadInternal(string path, bool loadFullImage = false)
@@ -144,8 +144,7 @@ namespace Wox.Infrastructure.Image
* - Solution: just load the icon * - Solution: just load the icon
*/ */
type = ImageType.Folder; type = ImageType.Folder;
image = WindowsThumbnailProvider.GetThumbnail(path, Constant.ThumbnailSize, image = WindowsThumbnailProvider.GetThumbnail(path, Constant.ThumbnailSize, Constant.ThumbnailSize, ThumbnailOptions.IconOnly);
Constant.ThumbnailSize, ThumbnailOptions.IconOnly);
} }
else if (File.Exists(path)) else if (File.Exists(path))
{ {
@@ -164,15 +163,13 @@ namespace Wox.Infrastructure.Image
* be the case in many situations while testing. * be the case in many situations while testing.
* - Solution: explicitly pass the ThumbnailOnly flag * - Solution: explicitly pass the ThumbnailOnly flag
*/ */
image = WindowsThumbnailProvider.GetThumbnail(path, Constant.ThumbnailSize, image = WindowsThumbnailProvider.GetThumbnail(path, Constant.ThumbnailSize, Constant.ThumbnailSize, ThumbnailOptions.ThumbnailOnly);
Constant.ThumbnailSize, ThumbnailOptions.ThumbnailOnly);
} }
} }
else else
{ {
type = ImageType.File; type = ImageType.File;
image = WindowsThumbnailProvider.GetThumbnail(path, Constant.ThumbnailSize, image = WindowsThumbnailProvider.GetThumbnail(path, Constant.ThumbnailSize, Constant.ThumbnailSize, ThumbnailOptions.None);
Constant.ThumbnailSize, ThumbnailOptions.None);
} }
} }
else else

View File

@@ -3,11 +3,11 @@
// See the LICENSE file in the project root for more information. // See the LICENSE file in the project root for more information.
using System; using System;
using System.Runtime.InteropServices;
using System.IO; using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop; using System.Windows.Interop;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using System.Windows;
namespace Wox.Infrastructure.Image namespace Wox.Infrastructure.Image
{ {
@@ -66,7 +66,7 @@ namespace Wox.Infrastructure.Image
PARENTRELATIVEEDITING = 0x80031001, PARENTRELATIVEEDITING = 0x80031001,
DESKTOPABSOLUTEEDITING = 0x8004c000, DESKTOPABSOLUTEEDITING = 0x8004c000,
FILESYSPATH = 0x80058000, FILESYSPATH = 0x80058000,
URL = 0x80068000 URL = 0x80068000,
} }
internal enum HResult internal enum HResult
@@ -84,7 +84,7 @@ namespace Wox.Infrastructure.Image
Win32ErrorCanceled = 1223, Win32ErrorCanceled = 1223,
Canceled = unchecked((int)0x800704C7), Canceled = unchecked((int)0x800704C7),
ResourceInUse = unchecked((int)0x800700AA), ResourceInUse = unchecked((int)0x800700AA),
AccessDenied = unchecked((int)0x80030005) AccessDenied = unchecked((int)0x80030005),
} }
[ComImportAttribute()] [ComImportAttribute()]
@@ -105,9 +105,15 @@ namespace Wox.Infrastructure.Image
private int width; private int width;
private int height; private int height;
public int Width { set { width = value; } } public int Width
{
set { width = value; }
}
public int Height { set { height = value; } } public int Height
{
set { height = value; }
}
} }
public static BitmapSource GetThumbnail(string fileName, int width, int height, ThumbnailOptions options) public static BitmapSource GetThumbnail(string fileName, int width, int height, ThumbnailOptions options)
@@ -132,12 +138,14 @@ namespace Wox.Infrastructure.Image
int retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem); int retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem);
if (retCode != 0) if (retCode != 0)
{
throw Marshal.GetExceptionForHR(retCode); throw Marshal.GetExceptionForHR(retCode);
}
NativeSize nativeSize = new NativeSize NativeSize nativeSize = new NativeSize
{ {
Width = width, Width = width,
Height = height Height = height,
}; };
IntPtr hBitmap; IntPtr hBitmap;
@@ -151,7 +159,10 @@ namespace Wox.Infrastructure.Image
Marshal.ReleaseComObject(nativeShellItem); Marshal.ReleaseComObject(nativeShellItem);
if (hr == HResult.Ok) return hBitmap; if (hr == HResult.Ok)
{
return hBitmap;
}
throw new COMException($"Error while extracting thumbnail for {fileName}", Marshal.GetExceptionForHR((int)hr)); throw new COMException($"Error while extracting thumbnail for {fileName}", Marshal.GetExceptionForHR((int)hr));
} }

View File

@@ -100,7 +100,8 @@ namespace Wox.Infrastructure.Logger
logger.Error($"Exception target site:\n <{e.TargetSite}>"); logger.Error($"Exception target site:\n <{e.TargetSite}>");
logger.Error($"Exception HResult:\n <{e.HResult}>"); logger.Error($"Exception HResult:\n <{e.HResult}>");
e = e.InnerException; e = e.InnerException;
} while (e != null); }
while (e != null);
logger.Error("-------------------------- End exception --------------------------"); logger.Error("-------------------------- End exception --------------------------");
} }

View File

@@ -0,0 +1,28 @@
// 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.CompilerServices;
[assembly: InternalsVisibleToAttribute("Microsoft.Plugin.Program.UnitTests")]
namespace Wox.Infrastructure
{
public class MatchOption
{
/// <summary>
/// Gets or sets prefix of match char, use for highlight
/// </summary>
[Obsolete("this is never used")]
public string Prefix { get; set; } = string.Empty;
/// <summary>
/// Gets or sets suffix of match char, use for highlight
/// </summary>
[Obsolete("this is never used")]
public string Suffix { get; set; } = string.Empty;
public bool IgnoreCase { get; set; } = true;
}
}

View File

@@ -0,0 +1,77 @@
// 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.Collections.Generic;
using System.Runtime.CompilerServices;
using static Wox.Infrastructure.StringMatcher;
[assembly: InternalsVisibleToAttribute("Microsoft.Plugin.Program.UnitTests")]
namespace Wox.Infrastructure
{
public class MatchResult
{
public MatchResult(bool success, SearchPrecisionScore searchPrecision)
{
Success = success;
SearchPrecision = searchPrecision;
}
public MatchResult(bool success, SearchPrecisionScore searchPrecision, List<int> matchData, int rawScore)
{
Success = success;
SearchPrecision = searchPrecision;
MatchData = matchData;
RawScore = rawScore;
}
public bool Success { get; set; }
/// <summary>
/// Gets the final score of the match result with search precision filters applied.
/// </summary>
public int Score { get; private set; }
/// <summary>
/// The raw calculated search score without any search precision filtering applied.
/// </summary>
private int _rawScore;
public int RawScore
{
get
{
return _rawScore;
}
set
{
_rawScore = value;
Score = ScoreAfterSearchPrecisionFilter(_rawScore);
}
}
/// <summary>
/// Gets or sets matched data to highlight.
/// </summary>
public List<int> MatchData { get; set; }
public SearchPrecisionScore SearchPrecision { get; set; }
public bool IsSearchPrecisionScoreMet()
{
return IsSearchPrecisionScoreMet(_rawScore);
}
private bool IsSearchPrecisionScoreMet(int rawScore)
{
return rawScore >= (int)SearchPrecision;
}
private int ScoreAfterSearchPrecisionFilter(int rawScore)
{
return IsSearchPrecisionScoreMet(rawScore) ? rawScore : 0;
}
}
}

View File

@@ -77,7 +77,7 @@ namespace Wox.Infrastructure.Storage
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
BinaryFormatter binaryFormatter = new BinaryFormatter BinaryFormatter binaryFormatter = new BinaryFormatter
{ {
AssemblyFormat = FormatterAssemblyStyle.Simple AssemblyFormat = FormatterAssemblyStyle.Simple,
}; };
try try
@@ -119,7 +119,7 @@ namespace Wox.Infrastructure.Storage
{ {
BinaryFormatter binaryFormatter = new BinaryFormatter BinaryFormatter binaryFormatter = new BinaryFormatter
{ {
AssemblyFormat = FormatterAssemblyStyle.Simple AssemblyFormat = FormatterAssemblyStyle.Simple,
}; };
try try

View File

@@ -10,7 +10,9 @@ namespace Wox.Infrastructure.Storage
// File System Watcher Wrapper class which implements the IFileSystemWatcherWrapper interface // File System Watcher Wrapper class which implements the IFileSystemWatcherWrapper interface
public class FileSystemWatcherWrapper : FileSystemWatcher, IFileSystemWatcherWrapper public class FileSystemWatcherWrapper : FileSystemWatcher, IFileSystemWatcherWrapper
{ {
public FileSystemWatcherWrapper() { } public FileSystemWatcherWrapper()
{
}
Collection<string> IFileSystemWatcherWrapper.Filters Collection<string> IFileSystemWatcherWrapper.Filters
{ {

View File

@@ -37,7 +37,7 @@ namespace Wox.Infrastructure.Storage
_serializerSettings = new JsonSerializerSettings _serializerSettings = new JsonSerializerSettings
{ {
ObjectCreationHandling = ObjectCreationHandling.Replace, ObjectCreationHandling = ObjectCreationHandling.Replace,
NullValueHandling = NullValueHandling.Ignore NullValueHandling = NullValueHandling.Ignore,
}; };
} }

View File

@@ -18,7 +18,10 @@ namespace Wox.Infrastructure.Storage
/// <typeparam name="T">typeof</typeparam> /// <typeparam name="T">typeof</typeparam>
public class ListRepository<T> : IRepository<T>, IEnumerable<T> public class ListRepository<T> : IRepository<T>, IEnumerable<T>
{ {
public IList<T> Items { get { return _items.Values.ToList(); } } public IList<T> Items
{
get { return _items.Values.ToList(); }
}
private ConcurrentDictionary<int, T> _items = new ConcurrentDictionary<int, T>(); private ConcurrentDictionary<int, T> _items = new ConcurrentDictionary<int, T>();

View File

@@ -6,7 +6,8 @@ using System.IO;
namespace Wox.Infrastructure.Storage namespace Wox.Infrastructure.Storage
{ {
public class PluginJsonStorage<T> : JsonStorage<T> where T : new() public class PluginJsonStorage<T> : JsonStorage<T>
where T : new()
{ {
public PluginJsonStorage() public PluginJsonStorage()
{ {

View File

@@ -12,16 +12,16 @@ namespace Wox.Infrastructure.Storage
// This detail is accessed by the storage items and is used to decide if the cache must be deleted or not // This detail is accessed by the storage items and is used to decide if the cache must be deleted or not
public bool clearCache = false; public bool clearCache = false;
private String currentPowerToysVersion = String.Empty; private string currentPowerToysVersion = string.Empty;
private String FilePath { get; set; } = String.Empty; private string FilePath { get; set; } = string.Empty;
// As of now this information is not pertinent but may be in the future // As of now this information is not pertinent but may be in the future
// There may be cases when we want to delete only the .cache files and not the .json storage files // There may be cases when we want to delete only the .cache files and not the .json storage files
private enum StorageType private enum StorageType
{ {
BINARY_STORAGE = 0, BINARY_STORAGE = 0,
JSON_STORAGE = 1 JSON_STORAGE = 1,
} }
// To compare the version numbers // To compare the version numbers
@@ -33,7 +33,7 @@ namespace Wox.Infrastructure.Storage
// If there is some error in populating/retrieving the version numbers, then the cache must be deleted // If there is some error in populating/retrieving the version numbers, then the cache must be deleted
// This case will not be hit, but is present as a fail safe // This case will not be hit, but is present as a fail safe
if (String.IsNullOrEmpty(version1) || String.IsNullOrEmpty(version2)) if (string.IsNullOrEmpty(version1) || string.IsNullOrEmpty(version2))
{ {
return true; return true;
} }
@@ -81,7 +81,7 @@ namespace Wox.Infrastructure.Storage
} }
} }
private string GetFilePath(String AssociatedFilePath, int type) private string GetFilePath(string AssociatedFilePath, int type)
{ {
string suffix = string.Empty; string suffix = string.Empty;
string cacheSuffix = ".cache"; string cacheSuffix = ".cache";
@@ -100,12 +100,12 @@ namespace Wox.Infrastructure.Storage
return filePath; return filePath;
} }
public StoragePowerToysVersionInfo(String AssociatedFilePath, int type) public StoragePowerToysVersionInfo(string AssociatedFilePath, int type)
{ {
FilePath = GetFilePath(AssociatedFilePath, type); FilePath = GetFilePath(AssociatedFilePath, type);
// Get the previous version of PowerToys and cache Storage details from the CacheDetails.json storage file // Get the previous version of PowerToys and cache Storage details from the CacheDetails.json storage file
String previousVersion = GetPreviousVersion(); string previousVersion = GetPreviousVersion();
currentPowerToysVersion = Microsoft.PowerToys.Settings.UI.Lib.Utilities.Helper.GetProductVersion(); currentPowerToysVersion = Microsoft.PowerToys.Settings.UI.Lib.Utilities.Helper.GetProductVersion();
// If the previous version is below a set threshold, then we want to delete the file // If the previous version is below a set threshold, then we want to delete the file

View File

@@ -6,7 +6,8 @@ using System.IO;
namespace Wox.Infrastructure.Storage namespace Wox.Infrastructure.Storage
{ {
public class WoxJsonStorage<T> : JsonStorage<T> where T : new() public class WoxJsonStorage<T> : JsonStorage<T>
where T : new()
{ {
public WoxJsonStorage() public WoxJsonStorage()
{ {

View File

@@ -6,7 +6,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using static Wox.Infrastructure.StringMatcher;
[assembly: InternalsVisibleToAttribute("Microsoft.Plugin.Program.UnitTests")] [assembly: InternalsVisibleToAttribute("Microsoft.Plugin.Program.UnitTests")]
@@ -62,7 +61,10 @@ namespace Wox.Infrastructure
/// </summary> /// </summary>
public MatchResult FuzzyMatch(string query, string stringToCompare, MatchOption opt) public MatchResult FuzzyMatch(string query, string stringToCompare, MatchOption opt)
{ {
if (string.IsNullOrEmpty(stringToCompare) || string.IsNullOrEmpty(query)) return new MatchResult(false, UserSettingSearchPrecision); if (string.IsNullOrEmpty(stringToCompare) || string.IsNullOrEmpty(query))
{
return new MatchResult(false, UserSettingSearchPrecision);
}
query = query.Trim(); query = query.Trim();
@@ -93,7 +95,6 @@ namespace Wox.Infrastructure
for (var compareStringIndex = 0; compareStringIndex < fullStringToCompareWithoutCase.Length; compareStringIndex++) for (var compareStringIndex = 0; compareStringIndex < fullStringToCompareWithoutCase.Length; compareStringIndex++)
{ {
// To maintain a list of indices which correspond to spaces in the string to compare // To maintain a list of indices which correspond to spaces in the string to compare
// To populate the list only for the first query substring // To populate the list only for the first query substring
if (fullStringToCompareWithoutCase[compareStringIndex].Equals(' ') && currentQuerySubstringIndex == 0) if (fullStringToCompareWithoutCase[compareStringIndex].Equals(' ') && currentQuerySubstringIndex == 0)
@@ -150,10 +151,12 @@ namespace Wox.Infrastructure
currentQuerySubstringIndex++; currentQuerySubstringIndex++;
allQuerySubstringsMatched = AllQuerySubstringsMatched(currentQuerySubstringIndex, querySubstrings.Length); allQuerySubstringsMatched = AllQuerySubstringsMatched(currentQuerySubstringIndex, querySubstrings.Length);
if (allQuerySubstringsMatched) if (allQuerySubstringsMatched)
break; {
break;
// otherwise move to the next query substring }
// otherwise move to the next query substring
currentQuerySubstring = querySubstrings[currentQuerySubstringIndex]; currentQuerySubstring = querySubstrings[currentQuerySubstringIndex];
currentQuerySubstringCharacterIndex = 0; currentQuerySubstringCharacterIndex = 0;
} }
@@ -186,8 +189,7 @@ namespace Wox.Infrastructure
} }
} }
private static bool AllPreviousCharsMatched(int startIndexToVerify, int currentQuerySubstringCharacterIndex, private static bool AllPreviousCharsMatched(int startIndexToVerify, int currentQuerySubstringCharacterIndex, string fullStringToCompareWithoutCase, string currentQuerySubstring)
string fullStringToCompareWithoutCase, string currentQuerySubstring)
{ {
var allMatch = true; var allMatch = true;
for (int indexToCheck = 0; indexToCheck < currentQuerySubstringCharacterIndex; indexToCheck++) for (int indexToCheck = 0; indexToCheck < currentQuerySubstringCharacterIndex; indexToCheck++)
@@ -250,11 +252,11 @@ namespace Wox.Infrastructure
} }
else else
{ {
score += threshold * 10 + (count - threshold) * 5; score += (threshold * 10) + ((count - threshold) * 5);
} }
} }
if (String.Equals(query, stringToCompare, StringComparison.CurrentCultureIgnoreCase)) if (string.Equals(query, stringToCompare, StringComparison.CurrentCultureIgnoreCase))
{ {
var bonusForExactMatch = 10; var bonusForExactMatch = 10;
score += bonusForExactMatch; score += bonusForExactMatch;
@@ -267,86 +269,7 @@ namespace Wox.Infrastructure
{ {
Regular = 50, Regular = 50,
Low = 20, Low = 20,
None = 0 None = 0,
} }
} }
public class MatchResult
{
public MatchResult(bool success, SearchPrecisionScore searchPrecision)
{
Success = success;
SearchPrecision = searchPrecision;
}
public MatchResult(bool success, SearchPrecisionScore searchPrecision, List<int> matchData, int rawScore)
{
Success = success;
SearchPrecision = searchPrecision;
MatchData = matchData;
RawScore = rawScore;
}
public bool Success { get; set; }
/// <summary>
/// The final score of the match result with search precision filters applied.
/// </summary>
public int Score { get; private set; }
/// <summary>
/// The raw calculated search score without any search precision filtering applied.
/// </summary>
private int _rawScore;
public int RawScore
{
get { return _rawScore; }
set
{
_rawScore = value;
Score = ScoreAfterSearchPrecisionFilter(_rawScore);
}
}
/// <summary>
/// Matched data to highlight.
/// </summary>
public List<int> MatchData { get; set; }
public SearchPrecisionScore SearchPrecision { get; set; }
public bool IsSearchPrecisionScoreMet()
{
return IsSearchPrecisionScoreMet(_rawScore);
}
private bool IsSearchPrecisionScoreMet(int rawScore)
{
return rawScore >= (int)SearchPrecision;
}
private int ScoreAfterSearchPrecisionFilter(int rawScore)
{
return IsSearchPrecisionScoreMet(rawScore) ? rawScore : 0;
}
}
public class MatchOption
{
/// <summary>
/// prefix of match char, use for highlight
/// </summary>
[Obsolete("this is never used")]
public string Prefix { get; set; } = "";
/// <summary>
/// suffix of match char, use for highlight
/// </summary>
[Obsolete("this is never used")]
public string Suffix { get; set; } = "";
public bool IgnoreCase { get; set; } = true;
}
} }

View File

@@ -33,7 +33,7 @@ namespace Wox.Infrastructure.UserSettings
ID = metadata.ID, ID = metadata.ID,
Name = metadata.Name, Name = metadata.Name,
ActionKeywords = metadata.ActionKeywords, ActionKeywords = metadata.ActionKeywords,
Disabled = metadata.Disabled Disabled = metadata.Disabled,
}; };
} }
} }

View File

@@ -14,7 +14,7 @@ namespace Wox.Infrastructure.UserSettings
public class Settings : BaseModel public class Settings : BaseModel
{ {
private string _hotkey = "Alt + Space"; private string _hotkey = "Alt + Space";
private string _previousHotkey = ""; private string _previousHotkey = string.Empty;
public string PreviousHotkey public string PreviousHotkey
{ {
@@ -63,7 +63,7 @@ namespace Wox.Infrastructure.UserSettings
public string ResultFontStretch { get; set; } public string ResultFontStretch { get; set; }
/// <summary> /// <summary>
/// when false Alphabet static service will always return empty results /// Gets or sets a value indicating whether when false Alphabet static service will always return empty results
/// </summary> /// </summary>
public bool ShouldUsePinyin { get; set; } = false; public bool ShouldUsePinyin { get; set; } = false;
@@ -72,10 +72,13 @@ namespace Wox.Infrastructure.UserSettings
[JsonIgnore] [JsonIgnore]
public string QuerySearchPrecisionString public string QuerySearchPrecisionString
{ {
get { return QuerySearchPrecision.ToString(); } get
{
return QuerySearchPrecision.ToString();
}
set set
{ {
try try
{ {
var precisionScore = (StringMatcher.SearchPrecisionScore)Enum var precisionScore = (StringMatcher.SearchPrecisionScore)Enum
@@ -92,8 +95,8 @@ namespace Wox.Infrastructure.UserSettings
StringMatcher.Instance.UserSettingSearchPrecision = StringMatcher.SearchPrecisionScore.Regular; StringMatcher.Instance.UserSettingSearchPrecision = StringMatcher.SearchPrecisionScore.Regular;
throw; throw;
} }
} }
} }
public bool AutoUpdates { get; set; } = false; public bool AutoUpdates { get; set; } = false;
@@ -143,17 +146,20 @@ namespace Wox.Infrastructure.UserSettings
public bool HideOnStartup { get; set; } public bool HideOnStartup { get; set; }
bool _hideNotifyIcon { get; set; } private bool _hideNotifyIcon;
public bool HideNotifyIcon public bool HideNotifyIcon
{ {
get { return _hideNotifyIcon; } get
{
return _hideNotifyIcon;
}
set set
{ {
_hideNotifyIcon = value; _hideNotifyIcon = value;
OnPropertyChanged(); OnPropertyChanged();
} }
} }
public bool LeaveCmdOpen { get; set; } public bool LeaveCmdOpen { get; set; }
@@ -176,7 +182,7 @@ namespace Wox.Infrastructure.UserSettings
{ {
Selected, Selected,
Empty, Empty,
Preserved Preserved,
} }
[Obsolete] [Obsolete]
@@ -184,6 +190,6 @@ namespace Wox.Infrastructure.UserSettings
{ {
Normal = 0, Normal = 0,
LayeredWindow = 1, LayeredWindow = 1,
DWM = 2 DWM = 2,
} }
} }