PowerToys/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Main.cs

206 lines
7.1 KiB
C#
Raw Normal View History

2020-08-18 01:00:56 +08:00
// 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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Plugin.Program.Programs;
using Microsoft.Plugin.Program.Storage;
using Wox.Infrastructure.Logger;
using Wox.Infrastructure.Storage;
using Wox.Plugin;
using Stopwatch = Wox.Infrastructure.Stopwatch;
namespace Microsoft.Plugin.Program
{
public class Main : IPlugin, IPluginI18n, IContextMenu, ISavable, IReloadable, IDisposable
2020-08-18 01:00:56 +08:00
{
internal static ProgramPluginSettings Settings { get; set; }
private static bool IsStartupIndexProgramsRequired => Settings.LastIndexTime.AddDays(3) < DateTime.Today;
private static PluginInitContext _context;
private readonly PluginJsonStorage<ProgramPluginSettings> _settingsStorage;
private bool _disposed = false;
Enable Static Analysis on programs plugin (#5847) * Removing unused ProgramSettings constructor paramaters. * Fix for: Severity Code Description Project File Line Suppression State Error CA1829 Use the "Count" property instead of Enumerable.Count(). Microsoft.Plugin.Program C:\Repos\PowerToys\src\modules\launcher\Plugins\Microsoft.Plugin.Program\Views\ProgramSetting.xaml.cs 182 Active Severity Code Description Project File Line Suppression State Error CA1827 Count() is used where Any() could be used instead to improve performance. Microsoft.Plugin.Program C:\Repos\PowerToys\src\modules\launcher\Plugins\Microsoft.Plugin.Program\Views\ProgramSetting.xaml.cs 287 Active * Fixes for CA1031: https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1031?view=vs-2019 * More fixes(Suppression) for CA1031 (Catching base exception) https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1031?view=vs-2019 * Fix for nested types being externally visible. CA1034 https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1034?view=vs-2019 * Fix for CA1028 If possible, make the underlying type of Hresult System.Int32 instead of uint. Microsoft.Plugin.Program C:\Repos\PowerToys\src\modules\launcher\Plugins\Microsoft.Plugin.Program\Programs\UWP.cs 236 Active * Fix for CA2227 Collection properties should be readonly. https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2227?view=vs-2019 Fix rror CA2211 Non-constant fields should not be visible https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2211?view=vs-2019 * CA2208: Instantiate argument exceptions correctly https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2208?view=vs-2019 * Win32.cs Static analysis fixes: CA2200: Rethrow to preserve stack details https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200?view=vs-2019 CA1825: Avoid zero-length array allocations https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1825?view=vs-2019 CA2211: Non-constant fields should not be visible https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2211?view=vs-2019 * More Win32.cs static analysis fixes: CA1307: Specify StringComparison https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1307?view=vs-2019 Verifying query is not null before using it. CA1062: Validate arguments of public methods https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1062?view=vs-2019 CA1305: Specify IFormatProvider https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1305?view=vs-2019 * UWPApplication. CA2007: Do not directly await a Task https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2007?view=vs-2019 * Error CA2010 Consume the hresult returned by method 'Microsoft.Plugin.Program.Programs.AppxPackageHelper.IAppxManifestApplication.GetStringValue(string, out string)' and call Marshal.ThrowExceptionForHR. Note: CA2010 has been removed from future FXCop versions as it can provide incorrect advice for methods that don't return hresult (possibly when [PreserveSig] has been incorrectly labeled.) I've verified the methods in question do still return hresults. * More fixes for Error CA2010 Consume the hresult returned by method and call Marshal.ThrowExceptionForHR. * Fixes for: Error CA2000 Call System.IDisposable.Dispose on object created before all references to it are out of scope. * Suppress CA1031:Do not catch general exception types * Fixes for Error CA1034 Do not nest type ... * Fixing Unit tests that were broken as per a previous fix. * Fix for: CA1034: Nested types should not be visible: https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1034?view=vs-2019 * Suppressing CA1707 for native/com types. CA1707:Identifiers should not contain underscores * Fix for Error CA1307 The behavior of 'string.Replace(string, string?)' could vary based on the current user's locale settings. * Fixes for Error CA1825 Avoid unnecessary zero-length array allocations. Use Array.Empty<string>() instead. * Fix for: Error CA1823 Unused field 'IndexLock'. * Fixes for CA1822: Mark members as static: https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1822?view=vs-2019 * Fix for Error CA1819 Properties should not return arrays * Fix for Error CA1806 ContextMenus calls Trim but does not use the new string instance that the method returns. Pass the instance as an argument to another method, assign the instance to a variable, or remove the call if it is unnecessary. * Fix for Error CA1801 Parameter settings of method UpdateSettings is never used. Remove the parameter or use it in the method body. * Fix for Error CA1724 The type name Settings conflicts in whole or in part with the namespace name 'Microsoft.PowerToys.Settings'. * Includes FxCop for static analysis * Fix for Error CA1717 Only FlagsAttribute enums should have plural names * Suppress Stgm flags: Error CA1714 Flags enums should have plural names Microsoft.Plugin.Program * Rename Win32 to Win32Program Fix for: Error CA1724 The type name Win32 conflicts in whole or in part with the namespace name 'Microsoft.Win32' defined in the .NET Framework. Rename the type to eliminate the conflict. * Fixes for Error CA1507 Use nameof in place of string literal * Using ordinal instead of invariant culture when not symbolic comparison * CA1308: Normalize strings to uppercase https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1308?view=vs-2019 * CA1304: Specify CultureInfo CA1305: Specify IFormatProvider https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1305?view=vs-2019 https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1304?view=vs-2019 * CA1062: Validate arguments of public methods https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1062?view=vs-2019 * CA1056: URI properties should not be strings https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1056?view=vs-2019 Fix: Making LogoURi private, as it is only used internally and operated on as a string * Warning CA1052 Type 'AppxPackageHelper' is a static holder type but is neither static nor NotInheritable * CA1060: Move P/Invokes to NativeMethods class https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1060?view=vs-2019 * Programs Plugin - Treat warnings as errors true * CA1031:Do not catch general exception types Missed release only compile issue. Making debug and release behave the same. * Renaming 'Create' to 'CreateWin32Program' based on PR feedback.
2020-08-12 00:08:44 +08:00
private PackageRepository _packageRepository = new PackageRepository(new PackageCatalogWrapper(), new BinaryStorage<IList<UWPApplication>>("UWP"));
Functionality to detect Win32 apps which are installed, deleted or renamed while PowerToys is running (#4960) * Added file system wrapper and interface * added win32program repository which would load store app and also handle new apps being added/deleted * Added event handlers to win32 program repo * added paths to monitor and setting FSWs for each location * Events firing as expected * filter extensions added, events fire as expected * override gethashcode so that duplicates don't show up. OnCreated and OnDeleted events trigger as expected * implemented setter for filters in FileSystemWatcher * Rename adds item but does not seem to delete the previous app * catching an exception when a duplicate item is inserted * Removed notify filter for directory because we only need to monitor files * Added exe programs to be indexed in the desktop and startmenu * created a new class to init FileSystemHelpers instead of main * Added fix for shortcut applications to work as expected while renaming and deleting them * Added wrappers for file system operations * Added some tests * Added all tests for appref-ms and added a condition to search in sub directories * Added tests for Exe applications * Added lnk app tests * Added tests for shortcut applications * removed unnecessary wrappers * override Equals for win32 * removed debug statements * Fixed exe issue * Fixed internet shortcut exception * fixed renaming shortcut apps * Added a retry block for ReadAllLines * capitalized method name - RetrieveTargetPath * made naming consistent, helper variables start with underscore * Added the exception condition back * renamed Win32ProgramRepositoryHelper to Win32ProgramFileSystemWatchers * made win32Program repository variable static * changed list to ilist * disposed file system watchers * make retrieveTargetPath upper case in tests
2020-07-18 13:32:21 +08:00
private static Win32ProgramFileSystemWatchers _win32ProgramRepositoryHelper;
2020-08-18 01:00:56 +08:00
private static Win32ProgramRepository _win32ProgramRepository;
public Main()
{
_settingsStorage = new PluginJsonStorage<ProgramPluginSettings>();
Settings = _settingsStorage.Load();
// This helper class initializes the file system watchers based on the locations to watch
_win32ProgramRepositoryHelper = new Win32ProgramFileSystemWatchers();
// Initialize the Win32ProgramRepository with the settings object
_win32ProgramRepository = new Win32ProgramRepository(_win32ProgramRepositoryHelper.FileSystemWatchers.Cast<IFileSystemWatcherWrapper>().ToList(), new BinaryStorage<IList<Programs.Win32Program>>("Win32"), Settings, _win32ProgramRepositoryHelper.PathsToWatch);
Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Preload programs cost", () =>
{
_win32ProgramRepository.Load();
_packageRepository.Load();
});
Log.Info($"|Microsoft.Plugin.Program.Main|Number of preload win32 programs <{_win32ProgramRepository.Count()}>");
var a = Task.Run(() =>
{
if (IsStartupIndexProgramsRequired || !_win32ProgramRepository.Any())
{
Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Win32Program index cost", _win32ProgramRepository.IndexPrograms);
}
});
var b = Task.Run(() =>
{
if (IsStartupIndexProgramsRequired || !_packageRepository.Any())
{
Stopwatch.Normal("|Microsoft.Plugin.Program.Main|Win32Program index cost", _packageRepository.IndexPrograms);
}
});
Task.WaitAll(a, b);
Settings.LastIndexTime = DateTime.Today;
}
public void Save()
{
_settingsStorage.Save();
_win32ProgramRepository.Save();
_packageRepository.Save();
}
public List<Result> Query(Query query)
{
var results1 = _win32ProgramRepository.AsParallel()
.Where(p => p.Enabled)
.Select(p => p.Result(query.Search, _context.API));
var results2 = _packageRepository.AsParallel()
.Where(p => p.Enabled)
.Select(p => p.Result(query.Search, _context.API));
var result = results1.Concat(results2).Where(r => r != null && r.Score > 0);
if (result.Any())
{
var maxScore = result.Max(x => x.Score);
result = result.Where(x => x.Score > Settings.MinScoreThreshold * maxScore);
}
2020-08-18 01:00:56 +08:00
return result.ToList();
}
public void Init(PluginInitContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_context.API.ThemeChanged += OnThemeChanged;
UpdateUWPIconPath(_context.API.GetCurrentTheme());
}
public void OnThemeChanged(Theme currentTheme, Theme newTheme)
{
UpdateUWPIconPath(newTheme);
}
public void UpdateUWPIconPath(Theme theme)
{
foreach (UWPApplication app in _packageRepository)
{
app.UpdatePath(theme);
}
}
public void IndexPrograms()
{
var t1 = Task.Run(() => _win32ProgramRepository.IndexPrograms());
var t2 = Task.Run(() => _packageRepository.IndexPrograms());
Task.WaitAll(t1, t2);
Settings.LastIndexTime = DateTime.Today;
}
public string GetTranslatedPluginTitle()
{
return _context.API.GetTranslation("wox_plugin_program_plugin_name");
}
public string GetTranslatedPluginDescription()
{
return _context.API.GetTranslation("wox_plugin_program_plugin_description");
}
public List<ContextMenuResult> LoadContextMenus(Result selectedResult)
{
if (selectedResult == null)
{
throw new ArgumentNullException(nameof(selectedResult));
}
var menuOptions = new List<ContextMenuResult>();
if (selectedResult.ContextData is Programs.IProgram program)
{
menuOptions = program.ContextMenus(_context.API);
}
return menuOptions;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "We want to keep the process alive and show the user a warning message")]
public static void StartProcess(Func<ProcessStartInfo, Process> runProcess, ProcessStartInfo info)
{
try
{
if (runProcess == null)
{
throw new ArgumentNullException(nameof(runProcess));
}
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
runProcess(info);
}
catch (Exception)
{
var name = "Plugin: Program";
var message = $"Unable to start: {info.FileName}";
_context.API.ShowMsg(name, message, string.Empty);
}
}
public void ReloadData()
{
IndexPrograms();
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_context.API.ThemeChanged -= OnThemeChanged;
Functionality to detect Win32 apps which are installed, deleted or renamed while PowerToys is running (#4960) * Added file system wrapper and interface * added win32program repository which would load store app and also handle new apps being added/deleted * Added event handlers to win32 program repo * added paths to monitor and setting FSWs for each location * Events firing as expected * filter extensions added, events fire as expected * override gethashcode so that duplicates don't show up. OnCreated and OnDeleted events trigger as expected * implemented setter for filters in FileSystemWatcher * Rename adds item but does not seem to delete the previous app * catching an exception when a duplicate item is inserted * Removed notify filter for directory because we only need to monitor files * Added exe programs to be indexed in the desktop and startmenu * created a new class to init FileSystemHelpers instead of main * Added fix for shortcut applications to work as expected while renaming and deleting them * Added wrappers for file system operations * Added some tests * Added all tests for appref-ms and added a condition to search in sub directories * Added tests for Exe applications * Added lnk app tests * Added tests for shortcut applications * removed unnecessary wrappers * override Equals for win32 * removed debug statements * Fixed exe issue * Fixed internet shortcut exception * fixed renaming shortcut apps * Added a retry block for ReadAllLines * capitalized method name - RetrieveTargetPath * made naming consistent, helper variables start with underscore * Added the exception condition back * renamed Win32ProgramRepositoryHelper to Win32ProgramFileSystemWatchers * made win32Program repository variable static * changed list to ilist * disposed file system watchers * make retrieveTargetPath upper case in tests
2020-07-18 13:32:21 +08:00
_win32ProgramRepositoryHelper.Dispose();
_disposed = true;
}
}
}
2020-08-18 01:00:56 +08:00
}
}