Merge branch 'master' into spelling

This commit is contained in:
Clint Rutkas
2020-11-02 09:57:48 -08:00
committed by GitHub
245 changed files with 2177 additions and 1210 deletions

View File

@@ -68,6 +68,7 @@ namespace Microsoft.Plugin.Calculator.UnitTests
var engine = new CalculateEngine();
// Act
// Using InvariantCulture since this is internal
var result = engine.Interpret(input, CultureInfo.InvariantCulture);
// Assert
@@ -84,6 +85,7 @@ namespace Microsoft.Plugin.Calculator.UnitTests
var engine = new CalculateEngine();
// Act
// Using InvariantCulture since this is internal
var result = engine.Interpret(input, CultureInfo.InvariantCulture);
// Assert
@@ -140,6 +142,7 @@ namespace Microsoft.Plugin.Calculator.UnitTests
var engine = new CalculateEngine();
// Act
// Using InvariantCulture since this is internal
var result = engine.Interpret(input, CultureInfo.InvariantCulture);
// Assert
@@ -158,6 +161,7 @@ namespace Microsoft.Plugin.Calculator.UnitTests
var engine = new CalculateEngine();
// Act
// Using InvariantCulture since this is internal
var result = engine.Interpret(input, CultureInfo.InvariantCulture);
// Assert

View File

@@ -15,6 +15,7 @@ namespace Microsoft.Plugin.Calculator
public CalculateResult Interpret(string input)
{
// Using CurrentCulture this is user facing
return Interpret(input, CultureInfo.CurrentCulture);
}

View File

