2020-08-17 10:00:56 -07: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.
2020-08-12 11:46:11 -07:00
using System ;
2020-09-25 10:36:38 -07:00
using System.Collections.Concurrent ;
2020-07-17 22:32:21 -07:00
using System.Collections.Generic ;
using System.Collections.ObjectModel ;
2020-08-17 10:00:56 -07:00
using System.Globalization ;
2020-08-12 11:46:11 -07:00
using System.IO ;
2020-11-02 18:33:43 +01:00
using System.IO.Abstractions ;
2020-09-25 10:36:38 -07:00
using System.Threading.Tasks ;
2020-08-17 10:00:56 -07:00
using Wox.Infrastructure.Storage ;
2020-10-23 13:06:22 -07:00
using Wox.Plugin.Logger ;
2020-08-12 11:46:11 -07:00
using Win32Program = Microsoft . Plugin . Program . Programs . Win32Program ;
2020-08-17 10:00:56 -07:00
2020-07-17 22:32:21 -07:00
namespace Microsoft.Plugin.Program.Storage
{
2020-08-11 09:08:44 -07:00
internal class Win32ProgramRepository : ListRepository < Programs . Win32Program > , IProgramRepository
2020-07-17 22:32:21 -07:00
{
2020-11-02 18:33:43 +01:00
private static readonly IFileSystem FileSystem = new FileSystem ( ) ;
private static readonly IPath Path = FileSystem . Path ;
2020-08-14 12:46:23 -07:00
private const string LnkExtension = ".lnk" ;
private const string UrlExtension = ".url" ;
2021-07-28 14:15:47 +03:00
private IStorage < IList < Programs . Win32Program > > _storage ;
2020-08-11 09:08:44 -07:00
private ProgramPluginSettings _settings ;
2020-07-17 22:32:21 -07:00
private IList < IFileSystemWatcherWrapper > _fileSystemWatcherHelpers ;
private string [ ] _pathsToWatch ;
private int _numberOfPathsToWatch ;
2020-08-14 12:46:23 -07:00
private Collection < string > extensionsToWatch = new Collection < string > { "*.exe" , $"*{LnkExtension}" , "*.appref-ms" , $"*{UrlExtension}" } ;
2020-07-17 22:32:21 -07:00
2020-09-25 10:36:38 -07:00
private static ConcurrentQueue < string > commonEventHandlingQueue = new ConcurrentQueue < string > ( ) ;
2021-07-28 14:15:47 +03:00
public Win32ProgramRepository ( IList < IFileSystemWatcherWrapper > fileSystemWatcherHelpers , IStorage < IList < Win32Program > > storage , ProgramPluginSettings settings , string [ ] pathsToWatch )
2020-07-17 22:32:21 -07:00
{
2020-08-14 12:46:23 -07:00
_fileSystemWatcherHelpers = fileSystemWatcherHelpers ;
2021-07-28 14:15:47 +03:00
_storage = storage ? ? throw new ArgumentNullException ( nameof ( storage ) , "Win32ProgramRepository requires an initialized storage interface" ) ;
2020-08-14 12:46:23 -07:00
_settings = settings ? ? throw new ArgumentNullException ( nameof ( settings ) , "Win32ProgramRepository requires an initialized settings object" ) ;
_pathsToWatch = pathsToWatch ;
_numberOfPathsToWatch = pathsToWatch . Length ;
2020-07-17 22:32:21 -07:00
InitializeFileSystemWatchers ( ) ;
2020-09-25 10:36:38 -07:00
// This task would always run in the background trying to dequeue file paths from the queue at regular intervals.
2020-10-20 11:13:53 -07:00
_ = Task . Run ( async ( ) = >
2020-09-25 10:36:38 -07:00
{
while ( true )
{
int dequeueDelay = 500 ;
2020-10-20 11:13:53 -07:00
string appPath = await EventHandler . GetAppPathFromQueueAsync ( commonEventHandlingQueue , dequeueDelay ) . ConfigureAwait ( false ) ;
2020-09-25 10:36:38 -07:00
// To allow for the installation process to finish.
2020-10-20 11:13:53 -07:00
await Task . Delay ( 5000 ) . ConfigureAwait ( false ) ;
2020-09-25 10:36:38 -07:00
if ( ! string . IsNullOrEmpty ( appPath ) )
{
Programs . Win32Program app = Programs . Win32Program . GetAppFromPath ( appPath ) ;
if ( app ! = null )
{
Add ( app ) ;
}
}
}
} ) . ConfigureAwait ( false ) ;
2020-07-17 22:32:21 -07:00
}
private void InitializeFileSystemWatchers ( )
{
2020-07-22 13:27:17 -07:00
for ( int index = 0 ; index < _numberOfPathsToWatch ; index + + )
2020-07-17 22:32:21 -07:00
{
// To set the paths to monitor
_fileSystemWatcherHelpers [ index ] . Path = _pathsToWatch [ index ] ;
// to be notified when there is a change to a file
2020-07-22 10:58:01 -07:00
_fileSystemWatcherHelpers [ index ] . NotifyFilter = NotifyFilters . FileName | NotifyFilters . LastWrite ;
2020-07-17 22:32:21 -07:00
// filtering the app types that we want to monitor
_fileSystemWatcherHelpers [ index ] . Filters = extensionsToWatch ;
// Registering the event handlers
_fileSystemWatcherHelpers [ index ] . Created + = OnAppCreated ;
_fileSystemWatcherHelpers [ index ] . Deleted + = OnAppDeleted ;
_fileSystemWatcherHelpers [ index ] . Renamed + = OnAppRenamed ;
2020-07-22 10:58:01 -07:00
_fileSystemWatcherHelpers [ index ] . Changed + = OnAppChanged ;
2020-07-17 22:32:21 -07:00
// Enable the file system watcher
_fileSystemWatcherHelpers [ index ] . EnableRaisingEvents = true ;
// Enable it to search in sub folders as well
_fileSystemWatcherHelpers [ index ] . IncludeSubdirectories = true ;
}
2020-08-17 10:00:56 -07:00
}
2020-10-30 14:41:23 -04:00
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Intentionally keeping the process alive>")]
2020-07-17 22:32:21 -07:00
private void OnAppRenamed ( object sender , RenamedEventArgs e )
{
string oldPath = e . OldFullPath ;
string newPath = e . FullPath ;
string extension = Path . GetExtension ( newPath ) ;
2020-09-10 15:06:37 -07:00
Win32Program . ApplicationType appType = Win32Program . GetAppTypeFromPath ( newPath ) ;
2021-01-14 13:17:32 +02:00
Programs . Win32Program newApp = Win32Program . GetAppFromPath ( newPath ) ;
2020-08-11 09:08:44 -07:00
Programs . Win32Program oldApp = null ;
2020-07-17 22:32:21 -07:00
// Once the shortcut application is renamed, the old app does not exist and therefore when we try to get the FullPath we get the lnk path instead of the exe path
// This changes the hashCode() of the old application.
// Therefore, instead of retrieving the old app using the GetAppFromPath(), we construct the application ourself
// This situation is not encountered for other application types because the fullPath is the path itself, instead of being computed by using the path to the app.
try
{
2020-09-10 15:06:37 -07:00
if ( appType = = Win32Program . ApplicationType . ShortcutApplication )
2020-07-17 22:32:21 -07:00
{
2021-01-14 13:17:32 +02:00
oldApp = new Win32Program ( ) { Name = Path . GetFileNameWithoutExtension ( e . OldName ) , ExecutableName = Path . GetFileName ( e . OldName ) , FullPath = newApp . FullPath } ;
2020-07-17 22:32:21 -07:00
}
2020-09-10 15:06:37 -07:00
else if ( appType = = Win32Program . ApplicationType . InternetShortcutApplication )
2020-07-17 22:32:21 -07:00
{
2020-08-11 09:08:44 -07:00
oldApp = new Win32Program ( ) { Name = Path . GetFileNameWithoutExtension ( e . OldName ) , ExecutableName = Path . GetFileName ( e . OldName ) , FullPath = newApp . FullPath } ;
2020-07-17 22:32:21 -07:00
}
else
{
2020-08-11 09:08:44 -07:00
oldApp = Win32Program . GetAppFromPath ( oldPath ) ;
2020-07-17 22:32:21 -07:00
}
}
catch ( Exception ex )
{
2021-01-14 13:17:32 +02:00
Log . Exception ( $"OnAppRenamed-{extension} Program|{e.OldName}|Unable to create program from {oldPath}" , ex , GetType ( ) ) ;
2020-07-17 22:32:21 -07:00
}
2020-08-17 10:00:56 -07:00
2020-07-17 22:32:21 -07:00
// To remove the old app which has been renamed and to add the new application.
if ( oldApp ! = null )
{
2021-01-14 13:17:32 +02:00
if ( string . IsNullOrWhiteSpace ( oldApp . Name ) | | string . IsNullOrWhiteSpace ( oldApp . ExecutableName ) | | string . IsNullOrWhiteSpace ( oldApp . FullPath ) )
{
Log . Error ( $"Old app was not initialized properly. OldFullPath: {e.OldFullPath}; OldName: {e.OldName}; FullPath: {e.FullPath}" , GetType ( ) ) ;
}
else
{
Remove ( oldApp ) ;
}
2020-07-17 22:32:21 -07:00
}
if ( newApp ! = null )
{
Add ( newApp ) ;
}
2020-08-17 10:00:56 -07:00
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Intentionally keeping the process alive")]
2020-07-17 22:32:21 -07:00
private void OnAppDeleted ( object sender , FileSystemEventArgs e )
{
string path = e . FullPath ;
string extension = Path . GetExtension ( path ) ;
2020-08-11 09:08:44 -07:00
Programs . Win32Program app = null ;
2020-07-17 22:32:21 -07:00
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.
2020-10-30 16:43:09 -07:00
// Using OrdinalIgnoreCase since this is used internally
2020-08-14 12:46:23 -07:00
if ( extension . Equals ( LnkExtension , StringComparison . OrdinalIgnoreCase ) )
2020-07-17 22:32:21 -07:00
{
app = GetAppWithSameLnkResolvedPath ( path ) ;
}
2020-08-14 12:46:23 -07:00
else if ( extension . Equals ( UrlExtension , StringComparison . OrdinalIgnoreCase ) )
2020-07-17 22:32:21 -07:00
{
app = GetAppWithSameNameAndExecutable ( Path . GetFileNameWithoutExtension ( path ) , Path . GetFileName ( path ) ) ;
}
else
{
2020-08-11 09:08:44 -07:00
app = Programs . Win32Program . GetAppFromPath ( path ) ;
2020-07-17 22:32:21 -07:00
}
}
2020-07-22 13:27:17 -07:00
catch ( Exception ex )
2020-07-17 22:32:21 -07:00
{
2020-09-23 16:32:06 -07:00
Log . Exception ( $"OnAppDeleted-{extension}Program|{path}|Unable to create program from {path}" , ex , GetType ( ) ) ;
2020-07-17 22:32:21 -07:00
}
if ( app ! = null )
{
Remove ( app ) ;
}
}
// When a URL application is deleted, we can no longer get the HashCode directly from the path because the FullPath a Url app is the URL obtained from reading the file
2022-03-14 16:46:34 +01:00
[System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1309:Use ordinal string comparison", Justification = "Using CurrentCultureIgnoreCase since application names could be dependent on currentculture See: https://github.com/microsoft/PowerToys/pull/5847/files#r468245190")]
2020-08-11 09:08:44 -07:00
private Win32Program GetAppWithSameNameAndExecutable ( string name , string executableName )
2020-07-17 22:32:21 -07:00
{
2020-08-11 09:08:44 -07:00
foreach ( Win32Program app in Items )
2020-07-17 22:32:21 -07:00
{
2020-10-30 16:43:09 -07:00
// Using CurrentCultureIgnoreCase since application names could be dependent on currentculture See: https://github.com/microsoft/PowerToys/pull/5847/files#r468245190
2020-08-11 09:08:44 -07:00
if ( name . Equals ( app . Name , StringComparison . CurrentCultureIgnoreCase ) & & executableName . Equals ( app . ExecutableName , StringComparison . CurrentCultureIgnoreCase ) )
2020-07-17 22:32:21 -07:00
{
return app ;
}
}
2020-08-17 10:00:56 -07:00
2020-07-17 22:32:21 -07:00
return null ;
}
// To mitigate the issue faced (as stated above) when a shortcut application is renamed, the Exe FullPath and executable name must be obtained.
// Unlike the rename event args, since we do not have a newPath, we iterate through all the programs and find the one with the same LnkResolved path.
2020-08-11 09:08:44 -07:00
private Programs . Win32Program GetAppWithSameLnkResolvedPath ( string lnkResolvedPath )
2020-07-17 22:32:21 -07:00
{
2020-08-11 09:08:44 -07:00
foreach ( Programs . Win32Program app in Items )
2020-07-17 22:32:21 -07:00
{
2020-10-30 16:43:09 -07:00
// Using Invariant / OrdinalIgnoreCase since we're comparing paths
if ( lnkResolvedPath . ToUpperInvariant ( ) . Equals ( app . LnkResolvedPath , StringComparison . OrdinalIgnoreCase ) )
2020-07-17 22:32:21 -07:00
{
return app ;
}
}
2020-08-17 10:00:56 -07:00
2020-07-17 22:32:21 -07:00
return null ;
}
private void OnAppCreated ( object sender , FileSystemEventArgs e )
{
string path = e . FullPath ;
2020-10-30 16:43:09 -07:00
// Using OrdinalIgnoreCase since we're comparing extensions
if ( ! Path . GetExtension ( path ) . Equals ( UrlExtension , StringComparison . OrdinalIgnoreCase ) & & ! Path . GetExtension ( path ) . Equals ( LnkExtension , StringComparison . OrdinalIgnoreCase ) )
2020-07-17 22:32:21 -07:00
{
2020-08-11 09:08:44 -07:00
Programs . Win32Program app = Programs . Win32Program . GetAppFromPath ( path ) ;
2020-07-22 10:58:01 -07:00
if ( app ! = null )
{
Add ( app ) ;
}
}
}
private void OnAppChanged ( object sender , FileSystemEventArgs e )
{
string path = e . FullPath ;
2020-10-30 16:43:09 -07:00
// Using OrdinalIgnoreCase since we're comparing extensions
if ( Path . GetExtension ( path ) . Equals ( UrlExtension , StringComparison . OrdinalIgnoreCase ) | | Path . GetExtension ( path ) . Equals ( LnkExtension , StringComparison . OrdinalIgnoreCase ) )
2020-07-22 10:58:01 -07:00
{
2020-09-25 10:36:38 -07:00
// 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.
commonEventHandlingQueue . Enqueue ( path ) ;
2020-07-17 22:32:21 -07:00
}
}
public void IndexPrograms ( )
{
2020-08-11 09:08:44 -07:00
var applications = Programs . Win32Program . All ( _settings ) ;
2021-06-03 16:11:09 +02:00
Log . Info ( $"Indexed {applications.Count} win32 applications" , GetType ( ) ) ;
2020-10-29 17:52:35 -07:00
SetList ( applications ) ;
2020-07-17 22:32:21 -07:00
}
2021-07-28 14:15:47 +03:00
public void Save ( )
{
_storage . Save ( Items ) ;
}
public void Load ( )
{
var items = _storage . TryLoad ( Array . Empty < Win32Program > ( ) ) ;
SetList ( items ) ;
}
2020-07-17 22:32:21 -07:00
}
}