@@ -35,6 +35,7 @@ namespace Microsoft.Plugin.Calculator
try
{
// Using CurrentUICulture since this is user facing
var result = CalculateEngine.Interpret(query.Search, CultureInfo.CurrentUICulture);
// This could happen for some incorrect queries, like pi(2)

View File

@@ -27,6 +27,7 @@ namespace Microsoft.Plugin.Calculator
return new Result
{
// Using CurrentCulture since this is user facing
Title = roundedResult?.ToString(CultureInfo.CurrentCulture),
IcoPath = iconPath,
Score = 300,
@@ -45,6 +46,7 @@ namespace Microsoft.Plugin.Calculator
{
try
{
// Using CurrentUICulture since this is user facing
Clipboard.SetText(roundedResult?.ToString(CultureInfo.CurrentUICulture.NumberFormat));
ret = true;
}

View File

@@ -69,8 +69,10 @@ namespace Microsoft.Plugin.Folder.UnitTests
{
// Setup
var folderHelperMock = new Mock<IFolderHelper>();
// Using Ordinal since this is used with paths
folderHelperMock.Setup(r => r.IsDriveOrSharedFolder(It.IsAny<string>()))
.Returns<string>(s => s.StartsWith("C:", StringComparison.CurrentCultureIgnoreCase));
.Returns<string>(s => s.StartsWith("C:", StringComparison.Ordinal));
var itemResultMock = new Mock<IItemResult>();

View File

@@ -5,11 +5,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions.TestingHelpers;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Plugin.Folder.Sources;
using Microsoft.Plugin.Folder.Sources.Result;
using Moq;
using NUnit.Framework;
namespace Microsoft.Plugin.Folder.UnitTests
@@ -17,115 +16,45 @@ namespace Microsoft.Plugin.Folder.UnitTests
[TestFixture]
public class InternalQueryFolderTests
{
private static readonly HashSet<string> DirectoryExist = new HashSet<string>()
{
@"c:",
@"c:\",
@"c:\Test\",
@"c:\Test\A\",
@"c:\Test\b\",
};
private static readonly HashSet<string> FilesExist = new HashSet<string>()
{
@"c:\bla.txt",
@"c:\Test\test.txt",
@"c:\Test\more-test.png",
};
private static Mock<IQueryFileSystemInfo> _queryFileSystemInfoMock;
private static IQueryFileSystemInfo _queryFileSystemInfoMock;
private static MockFileSystem _fileSystem;
[SetUp]
public void SetupMock()
{
var queryFileSystemInfoMock = new Mock<IQueryFileSystemInfo>();
queryFileSystemInfoMock.Setup(r => r.Exists(It.IsAny<string>()))
.Returns<string>(path => ContainsDirectory(path));
queryFileSystemInfoMock.Setup(r => r.MatchFileSystemInfo(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Returns<string, string, bool>(MatchFileSystemInfo);
_queryFileSystemInfoMock = queryFileSystemInfoMock;
}
// Windows supports C:\\\\\ => C:\
private static bool ContainsDirectory(string path)
{
return DirectoryExist.Contains(TrimDirectoryEnd(path));
}
private static string TrimDirectoryEnd(string path)
{
var trimEnd = path.TrimEnd('\\');
if (path.EndsWith('\\'))
// Note: This mock filesystem adds a 'c:\temp' directory.
_fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>()
{
trimEnd += '\\';
}
{ @"c:\bla.txt", new MockFileData(string.Empty) },
{ @"c:\Test\test.txt", new MockFileData(string.Empty) },
{ @"c:\Test\more-test.png", new MockFileData(string.Empty) },
{ @"c:\Test\A\deep-nested.png", new MockFileData(string.Empty) },
{ @"c:\Test\b\", new MockDirectoryData() },
});
return trimEnd;
}
private static IEnumerable<DisplayFileInfo> MatchFileSystemInfo(string search, string incompleteName, bool isRecursive)
{
Func<string, bool> folderSearchFunc;
Func<string, bool> fileSearchFunc;
switch (isRecursive)
{
case false:
folderSearchFunc = s => s.Equals(search, StringComparison.CurrentCultureIgnoreCase);
var regexSearch = TrimDirectoryEnd(search);
fileSearchFunc = s => Regex.IsMatch(s, $"^{Regex.Escape(regexSearch)}[^\\\\]*$");
break;
case true:
folderSearchFunc = s => s.StartsWith(search, StringComparison.CurrentCultureIgnoreCase);
fileSearchFunc = s => s.StartsWith(search, StringComparison.CurrentCultureIgnoreCase);
break;
}
var directories = DirectoryExist.Where(s => folderSearchFunc(s))
.Select(dir => new DisplayFileInfo()
{
Type = DisplayType.Directory,
FullName = dir,
});
var files = FilesExist.Where(s => fileSearchFunc(s))
.Select(file => new DisplayFileInfo()
{
Type = DisplayType.File,
FullName = file,
});
return directories.Concat(files);
_queryFileSystemInfoMock = new QueryFileSystemInfo(_fileSystem.DirectoryInfo);
}
[Test]
public void Query_ThrowsException_WhenCalledNull()
{
// Setup
var queryInternalDirectory = new QueryInternalDirectory(new FolderSettings(), _queryFileSystemInfoMock.Object);
var queryInternalDirectory = new QueryInternalDirectory(new FolderSettings(), _queryFileSystemInfoMock, _fileSystem.Directory);
// Act & Assert
Assert.Throws<ArgumentNullException>(() => queryInternalDirectory.Query(null).ToArray());
}
[TestCase(@"c", 0, 0, false, Reason = "String empty is nothing")]
[TestCase(@"c:", 1, 1, false, Reason = "Root without \\")]
[TestCase(@"c:\", 1, 1, false, Reason = "Normal root")]
[TestCase(@"c:\Test", 1, 2, false, Reason = "Select yourself")]
[TestCase(@"c:\>", 2, 2, true, Reason = "Max Folder test recursive")]
[TestCase(@"c:\Test>", 2, 2, true, Reason = "2 Folders recursive")]
[TestCase(@"c:\not-exist", 1, 1, false, Reason = "Folder not exist, return root")]
[TestCase(@"c:\not-exist>", 2, 2, true, Reason = "Folder not exist, return root recursive")]
[TestCase(@"c:", 2, 1, false, Reason = "Root without \\")]
[TestCase(@"c:\", 2, 1, false, Reason = "Normal root")]
[TestCase(@"c:\Test", 2, 2, false, Reason = "Select yourself")]
[TestCase(@"c:\not-exist", 2, 1, false, Reason = "Folder not exist, return root")]
[TestCase(@"c:\not-exist\not-exist2", 0, 0, false, Reason = "Folder not exist, return root")]
[TestCase(@"c:\not-exist\not-exist2>", 0, 0, false, Reason = "Folder not exist, return root recursive")]
[TestCase(@"c:\bla.t", 1, 1, false, Reason = "Partial match file")]
[TestCase(@"c:\bla.t", 2, 1, false, Reason = "Partial match file")]
public void Query_WhenCalled(string search, int folders, int files, bool truncated)
{
const int maxFolderSetting = 2;
const int maxFolderSetting = 3;
// Setup
var folderSettings = new FolderSettings()
@@ -134,7 +63,42 @@ namespace Microsoft.Plugin.Folder.UnitTests
MaxFolderResults = maxFolderSetting,
};
var queryInternalDirectory = new QueryInternalDirectory(folderSettings, _queryFileSystemInfoMock.Object);
var queryInternalDirectory = new QueryInternalDirectory(folderSettings, _queryFileSystemInfoMock, _fileSystem.Directory);
// Act
var isDriveOrSharedFolder = queryInternalDirectory.Query(search)
.ToLookup(r => r.GetType());
// Assert
Assert.AreEqual(files, isDriveOrSharedFolder[typeof(FileItemResult)].Count(), "File count doesn't match");
Assert.AreEqual(folders, isDriveOrSharedFolder[typeof(FolderItemResult)].Count(), "folder count doesn't match");
// Always check if there is less than max folders
Assert.LessOrEqual(isDriveOrSharedFolder[typeof(FileItemResult)].Count(), maxFolderSetting, "Files are not limited");
Assert.LessOrEqual(isDriveOrSharedFolder[typeof(FolderItemResult)].Count(), maxFolderSetting, "Folders are not limited");
// Checks if CreateOpenCurrentFolder is displayed
Assert.AreEqual(Math.Min(folders + files, 1), isDriveOrSharedFolder[typeof(CreateOpenCurrentFolderResult)].Count(), "CreateOpenCurrentFolder displaying is incorrect");
Assert.AreEqual(truncated, isDriveOrSharedFolder[typeof(TruncatedItemResult)].Count() == 1, "CreateOpenCurrentFolder displaying is incorrect");
}
[TestCase(@"c:\>", 3, 3, true, Reason = "Max Folder test recursive")]
[TestCase(@"c:\Test>", 3, 3, true, Reason = "2 Folders recursive")]
[TestCase(@"c:\not-exist>", 3, 3, true, Reason = "Folder not exist, return root recursive")]
[TestCase(@"c:\not-exist\not-exist2>", 0, 0, false, Reason = "Folder not exist, return root recursive")]
public void Query_Recursive_WhenCalled(string search, int folders, int files, bool truncated)
{
const int maxFolderSetting = 3;
// Setup
var folderSettings = new FolderSettings()
{
MaxFileResults = maxFolderSetting,
MaxFolderResults = maxFolderSetting,
};
var queryInternalDirectory = new QueryInternalDirectory(folderSettings, _queryFileSystemInfoMock, _fileSystem.Directory);
// Act
var isDriveOrSharedFolder = queryInternalDirectory.Query(search)

View File

@@ -14,6 +14,7 @@
<PackageReference Include="nunit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="System.IO.Abstractions.TestingHelpers" Version="12.2.3" />
</ItemGroup>
<ItemGroup>

View File

@@ -5,7 +5,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Abstractions;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
@@ -17,6 +17,7 @@ namespace Microsoft.Plugin.Folder
{
internal class ContextMenuLoader : IContextMenu
{
private readonly IFileSystem _fileSystem = new FileSystem();
private readonly PluginInitContext _context;
public ContextMenuLoader(PluginInitContext context)
@@ -76,7 +77,7 @@ namespace Microsoft.Plugin.Folder
{
if (record.Type == ResultType.File)
{
Helper.OpenInConsole(Path.GetDirectoryName(record.FullPath));
Helper.OpenInConsole(_fileSystem.Path.GetDirectoryName(record.FullPath));
}
else
{

View File

@@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.IO.Abstractions;
using System.Linq;
using System.Windows.Controls;
using ManagedCommon;
@@ -21,9 +22,10 @@ namespace Microsoft.Plugin.Folder
public const string DeleteFileFolderImagePath = "Images\\delete.dark.png";
public const string CopyImagePath = "Images\\copy.dark.png";
private static readonly IFileSystem _fileSystem = new FileSystem();
private static readonly PluginJsonStorage<FolderSettings> _storage = new PluginJsonStorage<FolderSettings>();
private static readonly FolderSettings _settings = _storage.Load();
private static readonly IQueryInternalDirectory _internalDirectory = new QueryInternalDirectory(_settings, new QueryFileSystemInfo());
private static readonly IQueryInternalDirectory _internalDirectory = new QueryInternalDirectory(_settings, new QueryFileSystemInfo(_fileSystem.DirectoryInfo), _fileSystem.Directory);
private static readonly FolderHelper _folderHelper = new FolderHelper(new DriveInformation(), new FolderLinksSettings(_settings));
private static readonly ICollection<IFolderProcessor> _processors = new IFolderProcessor[]

View File

@@ -78,6 +78,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="System.IO.Abstractions" Version="12.2.5" />
<PackageReference Include="System.Runtime" Version="4.3.1" />
</ItemGroup>

View File

@@ -2,17 +2,6 @@
// 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 System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using Wox.Infrastructure;
using Wox.Plugin;
using Wox.Plugin.Logger;
namespace Microsoft.Plugin.Folder
{
public class SearchResult

View File

@@ -3,12 +3,10 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using Wox.Infrastructure.FileSystemHelper;
namespace Microsoft.Plugin.Folder.Sources
{
public interface IQueryFileSystemInfo : IDirectoryWrapper
public interface IQueryFileSystemInfo
{
IEnumerable<DisplayFileInfo> MatchFileSystemInfo(string search, string incompleteName, bool isRecursive);
}

View File

@@ -4,20 +4,22 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
namespace Microsoft.Plugin.Folder.Sources
{
internal class DriveInformation : IDriveInformation
{
private static readonly IFileSystem _fileSystem = new FileSystem();
private static readonly List<string> DriverNames = InitialDriverList().ToList();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Do not want to change the behavior of the application, but want to enforce static analysis")]
private static IEnumerable<string> InitialDriverList()
{
var directorySeparatorChar = System.IO.Path.DirectorySeparatorChar;
return DriveInfo.GetDrives()
// Using InvariantCulture since this is internal
var directorySeparatorChar = _fileSystem.Path.DirectorySeparatorChar;
return _fileSystem.DriveInfo.GetDrives()
.Select(driver => driver.Name.ToLower(CultureInfo.InvariantCulture).TrimEnd(directorySeparatorChar));
}

View File

@@ -27,6 +27,7 @@ namespace Microsoft.Plugin.Folder.Sources
throw new ArgumentNullException(paramName: nameof(query));
}
// Using OrdinalIgnoreCase since this is internal
return _folderLinks.FolderLinks()
.Where(x => x.Nickname.StartsWith(query, StringComparison.OrdinalIgnoreCase));
}
@@ -38,7 +39,8 @@ namespace Microsoft.Plugin.Folder.Sources
throw new ArgumentNullException(nameof(search));
}
if (search.StartsWith(@"\\", StringComparison.InvariantCulture))
// Using Ordinal this is internal and we're comparing symbols
if (search.StartsWith(@"\\", StringComparison.Ordinal))
{ // share folder
return true;
}
@@ -48,6 +50,7 @@ namespace Microsoft.Plugin.Folder.Sources
if (driverNames.Any())
{
// Using InvariantCultureIgnoreCase since this is searching for drive names
if (driverNames.Any(dn => search.StartsWith(dn, StringComparison.InvariantCultureIgnoreCase)))
{
// normal drive letter

View File

@@ -2,20 +2,26 @@
// 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 System.IO;
using System.IO.Abstractions;
using System.Linq;
using Wox.Infrastructure.FileSystemHelper;
namespace Microsoft.Plugin.Folder.Sources
{
public class QueryFileSystemInfo : DirectoryWrapper, IQueryFileSystemInfo
public class QueryFileSystemInfo : IQueryFileSystemInfo
{
private readonly IDirectoryInfoFactory _directoryInfoFactory;
public QueryFileSystemInfo(IDirectoryInfoFactory directoryInfoFactory)
{
_directoryInfoFactory = directoryInfoFactory;
}
public IEnumerable<DisplayFileInfo> MatchFileSystemInfo(string search, string incompleteName, bool isRecursive)
{
// search folder and add results
var directoryInfo = new DirectoryInfo(search);
var directoryInfo = _directoryInfoFactory.FromDirectoryName(search);
var fileSystemInfos = directoryInfo.EnumerateFileSystemInfos(incompleteName, new EnumerationOptions()
{
MatchType = MatchType.Win32,
@@ -30,7 +36,7 @@ namespace Microsoft.Plugin.Folder.Sources
.Select(CreateDisplayFileInfo);
}
private static DisplayFileInfo CreateDisplayFileInfo(FileSystemInfo fileSystemInfo)
private static DisplayFileInfo CreateDisplayFileInfo(IFileSystemInfo fileSystemInfo)
{
return new DisplayFileInfo()
{
@@ -40,9 +46,9 @@ namespace Microsoft.Plugin.Folder.Sources
};
}
private static DisplayType GetDisplayType(FileSystemInfo fileSystemInfo)
private static DisplayType GetDisplayType(IFileSystemInfo fileSystemInfo)
{
if (fileSystemInfo is DirectoryInfo)
if (fileSystemInfo is IDirectoryInfo)
{
return DisplayType.Directory;
}

View File

@@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using ManagedCommon;
using Microsoft.Plugin.Folder.Sources.Result;
@@ -18,6 +19,7 @@ namespace Microsoft.Plugin.Folder.Sources
{
private readonly FolderSettings _settings;
private readonly IQueryFileSystemInfo _queryFileSystemInfo;
private readonly IDirectory _directory;
private static readonly HashSet<char> SpecialSearchChars = new HashSet<char>
{
@@ -26,10 +28,11 @@ namespace Microsoft.Plugin.Folder.Sources
private static string _warningIconPath;
public QueryInternalDirectory(FolderSettings folderSettings, IQueryFileSystemInfo queryFileSystemInfo)
public QueryInternalDirectory(FolderSettings folderSettings, IQueryFileSystemInfo queryFileSystemInfo, IDirectory directory)
{
_settings = folderSettings;
_queryFileSystemInfo = queryFileSystemInfo;
_directory = directory;
}
private static bool HasSpecialChars(string search)
@@ -47,7 +50,7 @@ namespace Microsoft.Plugin.Folder.Sources
private (string search, string incompleteName) Process(string search)
{
string incompleteName = string.Empty;
if (HasSpecialChars(search) || !_queryFileSystemInfo.Exists($@"{search}\"))
if (HasSpecialChars(search) || !_directory.Exists($@"{search}\"))
{
// if folder doesn't exist, we want to take the last part and use it afterwards to help the user
// find the right folder.
@@ -60,10 +63,11 @@ namespace Microsoft.Plugin.Folder.Sources
}
// Remove everything after the last \ and add *
// Using InvariantCulture since this is internal
incompleteName = search.Substring(index + 1)
.ToLower(CultureInfo.InvariantCulture) + "*";
search = search.Substring(0, index + 1);
if (!_queryFileSystemInfo.Exists(search))
if (!_directory.Exists(search))
{
return default;
}
@@ -71,7 +75,8 @@ namespace Microsoft.Plugin.Folder.Sources
else
{
// folder exist, add \ at the end of doesn't exist
if (!search.EndsWith(@"\", StringComparison.InvariantCulture))
// Using Ordinal since this is internal and is used for a symbol
if (!search.EndsWith(@"\", StringComparison.Ordinal))
{
search += @"\";
}

View File

@@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.IO;
using System.IO.Abstractions;
using Wox.Infrastructure;
using Wox.Plugin;
@@ -13,17 +13,31 @@ namespace Microsoft.Plugin.Folder.Sources.Result
{
private static readonly IShellAction ShellAction = new ShellAction();
private readonly IPath _path;
public FileItemResult()
: this(new FileSystem().Path)
{
}
private FileItemResult(IPath path)
{
_path = path;
}
public string FilePath { get; set; }
public string Title => Path.GetFileName(FilePath);
public string Title => _path.GetFileName(FilePath);
public string Search { get; set; }
public Wox.Plugin.Result Create(IPublicAPI contextApi)
{
var result = new Wox.Plugin.Result(StringMatcher.FuzzySearch(Search, Path.GetFileName(FilePath)).MatchData)
var result = new Wox.Plugin.Result(StringMatcher.FuzzySearch(Search, _path.GetFileName(FilePath)).MatchData)
{
Title = Title,
// Using CurrentCulture since this is user facing
SubTitle = string.Format(CultureInfo.CurrentCulture, Properties.Resources.wox_plugin_folder_select_file_result_subtitle, FilePath),
IcoPath = FilePath,
Action = c => ShellAction.Execute(FilePath, contextApi),

View File

@@ -37,6 +37,8 @@ namespace Microsoft.Plugin.Folder.Sources.Result
{
Title = Title,
IcoPath = Path,
// Using CurrentCulture since this is user facing
SubTitle = string.Format(CultureInfo.CurrentCulture, Properties.Resources.wox_plugin_folder_select_folder_result_subtitle, Subtitle),
QueryTextDisplay = Path,
ContextData = new SearchResult { Type = ResultType.Folder, FullPath = Path },

View File

@@ -23,6 +23,8 @@ namespace Microsoft.Plugin.Folder.Sources.Result
{
Title = Properties.Resources.Microsoft_plugin_folder_truncation_warning_title,
QueryTextDisplay = Search,
// Using CurrentCulture since this is user facing
SubTitle = string.Format(CultureInfo.CurrentCulture, Properties.Resources.Microsoft_plugin_folder_truncation_warning_subtitle, PostTruncationCount, PreTruncationCount),
IcoPath = WarningIconPath,
};

View File

@@ -39,7 +39,8 @@ namespace Microsoft.Plugin.Folder.Sources
var sanitizedPath = Regex.Replace(search, @"[\/\\]+", "\\");
// A network path must start with \\
if (!sanitizedPath.StartsWith("\\", StringComparison.InvariantCulture))
// Using Ordinal since this is internal and used with a symbol
if (!sanitizedPath.StartsWith("\\", StringComparison.Ordinal))
{
return sanitizedPath;
}

View File

@@ -28,6 +28,8 @@ namespace Microsoft.Plugin.Folder
{
Title = Title,
IcoPath = Path,
// Using CurrentCulture since this is user facing
SubTitle = string.Format(CultureInfo.CurrentCulture, Properties.Resources.wox_plugin_folder_select_folder_result_subtitle, Subtitle),
QueryTextDisplay = Path,
ContextData = new SearchResult { Type = ResultType.Folder, FullPath = Path },

View File

@@ -5,7 +5,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Abstractions;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
@@ -19,6 +19,8 @@ namespace Microsoft.Plugin.Indexer
{
internal class ContextMenuLoader : IContextMenu
{
private readonly IPath _path = new FileSystem().Path;
private readonly PluginInitContext _context;
public enum ResultType
@@ -41,7 +43,7 @@ namespace Microsoft.Plugin.Indexer
var contextMenus = new List<ContextMenuResult>();
if (selectedResult.ContextData is SearchResult record)
{
ResultType type = Path.HasExtension(record.Path) ? ResultType.File : ResultType.Folder;
ResultType type = _path.HasExtension(record.Path) ? ResultType.File : ResultType.Folder;
if (type == ResultType.File)
{
@@ -95,7 +97,7 @@ namespace Microsoft.Plugin.Indexer
{
if (type == ResultType.File)
{
Helper.OpenInConsole(Path.GetDirectoryName(record.Path));
Helper.OpenInConsole(_path.GetDirectoryName(record.Path));
}
else
{
@@ -147,9 +149,10 @@ namespace Microsoft.Plugin.Indexer
// Function to test if the file can be run as admin
private bool CanFileBeRunAsAdmin(string path)
{
string fileExtension = Path.GetExtension(path);
string fileExtension = _path.GetExtension(path);
foreach (string extension in appExtensions)
{
// Using OrdinalIgnoreCase since this is internal
if (extension.Equals(fileExtension, StringComparison.OrdinalIgnoreCase))
{
return true;

View File

@@ -7,7 +7,7 @@ using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Controls;
@@ -24,6 +24,8 @@ namespace Microsoft.Plugin.Indexer
{
internal class Main : ISettingProvider, IPlugin, ISavable, IPluginI18n, IContextMenu, IDisposable, IDelayedExecutionPlugin
{
private static readonly IFileSystem _fileSystem = new FileSystem();
// This variable contains metadata about the Plugin
private PluginInitContext _context;
@@ -38,7 +40,7 @@ namespace Microsoft.Plugin.Indexer
private readonly WindowsSearchAPI _api = new WindowsSearchAPI(_search);
// To obtain information regarding the drives that are indexed
private readonly IndexerDriveDetection _driveDetection = new IndexerDriveDetection(new RegistryWrapper(), new DriveInfoWrapper());
private readonly IndexerDriveDetection _driveDetection = new IndexerDriveDetection(new RegistryWrapper(), new DriveDetection.DriveInfoWrapper());
// Reserved keywords in oleDB
private readonly string reservedStringPattern = @"^[\/\\\$\%]+$|^.*[<>].*$";
@@ -110,12 +112,14 @@ namespace Microsoft.Plugin.Indexer
foreach (var searchResult in searchResultsList)
{
var path = searchResult.Path;
// Using CurrentCulture since this is user facing
var toolTipTitle = string.Format(CultureInfo.CurrentCulture, "{0} : {1}", Properties.Resources.Microsoft_plugin_indexer_name, searchResult.Title);
var toolTipText = string.Format(CultureInfo.CurrentCulture, "{0} : {1}", Properties.Resources.Microsoft_plugin_indexer_path, path);
string workingDir = null;
if (_settings.UseLocationAsWorkingDir)
{
workingDir = Path.GetDirectoryName(path);
workingDir = _fileSystem.Path.GetDirectoryName(path);
}
Result r = new Result();
@@ -149,7 +153,7 @@ namespace Microsoft.Plugin.Indexer
r.ContextData = searchResult;
// If the result is a directory, then it's display should show a directory.
if (Directory.Exists(path))
if (_fileSystem.Directory.Exists(path))
{
r.QueryTextDisplay = path;
}

View File

@@ -59,6 +59,7 @@ namespace Microsoft.Plugin.Indexer.SearchHelper
}
// # is URI syntax for the fragment component, need to be encoded so LocalPath returns complete path
// Using OrdinalIgnoreCase since this is internal and used with symbols
var string_path = ((string)oleDBResult.FieldData[0]).Replace("#", "%23", StringComparison.OrdinalIgnoreCase);
var uri_path = new Uri(string_path);
@@ -89,10 +90,11 @@ namespace Microsoft.Plugin.Indexer.SearchHelper
// convert file pattern if it is not '*'. Don't create restriction for '*' as it includes all files.
if (pattern != "*")
{
pattern = pattern.Replace("*", "%", StringComparison.InvariantCulture);
pattern = pattern.Replace("?", "_", StringComparison.InvariantCulture);
// Using Ordinal since these are internal and used with symbols
pattern = pattern.Replace("*", "%", StringComparison.Ordinal);
pattern = pattern.Replace("?", "_", StringComparison.Ordinal);
if (pattern.Contains("%", StringComparison.InvariantCulture) || pattern.Contains("_", StringComparison.InvariantCulture))
if (pattern.Contains("%", StringComparison.Ordinal) || pattern.Contains("_", StringComparison.Ordinal))
{
queryHelper.QueryWhereRestrictions += " AND System.FileName LIKE '" + pattern + "' ";
}

View File

@@ -39,10 +39,13 @@
</Item>
<Item ItemId=";Microsoft_plugin_indexer_drivedetectionwarning" ItemType="0;.resx" PsrId="211" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
<Val><![CDATA[Warning: Not all files are indexed.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Upozornění: Ne všechny jednotky jsou indexované.]]></Val>
<Val><![CDATA[Upozornění: Ne všechny soubory jsou indexované.]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
</Prev>
</Str>
<Disp Icon="Str" />
</Item>

View File

@@ -39,10 +39,13 @@
</Item>
<Item ItemId=";Microsoft_plugin_indexer_drivedetectionwarning" ItemType="0;.resx" PsrId="211" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
<Val><![CDATA[Warning: Not all files are indexed.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Warnung: Nicht alle Laufwerke sind indiziert.]]></Val>
<Val><![CDATA[Warnung: Nicht alle Dateien sind indiziert.]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
</Prev>
</Str>
<Disp Icon="Str" />
</Item>

View File

@@ -39,10 +39,13 @@
</Item>
<Item ItemId=";Microsoft_plugin_indexer_drivedetectionwarning" ItemType="0;.resx" PsrId="211" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
<Val><![CDATA[Warning: Not all files are indexed.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Advertencia: No se indexaron todas las unidades.]]></Val>
<Val><![CDATA[Advertencia: No se indexaron todos los archivos.]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
</Prev>
</Str>
<Disp Icon="Str" />
</Item>

View File

@@ -39,10 +39,13 @@
</Item>
<Item ItemId=";Microsoft_plugin_indexer_drivedetectionwarning" ItemType="0;.resx" PsrId="211" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
<Val><![CDATA[Warning: Not all files are indexed.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[警告: すべてのドライブがインデックス化されているわけではありません。]]></Val>
<Val><![CDATA[警告: すべてのファイルがインデックス化されているわけではありません。]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
</Prev>
</Str>
<Disp Icon="Str" />
</Item>

View File

@@ -39,10 +39,13 @@
</Item>
<Item ItemId=";Microsoft_plugin_indexer_drivedetectionwarning" ItemType="0;.resx" PsrId="211" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
<Val><![CDATA[Warning: Not all files are indexed.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Waarschuwing: niet alle stations zijn geïndexeerd.]]></Val>
<Val><![CDATA[Waarschuwing: niet alle bestanden zijn geïndexeerd.]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
</Prev>
</Str>
<Disp Icon="Str" />
</Item>

View File

@@ -39,10 +39,13 @@
</Item>
<Item ItemId=";Microsoft_plugin_indexer_drivedetectionwarning" ItemType="0;.resx" PsrId="211" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
<Val><![CDATA[Warning: Not all files are indexed.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Ostrzeżenie: Nie wszystkie dyski są indeksowane.]]></Val>
<Val><![CDATA[Ostrzeżenie: Nie wszystkie pliki są indeksowane.]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
</Prev>
</Str>
<Disp Icon="Str" />
</Item>

View File

@@ -39,10 +39,13 @@
</Item>
<Item ItemId=";Microsoft_plugin_indexer_drivedetectionwarning" ItemType="0;.resx" PsrId="211" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
<Val><![CDATA[Warning: Not all files are indexed.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Внимание! Проиндексированы не все диски.]]></Val>
<Val><![CDATA[Предупреждение: индексируются не все файлы.]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
</Prev>
</Str>
<Disp Icon="Str" />
</Item>

View File

@@ -39,10 +39,13 @@
</Item>
<Item ItemId=";Microsoft_plugin_indexer_drivedetectionwarning" ItemType="0;.resx" PsrId="211" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
<Val><![CDATA[Warning: Not all files are indexed.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[警告: 並非所有磁碟機皆已編製索引。]]></Val>
<Val><![CDATA[警告: 並非所有檔案皆已編製索引。]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA[Warning: Not all drives are indexed.]]></Val>
</Prev>
</Str>
<Disp Icon="Str" />
</Item>

View File

@@ -567,6 +567,7 @@ namespace Microsoft.Plugin.Program.UnitTests.Programs
var result = _cmderRunCommand.Result("cmder", string.Empty, mock.Object);
// Assert
// Using Ordinal since this is used internally
Assert.IsTrue(result.Title.Equals(_cmderRunCommand.Name, StringComparison.Ordinal));
Assert.IsFalse(result.Title.Equals(_cmderRunCommand.Description, StringComparison.Ordinal));
}

View File

@@ -5,6 +5,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using Microsoft.Plugin.Program.Programs;
using Microsoft.Plugin.Program.Storage;
@@ -209,7 +210,7 @@ namespace Microsoft.Plugin.Program.UnitTests.Storage
FileSystemEventArgs e = new FileSystemEventArgs(WatcherChangeTypes.Created, "directory", path);
// File.ReadAllLines must be mocked for url applications
var mockFile = new Mock<IFileWrapper>();
var mockFile = new Mock<IFile>();
mockFile.Setup(m => m.ReadAllLines(It.IsAny<string>())).Returns(new string[] { "URL=steam://rungameid/1258080", "IconFile=iconFile" });
Win32Program.FileWrapper = mockFile.Object;
@@ -256,7 +257,7 @@ namespace Microsoft.Plugin.Program.UnitTests.Storage
FileSystemEventArgs e = new FileSystemEventArgs(WatcherChangeTypes.Deleted, directory, path);
// File.ReadAllLines must be mocked for url applications
var mockFile = new Mock<IFileWrapper>();
var mockFile = new Mock<IFile>();
mockFile.Setup(m => m.ReadAllLines(It.IsAny<string>())).Returns(new string[] { "URL=steam://rungameid/1258080", "IconFile=iconFile" });
Win32Program.FileWrapper = mockFile.Object;
@@ -279,7 +280,7 @@ namespace Microsoft.Plugin.Program.UnitTests.Storage
RenamedEventArgs e = new RenamedEventArgs(WatcherChangeTypes.Renamed, directory, newpath, oldpath);
// File.ReadAllLines must be mocked for url applications
var mockFile = new Mock<IFileWrapper>();
var mockFile = new Mock<IFile>();
mockFile.Setup(m => m.ReadAllLines(It.IsAny<string>())).Returns(new string[] { "URL=steam://rungameid/1258080", "IconFile=iconFile" });
Win32Program.FileWrapper = mockFile.Object;

View File

@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security;

View File

@@ -23,6 +23,7 @@ namespace Microsoft.Plugin.Program
{
for (var i = 1; i < query.Terms.Count; i++)
{
// Using Ordinal since this is internal and used with a symbol
if (!string.Equals(query.Terms[i], DoubleDash, StringComparison.Ordinal))
{
continue;

View File

@@ -2,7 +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.IO;
using System.IO.Abstractions;
namespace Microsoft.Plugin.Program
{
@@ -16,11 +16,13 @@ namespace Microsoft.Plugin.Program
/// </remarks>
public class ProgramSource
{
private static readonly IFileSystem FileSystem = new FileSystem();
private string name;
public string Location { get; set; }
public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
public string Name { get => name ?? FileSystem.DirectoryInfo.FromDirectoryName(Location).Name; set => name = value; }
public bool Enabled { get; set; } = true;

View File

@@ -4,7 +4,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
@@ -19,6 +19,8 @@ namespace Microsoft.Plugin.Program.Programs
[Serializable]
public partial class UWP
{
private static readonly IPath Path = new FileSystem().Path;
public string Name { get; }
public string FullName { get; }
@@ -204,6 +206,7 @@ namespace Microsoft.Plugin.Program.Programs
{
if (obj is UWP uwp)
{
// Using CurrentCultureIgnoreCase since this is used with FamilyName
return FamilyName.Equals(uwp.FamilyName, StringComparison.CurrentCultureIgnoreCase);
}
else
@@ -214,6 +217,7 @@ namespace Microsoft.Plugin.Program.Programs
public override int GetHashCode()
{
// Using CurrentCultureIgnoreCase since this is used with FamilyName
return FamilyName.GetHashCode(StringComparison.CurrentCultureIgnoreCase);
}

View File

@@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
@@ -31,6 +32,10 @@ namespace Microsoft.Plugin.Program.Programs
[Serializable]
public class UWPApplication : IProgram
{
private static readonly IFileSystem FileSystem = new FileSystem();
private static readonly IPath Path = FileSystem.Path;
private static readonly IFile File = FileSystem.File;
public string AppListEntry { get; set; }
public string UniqueIdentifier { get; set; }
@@ -111,6 +116,7 @@ namespace Microsoft.Plugin.Program.Programs
result.Title = DisplayName;
result.SetTitleHighlightData(StringMatcher.FuzzySearch(query, Name).MatchData);
// Using CurrentCulture since this is user facing
var toolTipTitle = string.Format(CultureInfo.CurrentCulture, "{0}: {1}", Properties.Resources.powertoys_run_plugin_program_file_name, result.Title);
var toolTipText = string.Format(CultureInfo.CurrentCulture, "{0}: {1}", Properties.Resources.powertoys_run_plugin_program_file_path, Package.Location);
result.ToolTipData = new ToolTipData(toolTipTitle, toolTipText);
@@ -263,6 +269,8 @@ namespace Microsoft.Plugin.Program.Programs
if (File.Exists(manifest))
{
var file = File.ReadAllText(manifest);
// Using OrdinalIgnoreCase since this is used internally
if (file.Contains("TrustLevel=\"mediumIL\"", StringComparison.OrdinalIgnoreCase))
{
return true;
@@ -276,12 +284,16 @@ namespace Microsoft.Plugin.Program.Programs
internal string ResourceFromPri(string packageFullName, string resourceReference)
{
const string prefix = "ms-resource:";
// Using OrdinalIgnoreCase since this is used internally
if (!string.IsNullOrWhiteSpace(resourceReference) && resourceReference.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
// magic comes from @talynone
// https://github.com/talynone/Wox.Plugin.WindowsUniversalAppLauncher/blob/master/StoreAppLauncher/Helpers/NativeApiHelper.cs#L139-L153
string key = resourceReference.Substring(prefix.Length);
string parsed;
// Using Ordinal/OrdinalIgnorcase since these are used internally
if (key.StartsWith("//", StringComparison.Ordinal))
{
parsed = prefix + key;
@@ -540,6 +552,8 @@ namespace Microsoft.Plugin.Program.Programs
// windows 8 https://msdn.microsoft.com/en-us/library/windows/apps/br211475.aspx
string path;
bool isLogoUriSet;
// Using Ordinal since this is used internally with uri
if (uri.Contains("\\", StringComparison.Ordinal))
{
path = Path.Combine(Package.Location, uri);
@@ -598,6 +612,7 @@ namespace Microsoft.Plugin.Program.Programs
string currentBackgroundColor;
if (BackgroundColor == "transparent")
{
// Using InvariantCulture since this is internal
currentBackgroundColor = SystemParameters.WindowGlassBrush.ToString(CultureInfo.InvariantCulture);
}
else

View File

@@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Reflection;
using System.Security;
@@ -20,12 +21,18 @@ using Wox.Infrastructure;
using Wox.Infrastructure.FileSystemHelper;
using Wox.Plugin;
using Wox.Plugin.Logger;
using DirectoryWrapper = Wox.Infrastructure.FileSystemHelper.DirectoryWrapper;
namespace Microsoft.Plugin.Program.Programs
{
[Serializable]
public class Win32Program : IProgram
{
private static readonly IFileSystem FileSystem = new FileSystem();
private static readonly IPath Path = FileSystem.Path;
private static readonly IFile File = FileSystem.File;
private static readonly IDirectory Directory = FileSystem.Directory;
public string Name { get; set; }
public string UniqueIdentifier { get; set; }
@@ -57,7 +64,7 @@ namespace Microsoft.Plugin.Program.Programs
// Wrappers for File Operations
public static IFileVersionInfoWrapper FileVersionInfoWrapper { get; set; } = new FileVersionInfoWrapper();
public static IFileWrapper FileWrapper { get; set; } = new FileWrapper();
public static IFile FileWrapper { get; set; } = new FileSystem().File;
public static IShellLinkHelper Helper { get; set; } = new ShellLinkHelper();
@@ -98,6 +105,7 @@ namespace Microsoft.Plugin.Program.Programs
// To Filter PWAs when the user searches for the main application
// All Chromium based applications contain the --app-id argument
// Reference : https://codereview.chromium.org/399045/show
// Using Ordinal IgnoreCase since this is used internally
bool isWebApplication = FullPath.Contains(ProxyWebApp, StringComparison.OrdinalIgnoreCase) && Arguments.Contains(AppIdArgument, StringComparison.OrdinalIgnoreCase);
return isWebApplication;
}
@@ -121,6 +129,7 @@ namespace Microsoft.Plugin.Program.Programs
// check if any space separated query is a part of the app name or path name
foreach (var subquery in subqueries)
{
// Using OrdinalIgnoreCase since these are used internally
if (FullPath.Contains(subquery, StringComparison.OrdinalIgnoreCase))
{
pathContainsQuery = true;
@@ -172,6 +181,7 @@ namespace Microsoft.Plugin.Program.Programs
{
if (query != null && AppType == ApplicationType.RunCommand)
{
// Using OrdinalIgnoreCase since this is used internally
if (!query.Equals(Name, StringComparison.OrdinalIgnoreCase) && !query.Equals(ExecutableName, StringComparison.OrdinalIgnoreCase))
{
return false;
@@ -235,6 +245,7 @@ namespace Microsoft.Plugin.Program.Programs
result.Title = Name;
result.SetTitleHighlightData(StringMatcher.FuzzySearch(query, Name).MatchData);
// Using CurrentCulture since this is user facing
var toolTipTitle = string.Format(CultureInfo.CurrentCulture, "{0}: {1}", Properties.Resources.powertoys_run_plugin_program_file_name, result.Title);
var toolTipText = string.Format(CultureInfo.CurrentCulture, "{0}: {1}", Properties.Resources.powertoys_run_plugin_program_file_path, FullPath);
result.ToolTipData = new ToolTipData(toolTipTitle, toolTipText);
@@ -342,6 +353,8 @@ namespace Microsoft.Plugin.Program.Programs
Name = Path.GetFileNameWithoutExtension(path),
ExecutableName = Path.GetFileName(path),
IcoPath = path,
// Using CurrentCulture since this is user facing
FullPath = path.ToLower(CultureInfo.CurrentCulture),
UniqueIdentifier = path,
ParentDirectory = Directory.GetParent(path).FullName,
@@ -384,6 +397,7 @@ namespace Microsoft.Plugin.Program.Programs
foreach (string line in lines)
{
// Using OrdinalIgnoreCase since this is used internally
if (line.StartsWith(urlPrefix, StringComparison.OrdinalIgnoreCase))
{
urlPath = line.Substring(urlPrefix.Length);
@@ -407,6 +421,7 @@ namespace Microsoft.Plugin.Program.Programs
}
}
// Using OrdinalIgnoreCase since this is used internally
if (line.StartsWith(iconFilePrefix, StringComparison.OrdinalIgnoreCase))
{
iconPath = line.Substring(iconFilePrefix.Length);
@@ -465,6 +480,8 @@ namespace Microsoft.Plugin.Program.Programs
if (File.Exists(target) || Directory.Exists(target))
{
program.LnkResolvedPath = program.FullPath;
// Using CurrentCulture since this is user facing
program.FullPath = Path.GetFullPath(target).ToLower(CultureInfo.CurrentCulture);
program.AppType = GetAppTypeFromPath(target);
@@ -543,6 +560,7 @@ namespace Microsoft.Plugin.Program.Programs
string extension = Extension(path);
ApplicationType appType = ApplicationType.GenericFile;
// Using OrdinalIgnoreCase since these are used internally with paths
if (ExecutableApplicationExtensions.Contains(extension))
{
appType = ApplicationType.Win32Application;
@@ -677,6 +695,7 @@ namespace Microsoft.Plugin.Program.Programs
private static string Extension(string path)
{
// Using CurrentCulture since this is user facing
var extension = Path.GetExtension(path)?.ToLower(CultureInfo.CurrentCulture);
if (!string.IsNullOrEmpty(extension))
@@ -734,6 +753,7 @@ namespace Microsoft.Plugin.Program.Programs
.Distinct()
.ToArray();
// Using OrdinalIgnoreCase since this is used internally with paths
var programs1 = allPaths.AsParallel().Where(p => Extension(p).Equals(ShortcutExtension, StringComparison.OrdinalIgnoreCase)).Select(LnkProgram);
var programs2 = allPaths.AsParallel().Where(p => Extension(p).Equals(ApplicationReferenceExtension, StringComparison.OrdinalIgnoreCase)).Select(CreateWin32Program);
var programs3 = allPaths.AsParallel().Where(p => Extension(p).Equals(InternetShortcutExtension, StringComparison.OrdinalIgnoreCase)).Select(InternetShortcutProgram);
@@ -768,6 +788,7 @@ namespace Microsoft.Plugin.Program.Programs
.Distinct()
.ToArray();
// Using OrdinalIgnoreCase since this is used internally with paths
var programs1 = paths.AsParallel().Where(p => Extension(p).Equals(ShortcutExtension, StringComparison.OrdinalIgnoreCase)).Select(LnkProgram);
var programs2 = paths.AsParallel().Where(p => Extension(p).Equals(ApplicationReferenceExtension, StringComparison.OrdinalIgnoreCase)).Select(CreateWin32Program);
var programs3 = paths.AsParallel().Where(p => Extension(p).Equals(InternetShortcutExtension, StringComparison.OrdinalIgnoreCase)).Select(InternetShortcutProgram);
@@ -908,6 +929,7 @@ namespace Microsoft.Plugin.Program.Programs
&& !string.IsNullOrEmpty(app1.ExecutableName) && !string.IsNullOrEmpty(app2.ExecutableName)
&& !string.IsNullOrEmpty(app1.FullPath) && !string.IsNullOrEmpty(app2.FullPath))
{
// Using OrdinalIgnoreCase since this is used internally
return app1.Name.Equals(app2.Name, StringComparison.OrdinalIgnoreCase)
&& app1.ExecutableName.Equals(app2.ExecutableName, StringComparison.OrdinalIgnoreCase)
&& app1.FullPath.Equals(app2.FullPath, StringComparison.OrdinalIgnoreCase);
@@ -924,6 +946,8 @@ namespace Microsoft.Plugin.Program.Programs
int fullPathPrime = 31;
int result = 1;
// Using Ordinal since this is used internally
result = (result * namePrime) + obj.Name.ToUpperInvariant().GetHashCode(StringComparison.Ordinal);
result = (result * executablePrime) + obj.ExecutableName.ToUpperInvariant().GetHashCode(StringComparison.Ordinal);
result = (result * fullPathPrime) + obj.FullPath.ToUpperInvariant().GetHashCode(StringComparison.Ordinal);

View File

@@ -24,6 +24,7 @@ namespace Microsoft.Plugin.Program.Storage
// To obtain the last event associated with a particular app.
while (eventHandlingQueue.TryPeek(out string currentAppPath))
{
// Using OrdinalIgnoreCase since this is used internally with paths
if (string.IsNullOrEmpty(previousAppPath) || previousAppPath.Equals(currentAppPath, StringComparison.OrdinalIgnoreCase))
{
// To dequeue a path only if it is the first one in the queue or if the path was the same as thre previous one (to avoid trying to create apps on duplicate events)

View File

@@ -8,6 +8,7 @@ using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.IO.Abstractions;
using System.Threading.Tasks;
using Wox.Infrastructure.Storage;
using Wox.Plugin.Logger;
@@ -17,6 +18,9 @@ namespace Microsoft.Plugin.Program.Storage
{
internal class Win32ProgramRepository : ListRepository<Programs.Win32Program>, IProgramRepository
{
private static readonly IFileSystem FileSystem = new FileSystem();
private static readonly IPath Path = FileSystem.Path;
private const string LnkExtension = ".lnk";
private const string UrlExtension = ".url";
@@ -145,6 +149,7 @@ namespace Microsoft.Plugin.Program.Storage
try
{
// To mitigate the issue of not having a FullPath for a shortcut app, we iterate through the items and find the app with the same hashcode.
// Using OrdinalIgnoreCase since this is used internally
if (extension.Equals(LnkExtension, StringComparison.OrdinalIgnoreCase))
{
app = GetAppWithSameLnkResolvedPath(path);
@@ -174,6 +179,7 @@ namespace Microsoft.Plugin.Program.Storage
{
foreach (Win32Program app in Items)
{
// Using CurrentCultureIgnoreCase since application names could be dependent on currentculture See: https://github.com/microsoft/PowerToys/pull/5847/files#r468245190
if (name.Equals(app.Name, StringComparison.CurrentCultureIgnoreCase) && executableName.Equals(app.ExecutableName, StringComparison.CurrentCultureIgnoreCase))
{
return app;
@@ -189,7 +195,8 @@ namespace Microsoft.Plugin.Program.Storage
{
foreach (Programs.Win32Program app in Items)
{
if (lnkResolvedPath.ToLower(CultureInfo.CurrentCulture).Equals(app.LnkResolvedPath, StringComparison.CurrentCultureIgnoreCase))
// Using Invariant / OrdinalIgnoreCase since we're comparing paths
if (lnkResolvedPath.ToUpperInvariant().Equals(app.LnkResolvedPath, StringComparison.OrdinalIgnoreCase))
{
return app;
}
@@ -201,7 +208,9 @@ namespace Microsoft.Plugin.Program.Storage
private void OnAppCreated(object sender, FileSystemEventArgs e)
{
string path = e.FullPath;
if (!Path.GetExtension(path).Equals(UrlExtension, StringComparison.CurrentCultureIgnoreCase) && !Path.GetExtension(path).Equals(LnkExtension, StringComparison.CurrentCultureIgnoreCase))
// Using OrdinalIgnoreCase since we're comparing extensions
if (!Path.GetExtension(path).Equals(UrlExtension, StringComparison.OrdinalIgnoreCase) && !Path.GetExtension(path).Equals(LnkExtension, StringComparison.OrdinalIgnoreCase))
{
Programs.Win32Program app = Programs.Win32Program.GetAppFromPath(path);
if (app != null)
@@ -214,7 +223,9 @@ namespace Microsoft.Plugin.Program.Storage
private void OnAppChanged(object sender, FileSystemEventArgs e)
{
string path = e.FullPath;
if (Path.GetExtension(path).Equals(UrlExtension, StringComparison.CurrentCultureIgnoreCase) || Path.GetExtension(path).Equals(LnkExtension, StringComparison.CurrentCultureIgnoreCase))
// Using OrdinalIgnoreCase since we're comparing extensions
if (Path.GetExtension(path).Equals(UrlExtension, StringComparison.OrdinalIgnoreCase) || Path.GetExtension(path).Equals(LnkExtension, StringComparison.OrdinalIgnoreCase))
{
// When a url or lnk app is installed, multiple created and changed events are triggered.
// To prevent the code from acting on the first such event (which may still be during app installation), the events are added a common queue and dequeued by a background task at regular intervals - https://github.com/microsoft/PowerToys/issues/6429.

View File

@@ -8,6 +8,7 @@ using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Reflection;
using System.Windows.Input;
@@ -23,6 +24,11 @@ namespace Microsoft.Plugin.Shell
{
public class Main : IPlugin, ISettingProvider, IPluginI18n, IContextMenu, ISavable
{
private static readonly IFileSystem FileSystem = new FileSystem();
private static readonly IPath Path = FileSystem.Path;
private static readonly IFile File = FileSystem.File;
private static readonly IDirectory Directory = FileSystem.Directory;
private readonly ShellPluginSettings _settings;
private readonly PluginJsonStorage<ShellPluginSettings> _storage;
@@ -84,6 +90,7 @@ namespace Microsoft.Plugin.Shell
{
if (m.Key == cmd)
{
// Using CurrentCulture since this is user facing
result.SubTitle = Properties.Resources.wox_plugin_cmd_plugin_name + ": " + string.Format(CultureInfo.CurrentCulture, Properties.Resources.wox_plugin_cmd_cmd_has_been_executed_times, m.Value);
return null;
}
@@ -91,6 +98,8 @@ namespace Microsoft.Plugin.Shell
var ret = new Result
{
Title = m.Key,
// Using CurrentCulture since this is user facing
SubTitle = Properties.Resources.wox_plugin_cmd_plugin_name + ": " + string.Format(CultureInfo.CurrentCulture, Properties.Resources.wox_plugin_cmd_cmd_has_been_executed_times, m.Value),
IcoPath = IconPath,
Action = c =>
@@ -128,6 +137,8 @@ namespace Microsoft.Plugin.Shell
.Select(m => new Result
{
Title = m.Key,
// Using CurrentCulture since this is user facing
SubTitle = Properties.Resources.wox_plugin_cmd_plugin_name + ": " + string.Format(CultureInfo.CurrentCulture, Properties.Resources.wox_plugin_cmd_cmd_has_been_executed_times, m.Value),
IcoPath = IconPath,
Action = c =>

View File

@@ -5,7 +5,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Abstractions;
using System.Text;
using ManagedCommon;
using Microsoft.Plugin.Uri.UriHelper;
@@ -17,6 +17,10 @@ namespace Microsoft.Plugin.Uri
{
public class Main : IPlugin, IPluginI18n, IContextMenu, ISavable, IDisposable
{
private static readonly IFileSystem FileSystem = new FileSystem();
private static readonly IPath Path = FileSystem.Path;
private static readonly IFile File = FileSystem.File;
private readonly ExtendedUriParser _uriParser;
private readonly UriResolver _uriResolver;
private readonly PluginJsonStorage<UriSettings> _storage;
@@ -119,6 +123,7 @@ namespace Microsoft.Plugin.Uri
?? _registryWrapper.GetRegistryValue("HKEY_CLASSES_ROOT\\" + progId + "\\DefaultIcon", null);
// "Handles 'Indirect Strings' (UWP programs)"
// Using Ordinal since this is internal and used with a symbol
if (programLocation.StartsWith("@", StringComparison.Ordinal))
{
var directProgramLocationStringBuilder = new StringBuilder(128);
@@ -137,6 +142,7 @@ namespace Microsoft.Plugin.Uri
}
else
{
// Using Ordinal since this is internal and used with a symbol
var indexOfComma = programLocation.IndexOf(',', StringComparison.Ordinal);
BrowserIconPath = indexOfComma > 0
? programLocation.Substring(0, indexOfComma)

View File

@@ -18,9 +18,10 @@ namespace Microsoft.Plugin.Uri.UriHelper
}
// Handle common cases UriBuilder does not handle
if (input.EndsWith(":", StringComparison.Ordinal)
|| input.EndsWith(".", StringComparison.Ordinal)
|| input.EndsWith(":/", StringComparison.Ordinal))
// Using CurrentCulture since this is a user typed string
if (input.EndsWith(":", StringComparison.CurrentCulture)
|| input.EndsWith(".", StringComparison.CurrentCulture)
|| input.EndsWith(":/", StringComparison.CurrentCulture))
{
result = default;
return false;

View File

@@ -37,6 +37,7 @@ namespace Microsoft.Plugin.WindowWalker.Components
throw new ArgumentNullException(nameof(text));
}
// Using CurrentCulture since this is user facing
searchText = searchText.ToLower(CultureInfo.CurrentCulture);
text = text.ToLower(CultureInfo.CurrentCulture);

View File

@@ -563,6 +563,7 @@ namespace Microsoft.Plugin.WindowWalker.Components
public override string ToString()
{
// Using CurrentCulture since this is user facing
return string.Format(System.Globalization.CultureInfo.CurrentCulture, "{{Left={0},Top={1},Right={2},Bottom={3}}}", Left, Top, Right, Bottom);
}
}

View File

@@ -54,6 +54,7 @@ namespace Microsoft.Plugin.WindowWalker.Components
set
{
// Using CurrentCulture since this is user facing
searchText = value.ToLower(CultureInfo.CurrentCulture).Trim();
}
}

View File

@@ -252,6 +252,7 @@ namespace Microsoft.Plugin.WindowWalker.Components
// 1) There is a weird flashing behavior when trying
// to use ShowWindow for switching tabs in IE
// 2) SetForegroundWindow fails on minimized windows
// Using Ordinal since this is internal
if (ProcessName.ToUpperInvariant().Equals("IEXPLORE.EXE", StringComparison.Ordinal) || !Minimized)
{
NativeMethods.SetForegroundWindow(Hwnd);
@@ -270,6 +271,7 @@ namespace Microsoft.Plugin.WindowWalker.Components
/// <returns>The title of the window</returns>
public override string ToString()
{
// Using CurrentCulture since this is user facing
return Title + " (" + ProcessName.ToUpper(CultureInfo.CurrentCulture) + ")";
}