private static Win32Program ExeProgram(string path)
        {
            try
            {
                var program = CreateWin32Program(path);
                var info    = FileVersionInfoWrapper.GetVersionInfo(path);
                if (!string.IsNullOrEmpty(info?.FileDescription))
                {
                    program.Description = info.FileDescription;
                }

                return(program);
            }
            catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
            {
                ProgramLogger.Warn($"|Permission denied when trying to load the program from {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(InvalidProgram);
            }
            catch (FileNotFoundException e)
            {
                ProgramLogger.Warn($"|Unable to locate exe file at {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(InvalidProgram);
            }
            catch (Exception e)
            {
                ProgramLogger.Exception($"|An unexpected error occurred in the calling method ExeProgram at {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(InvalidProgram);
            }
        }
        private static Win32Program CreateWin32Program(string path)
        {
            try
            {
                return(new Win32Program
                {
                    Name = Path.GetFileNameWithoutExtension(path),
                    ExecutableName = Path.GetFileName(path),
                    IcoPath = path,

                    // Using InvariantCulture since this is user facing
                    FullPath = path.ToLowerInvariant(),
                    UniqueIdentifier = path,
                    ParentDirectory = Directory.GetParent(path).FullName,
                    Description = string.Empty,
                    Valid = true,
                    Enabled = true,
                    AppType = ApplicationType.Win32Application,
                });
            }
            catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
            {
                ProgramLogger.Warn($"|Permission denied when trying to load the program from {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(InvalidProgram);
            }
            catch (Exception e)
            {
                ProgramLogger.Exception($"|An unexpected error occurred in the calling method CreateWin32Program at {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(InvalidProgram);
            }
        }
Beispiel #3
0
        public static PackageWrapper GetWrapperFromPackage(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            string path;

            try
            {
                path = IsPackageDotInstallationPathAvailable.Value ? GetInstalledPath(package) : package.InstalledLocation.Path;
            }
            catch (Exception e) when(e is ArgumentException || e is FileNotFoundException || e is DirectoryNotFoundException)
            {
                ProgramLogger.Exception($"Exception {package.Id.Name}", e, MethodBase.GetCurrentMethod().DeclaringType, "Path could not be determined");
                return(new PackageWrapper(
                           package.Id.Name,
                           package.Id.FullName,
                           package.Id.FamilyName,
                           package.IsFramework,
                           package.IsDevelopmentMode,
                           string.Empty));
            }

            return(new PackageWrapper(
                       package.Id.Name,
                       package.Id.FullName,
                       package.Id.FamilyName,
                       package.IsFramework,
                       package.IsDevelopmentMode,
                       path));
        }
Beispiel #4
0
        private static Win32Program CreateWin32Program(string path)
        {
            try
            {
                var p = new Win32Program
                {
                    Name             = Path.GetFileNameWithoutExtension(path),
                    ExecutableName   = Path.GetFileName(path),
                    IcoPath          = path,
                    FullPath         = path.ToLower(CultureInfo.CurrentCulture),
                    UniqueIdentifier = path,
                    ParentDirectory  = Directory.GetParent(path).FullName,
                    Description      = string.Empty,
                    Valid            = true,
                    Enabled          = true,
                    AppType          = ApplicationType.Win32Application,
                };
                return(p);
            }
            catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
            {
                ProgramLogger.Exception($"|Permission denied when trying to load the program from {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(new Win32Program()
                {
                    Valid = false, Enabled = false
                });
            }
        }
        public void OnPackageInstalling(PackageCatalog p, PackageInstallingEventArgs args)
        {
            if (args.IsComplete)
            {
                try
                {
                    var packageWrapper = PackageWrapper.GetWrapperFromPackage(args.Package);
                    if (!string.IsNullOrEmpty(packageWrapper.InstalledLocation))
                    {
                        var uwp = new UWP(packageWrapper);
                        uwp.InitializeAppInfo(packageWrapper.InstalledLocation);
                        foreach (var app in uwp.Apps)
                        {
                            Add(app);
                        }
                    }
                }

                // InitializeAppInfo will throw if there is no AppxManifest.xml for the package.
                // Note there are sometimes multiple packages per product and this doesn't necessarily mean that we haven't found the app.
                // eg. "Could not find file 'C:\\Program Files\\WindowsApps\\Microsoft.WindowsTerminalPreview_2020.616.45.0_neutral_~_8wekyb3d8bbwe\\AppxManifest.xml'."
                catch (System.IO.FileNotFoundException e)
                {
                    ProgramLogger.Exception(e.Message, e, GetType(), args.Package.InstalledLocation.ToString());
                }
            }
        }
        private static Win32Program LnkProgram(string path)
        {
            try
            {
                var    program = CreateWin32Program(path);
                string target  = ShellLinkHelper.RetrieveTargetPath(path);

                if (!string.IsNullOrEmpty(target))
                {
                    if (!(File.Exists(target) || Directory.Exists(target)))
                    {
                        // If the link points nowhere, consider it invalid.
                        return(InvalidProgram);
                    }

                    program.LnkResolvedPath           = program.FullPath;
                    program.LnkResolvedExecutableName = Path.GetFileName(target);

                    // Using CurrentCulture since this is user facing
                    program.FullPath = Path.GetFullPath(target).ToLowerInvariant();

                    program.Arguments = ShellLinkHelper.Arguments;

                    // A .lnk could be a (Chrome) PWA, set correct AppType
                    program.AppType = program.IsWebApplication()
                        ? ApplicationType.WebApplication
                        : GetAppTypeFromPath(target);

                    var description = ShellLinkHelper.Description;
                    if (!string.IsNullOrEmpty(description))
                    {
                        program.Description = description;
                    }
                    else
                    {
                        var info = FileVersionInfoWrapper.GetVersionInfo(target);
                        if (!string.IsNullOrEmpty(info?.FileDescription))
                        {
                            program.Description = info.FileDescription;
                        }
                    }
                }

                return(program);
            }
            catch (System.IO.FileLoadException e)
            {
                ProgramLogger.Warn($"Couldn't load the link file at {path}. This might be caused by a new link being created and locked by the OS.", e, MethodBase.GetCurrentMethod().DeclaringType, path);
                return(InvalidProgram);
            }

            // Only do a catch all in production. This is so make developer aware of any unhandled exception and add the exception handling in.
            // Error caused likely due to trying to get the description of the program
            catch (Exception e)
            {
                ProgramLogger.Exception($"|An unexpected error occurred in the calling method LnkProgram at {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(InvalidProgram);
            }
        }
Beispiel #7
0
        private static string GetProgramPathFromRegistrySubKeys(RegistryKey root, string subkey)
        {
            var path = string.Empty;

            try
            {
                using (var key = root.OpenSubKey(subkey))
                {
                    if (key == null)
                    {
                        return(string.Empty);
                    }

                    var defaultValue = string.Empty;
                    path = key.GetValue(defaultValue) as string;
                }

                if (string.IsNullOrEmpty(path))
                {
                    return(string.Empty);
                }

                // fix path like this: ""\"C:\\folder\\executable.exe\""
                return(path = path.Trim('"', ' '));
            }
            catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
            {
                ProgramLogger.Exception($"|Permission denied when trying to load the program from {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(string.Empty);
            }
        }
        public string RetrieveTargetPath(string path)
        {
            var       link      = new ShellLink();
            const int STGM_READ = 0;

            try
            {
                ((IPersistFile)link).Load(path, STGM_READ);
            }
            catch (System.IO.FileNotFoundException ex)
            {
                ProgramLogger.Exception("Path could not be retrieved", ex, GetType(), path);
                return(string.Empty);
            }

            var hwnd = default(_RemotableHandle);

            ((IShellLinkW)link).Resolve(ref hwnd, 0);

            const int     MAX_PATH = 260;
            StringBuilder buffer   = new StringBuilder(MAX_PATH);

            var data = default(WIN32_FIND_DATAW);

            ((IShellLinkW)link).GetPath(buffer, buffer.Capacity, ref data, SLGP_FLAGS.SLGP_SHORTPATH);
            var target = buffer.ToString();

            // To set the app description
            if (!string.IsNullOrEmpty(target))
            {
                buffer = new StringBuilder(MAX_PATH);
                try
                {
                    ((IShellLinkW)link).GetDescription(buffer, MAX_PATH);
                    Description = buffer.ToString();
                }
                catch (Exception e)
                {
                    Log.Exception($"|Failed to fetch description for {target}, {e.Message}", e, GetType());
                    Description = string.Empty;
                }

                StringBuilder argumentBuffer = new StringBuilder(MAX_PATH);
                ((IShellLinkW)link).GetArguments(argumentBuffer, argumentBuffer.Capacity);
                Arguments = argumentBuffer.ToString();

                // Set variable to true if the program takes in any arguments
                if (argumentBuffer.Length != 0)
                {
                    HasArguments = true;
                }
            }

            // To release unmanaged memory
            Marshal.ReleaseComObject(link);

            return(target);
        }
Beispiel #9
0
        private static IEnumerable <string> ProgramPaths(string directory, IList <string> suffixes, bool recursiveSearch = true)
        {
            if (!Directory.Exists(directory))
            {
                return(Array.Empty <string>());
            }

            var files       = new List <string>();
            var folderQueue = new Queue <string>();

            folderQueue.Enqueue(directory);

            do
            {
                var currentDirectory = folderQueue.Dequeue();
                try
                {
                    foreach (var suffix in suffixes)
                    {
                        try
                        {
                            files.AddRange(Directory.EnumerateFiles(currentDirectory, $"*.{suffix}", SearchOption.TopDirectoryOnly));
                        }
                        catch (DirectoryNotFoundException e)
                        {
                            ProgramLogger.Exception("|The directory trying to load the program from does not exist", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory);
                        }
                    }
                }
                catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
                {
                    ProgramLogger.Exception($"|Permission denied when trying to load programs from {currentDirectory}", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory);
                }

                try
                {
                    // If the search is set to be non-recursive, then do not enqueue the child directories.
                    if (!recursiveSearch)
                    {
                        continue;
                    }

                    foreach (var childDirectory in Directory.EnumerateDirectories(currentDirectory, "*", SearchOption.TopDirectoryOnly))
                    {
                        folderQueue.Enqueue(childDirectory);
                    }
                }
                catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
                {
                    ProgramLogger.Exception($"|Permission denied when trying to load programs from {currentDirectory}", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory);
                }
            }while (folderQueue.Any());

            return(files);
        }
Beispiel #10
0
        private void InitPackageVersion(string[] namespaces)
        {
            foreach (var n in _versionFromNamespace.Keys.Where(namespaces.Contains))
            {
                Version = _versionFromNamespace[n];
                return;
            }

            ProgramLogger.Exception($"|Trying to get the package version of the UWP program, but a unknown UWP appmanifest version {FullName} from location {Location} is returned.", new FormatException(), GetType(), Location);

            Version = PackageVersion.Unknown;
        }
Beispiel #11
0
        private static Win32Program LnkProgram(string path)
        {
            try
            {
                var           program  = CreateWin32Program(path);
                const int     MAX_PATH = 260;
                StringBuilder buffer   = new StringBuilder(MAX_PATH);

                string target = Helper.RetrieveTargetPath(path);

                if (!string.IsNullOrEmpty(target))
                {
                    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);

                        var description = Helper.Description;
                        if (!string.IsNullOrEmpty(description))
                        {
                            program.Description = description;
                        }
                        else
                        {
                            var info = FileVersionInfoWrapper.GetVersionInfo(target);
                            if (!string.IsNullOrEmpty(info?.FileDescription))
                            {
                                program.Description = info.FileDescription;
                            }
                        }
                    }
                }

                return(program);
            }

            // Only do a catch all in production. This is so make developer aware of any unhandled exception and add the exception handling in.
            // Error caused likely due to trying to get the description of the program
            catch (Exception e)
            {
                ProgramLogger.Exception($"|An unexpected error occurred in the calling method LnkProgram at {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(new Win32Program()
                {
                    Valid = false, Enabled = false
                });
            }
        }
Beispiel #12
0
        internal void LogoPathFromUri(string uri, Theme theme)
        {
            // all https://msdn.microsoft.com/windows/uwp/controls-and-patterns/tiles-and-notifications-app-assets
            // windows 10 https://msdn.microsoft.com/en-us/library/windows/apps/dn934817.aspx
            // windows 8.1 https://msdn.microsoft.com/en-us/library/windows/apps/hh965372.aspx#target_size
            // 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);
            }
            else
            {
                // for C:\Windows\MiracastView etc
                path = Path.Combine(Package.Location, "Assets", uri);
            }

            switch (theme)
            {
            case Theme.HighContrastBlack:
            case Theme.HighContrastOne:
            case Theme.HighContrastTwo:
                isLogoUriSet = SetHighContrastIcon(path, ContrastBlack);
                break;

            case Theme.HighContrastWhite:
                isLogoUriSet = SetHighContrastIcon(path, ContrastWhite);
                break;

            case Theme.Light:
                isLogoUriSet = SetColoredIcon(path, ContrastWhite);
                break;

            default:
                isLogoUriSet = SetColoredIcon(path, ContrastBlack);
                break;
            }

            if (!isLogoUriSet)
            {
                LogoPath = string.Empty;
                LogoType = LogoType.Error;
                ProgramLogger.Exception($"|{UserModelId} can't find logo uri for {uri} in package location: {Package.Location}", new FileNotFoundException(), GetType(), Package.Location);
            }
        }
Beispiel #13
0
        public void InitializeAppInfo(string installedLocation)
        {
            Location = installedLocation;
            var path = Path.Combine(installedLocation, "AppxManifest.xml");

            var namespaces = XmlNamespaces(path);

            InitPackageVersion(namespaces);

            const uint noAttribute   = 0x80;
            const Stgm exclusiveRead = Stgm.Read;
            var        hResult       = NativeMethods.SHCreateStreamOnFileEx(path, exclusiveRead, noAttribute, false, null, out IStream stream);

            if (hResult == Hresult.Ok)
            {
                var apps = new List <UWPApplication>();

                List <IAppxManifestApplication> appsViaManifests = AppxPackageHelper.GetAppsFromManifest(stream);
                foreach (var appInManifest in appsViaManifests)
                {
                    var app = new UWPApplication(appInManifest, this);
                    apps.Add(app);
                }

                Apps = apps.Where(a =>
                {
                    var valid =
                        !string.IsNullOrEmpty(a.UserModelId) &&
                        !string.IsNullOrEmpty(a.DisplayName) &&
                        a.AppListEntry != "none";

                    return(valid);
                }).ToArray();

                if (Marshal.ReleaseComObject(stream) > 0)
                {
                    Log.Error("AppxManifest.xml was leaked", MethodBase.GetCurrentMethod().DeclaringType);
                }
            }
            else
            {
                var e = Marshal.GetExceptionForHR((int)hResult);
                ProgramLogger.Exception("Error caused while trying to get the details of the UWP program", e, GetType(), path);

                Apps = new List <UWPApplication>().ToArray();
            }
        }
Beispiel #14
0
        public static Win32Program[] All(ProgramPluginSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            try
            {
                var programs = new List <Win32Program>().AsParallel();

                var unregistered = UnregisteredPrograms(settings.ProgramSources, settings.ProgramSuffixes);
                programs = programs.Concat(unregistered);

                if (settings.EnableRegistrySource)
                {
                    var appPaths = AppPathsPrograms(settings.ProgramSuffixes);
                    programs = programs.Concat(appPaths);
                }

                if (settings.EnableStartMenuSource)
                {
                    var startMenu = StartMenuPrograms(settings.ProgramSuffixes);
                    programs = programs.Concat(startMenu);
                }

                if (settings.EnablePathEnvironmentVariableSource)
                {
                    var appPathEnvironment = PathEnvironmentPrograms(settings.ProgramSuffixes);
                    programs = programs.Concat(appPathEnvironment);
                }

                if (settings.EnableDesktopSource)
                {
                    var desktop = DesktopPrograms(settings.ProgramSuffixes);
                    programs = programs.Concat(desktop);
                }

                return(DeduplicatePrograms(programs));
            }
            catch (Exception e)
            {
                ProgramLogger.Exception("An unexpected error occurred", e, MethodBase.GetCurrentMethod().DeclaringType, "Not available");

                return(Array.Empty <Win32Program>());
            }
        }
Beispiel #15
0
 private static IEnumerable <IPackage> CurrentUserPackages()
 {
     return(PackageManagerWrapper.FindPackagesForCurrentUser().Where(p =>
     {
         try
         {
             var f = p.IsFramework;
             var path = p.InstalledLocation;
             return !f && !string.IsNullOrEmpty(path);
         }
         catch (Exception e)
         {
             ProgramLogger.Exception("An unexpected error occurred and unable to verify if package is valid", e, MethodBase.GetCurrentMethod().DeclaringType, "id");
             return false;
         }
     }));
 }
Beispiel #16
0
 private async void Launch(IPublicAPI api, string queryArguments)
 {
     var appManager = new ApplicationActivationHelper.ApplicationActivationManager();
     const ApplicationActivationHelper.ActivateOptions noFlags = ApplicationActivationHelper.ActivateOptions.None;
     await Task.Run(() =>
     {
         try
         {
             appManager.ActivateApplication(UserModelId, queryArguments, noFlags, out var unusedPid);
         }
         catch (Exception ex)
         {
             ProgramLogger.Exception($"Unable to launch UWP {DisplayName}", ex, MethodBase.GetCurrentMethod().DeclaringType, queryArguments);
             var name    = "Plugin: " + Properties.Resources.wox_plugin_program_plugin_name;
             var message = $"{Properties.Resources.powertoys_run_plugin_program_uwp_failed}: {DisplayName}";
             api.ShowMsg(name, message, string.Empty);
         }
     }).ConfigureAwait(false);
 }
Beispiel #17
0
        private BitmapImage ImageFromPath(string path)
        {
            if (File.Exists(path))
            {
                MemoryStream memoryStream = new MemoryStream();

                byte[] fileBytes = File.ReadAllBytes(path);
                memoryStream.Write(fileBytes, 0, fileBytes.Length);
                memoryStream.Position = 0;

                var image = new BitmapImage();
                image.BeginInit();
                image.StreamSource = memoryStream;
                image.EndInit();
                return(image);
            }
            else
            {
                ProgramLogger.Exception($"Unable to get logo for {UserModelId} from {path} and located in {Package.Location}", new FileNotFoundException(), GetType(), path);
                return(new BitmapImage(new Uri(ImageLoader.ErrorIconPath)));
            }
        }
Beispiel #18
0
        private void InitPackageVersion(string[] namespaces)
        {
            var versionFromNamespace = new Dictionary <string, PackageVersion>
            {
                { "http://schemas.microsoft.com/appx/manifest/foundation/windows10", PackageVersion.Windows10 },
                { "http://schemas.microsoft.com/appx/2013/manifest", PackageVersion.Windows81 },
                { "http://schemas.microsoft.com/appx/2010/manifest", PackageVersion.Windows8 },
            };

            foreach (var n in versionFromNamespace.Keys)
            {
                if (namespaces.Contains(n))
                {
                    Version = versionFromNamespace[n];
                    return;
                }
            }

            ProgramLogger.Exception($"|Trying to get the package version of the UWP program, but a unknown UWP appmanifest version {FullName} from location {Location} is returned.", new FormatException(), GetType(), Location);

            Version = PackageVersion.Unknown;
        }
Beispiel #19
0
        private bool IfApplicationcanRunElevated()
        {
            if (EntryPoint == "Windows.FullTrustApplication")
            {
                return(true);
            }
            else
            {
                var manifest = Package.Location + "\\AppxManifest.xml";
                if (File.Exists(manifest))
                {
                    try
                    {
                        // Check the manifest to verify if the Trust Level for the application is "mediumIL"
                        var file   = File.ReadAllText(manifest);
                        var xmlDoc = new XmlDocument();
                        xmlDoc.LoadXml(file);
                        var xmlRoot          = xmlDoc.DocumentElement;
                        var namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
                        namespaceManager.AddNamespace("uap10", "http://schemas.microsoft.com/appx/manifest/uap/windows10/10");
                        var trustLevelNode = xmlRoot.SelectSingleNode("//*[local-name()='Application' and @uap10:TrustLevel]", namespaceManager); // According to https://docs.microsoft.com/en-us/windows/apps/desktop/modernize/grant-identity-to-nonpackaged-apps#create-a-package-manifest-for-the-sparse-package and https://docs.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-application#attributes

                        if (trustLevelNode?.Attributes["uap10:TrustLevel"]?.Value == "mediumIL")
                        {
                            return(true);
                        }
                    }
#pragma warning disable CA1031 // Do not catch general exception types
                    catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
                    {
                        ProgramLogger.Exception($"Unable to parse manifest file for {DisplayName}", e, MethodBase.GetCurrentMethod().DeclaringType, manifest);
                    }
                }
            }

            return(false);
        }
Beispiel #20
0
        private BitmapImage ImageFromPath(string path)
        {
            if (File.Exists(path))
            {
                var memoryStream = new MemoryStream();
                using (var fileStream = File.OpenRead(path))
                {
                    fileStream.CopyTo(memoryStream);
                    memoryStream.Position = 0;

                    var image = new BitmapImage();
                    image.BeginInit();
                    image.StreamSource = memoryStream;
                    image.EndInit();
                    return(image);
                }
            }
            else
            {
                ProgramLogger.Exception($"Unable to get logo for {UserModelId} from {path} and located in {Package.Location}", new FileNotFoundException(), GetType(), path);
                return(new BitmapImage(new Uri(ImageLoader.ErrorIconPath)));
            }
        }
Beispiel #21
0
        public static UWPApplication[] All()
        {
            var windows10 = new Version(10, 0);
            var support   = Environment.OSVersion.Version.Major >= windows10.Major;

            if (support)
            {
                var applications = CurrentUserPackages().AsParallel().SelectMany(p =>
                {
                    UWP u;
                    try
                    {
                        u = new UWP(p);
                        u.InitializeAppInfo(p.InstalledLocation);
                    }
                    catch (Exception e)
                    {
                        ProgramLogger.Exception($"Unable to convert Package to UWP for {p.FullName}", e, MethodBase.GetCurrentMethod().DeclaringType, p.InstalledLocation);

                        return(Array.Empty <UWPApplication>());
                    }

                    return(u.Apps);
                }).ToArray();

                var updatedListWithoutDisabledApps = applications
                                                     .Where(t1 => !Main.Settings.DisabledProgramSources
                                                            .Any(x => x.UniqueIdentifier == t1.UniqueIdentifier))
                                                     .Select(x => x);

                return(updatedListWithoutDisabledApps.ToArray());
            }
            else
            {
                return(Array.Empty <UWPApplication>());
            }
        }
Beispiel #22
0
        private static Win32Program InternetShortcutProgram(string path)
        {
            try
            {
                string[] lines    = FileWrapper.ReadAllLines(path);
                string   iconPath = string.Empty;
                string   urlPath  = string.Empty;
                bool     validApp = false;

                Regex internetShortcutURLPrefixes = new Regex(@"^steam:\/\/(rungameid|run)\/|^com\.epicgames\.launcher:\/\/apps\/");

                const string urlPrefix      = "URL=";
                const string iconFilePrefix = "IconFile=";

                foreach (string line in lines)
                {
                    // Using OrdinalIgnoreCase since this is used internally
                    if (line.StartsWith(urlPrefix, StringComparison.OrdinalIgnoreCase))
                    {
                        urlPath = line.Substring(urlPrefix.Length);

                        try
                        {
                            Uri uri = new Uri(urlPath);
                        }
                        catch (UriFormatException e)
                        {
                            // To catch the exception if the uri cannot be parsed.
                            // Link to watson crash: https://watsonportal.microsoft.com/Failure?FailureSearchText=5f871ea7-e886-911f-1b31-131f63f6655b
                            ProgramLogger.Exception($"url could not be parsed", e, MethodBase.GetCurrentMethod().DeclaringType, urlPath);
                            return(new Win32Program()
                            {
                                Valid = false, Enabled = false
                            });
                        }

                        // To filter out only those steam shortcuts which have 'run' or 'rungameid' as the hostname
                        if (internetShortcutURLPrefixes.Match(urlPath).Success)
                        {
                            validApp = true;
                        }
                    }

                    // Using OrdinalIgnoreCase since this is used internally
                    if (line.StartsWith(iconFilePrefix, StringComparison.OrdinalIgnoreCase))
                    {
                        iconPath = line.Substring(iconFilePrefix.Length);
                    }
                }

                if (!validApp)
                {
                    return(new Win32Program()
                    {
                        Valid = false, Enabled = false
                    });
                }

                try
                {
                    var p = new Win32Program
                    {
                        Name             = Path.GetFileNameWithoutExtension(path),
                        ExecutableName   = Path.GetFileName(path),
                        IcoPath          = iconPath,
                        FullPath         = urlPath,
                        UniqueIdentifier = path,
                        ParentDirectory  = Directory.GetParent(path).FullName,
                        Valid            = true,
                        Enabled          = true,
                        AppType          = ApplicationType.InternetShortcutApplication,
                    };
                    return(p);
                }
                catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
                {
                    ProgramLogger.Exception($"|Permission denied when trying to load the program from {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                    return(new Win32Program()
                    {
                        Valid = false, Enabled = false
                    });
                }
            }
            catch (Exception e)
            {
                ProgramLogger.Exception($"|An unexpected error occurred in the calling method InternetShortcutProgram at {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(new Win32Program()
                {
                    Valid = false, Enabled = false
                });
            }
        }
Beispiel #23
0
        private static Win32Program InternetShortcutProgram(string path)
        {
            try
            {
                // We don't want to read the whole file if we don't need to
                var    lines    = FileWrapper.ReadLines(path);
                string iconPath = string.Empty;
                string urlPath  = string.Empty;
                bool   validApp = false;

                const string urlPrefix      = "URL=";
                const string iconFilePrefix = "IconFile=";

                foreach (string line in lines)
                {
                    // Using OrdinalIgnoreCase since this is used internally
                    if (line.StartsWith(urlPrefix, StringComparison.OrdinalIgnoreCase))
                    {
                        urlPath = line.Substring(urlPrefix.Length);

                        if (!Uri.TryCreate(urlPath, UriKind.RelativeOrAbsolute, out Uri _))
                        {
                            ProgramLogger.Warn("url could not be parsed", null, MethodBase.GetCurrentMethod().DeclaringType, urlPath);
                            return(InvalidProgram);
                        }

                        // To filter out only those steam shortcuts which have 'run' or 'rungameid' as the hostname
                        if (InternetShortcutURLPrefixes.Match(urlPath).Success)
                        {
                            validApp = true;
                        }
                    }
                    else if (line.StartsWith(iconFilePrefix, StringComparison.OrdinalIgnoreCase))
                    {
                        iconPath = line.Substring(iconFilePrefix.Length);
                    }

                    // If we resolved an urlPath & and an iconPath quit reading the file
                    if (!string.IsNullOrEmpty(urlPath) && !string.IsNullOrEmpty(iconPath))
                    {
                        break;
                    }
                }

                if (!validApp)
                {
                    return(InvalidProgram);
                }

                try
                {
                    return(new Win32Program
                    {
                        Name = Path.GetFileNameWithoutExtension(path),
                        ExecutableName = Path.GetFileName(path),
                        IcoPath = iconPath,
                        FullPath = urlPath.ToLowerInvariant(),
                        UniqueIdentifier = path,
                        ParentDirectory = Directory.GetParent(path).FullName,
                        Valid = true,
                        Enabled = true,
                        AppType = ApplicationType.InternetShortcutApplication,
                    });
                }
                catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
                {
                    ProgramLogger.Warn($"|Permission denied when trying to load the program from {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                    return(InvalidProgram);
                }
            }
            catch (Exception e)
            {
                ProgramLogger.Exception($"|An unexpected error occurred in the calling method InternetShortcutProgram at {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path);

                return(InvalidProgram);
            }
        }
Beispiel #24
0
        private ImageSource PlatedImage(BitmapImage image)
        {
            if (!string.IsNullOrEmpty(BackgroundColor))
            {
                string currentBackgroundColor;
                if (BackgroundColor == "transparent")
                {
                    // Using InvariantCulture since this is internal
                    currentBackgroundColor = SystemParameters.WindowGlassBrush.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    currentBackgroundColor = BackgroundColor;
                }

                var padding = 8;
                var width   = image.Width + (2 * padding);
                var height  = image.Height + (2 * padding);
                var x       = 0;
                var y       = 0;

                var group     = new DrawingGroup();
                var converted = ColorConverter.ConvertFromString(currentBackgroundColor);
                if (converted != null)
                {
                    var color             = (Color)converted;
                    var brush             = new SolidColorBrush(color);
                    var pen               = new Pen(brush, 1);
                    var backgroundArea    = new Rect(0, 0, width, height);
                    var rectangleGeometry = new RectangleGeometry(backgroundArea);
                    var rectDrawing       = new GeometryDrawing(brush, pen, rectangleGeometry);
                    group.Children.Add(rectDrawing);

                    var imageArea    = new Rect(x + padding, y + padding, image.Width, image.Height);
                    var imageDrawing = new ImageDrawing(image, imageArea);
                    group.Children.Add(imageDrawing);

                    // http://stackoverflow.com/questions/6676072/get-system-drawing-bitmap-of-a-wpf-area-using-visualbrush
                    var visual  = new DrawingVisual();
                    var context = visual.RenderOpen();
                    context.DrawDrawing(group);
                    context.Close();

                    var bitmap = new RenderTargetBitmap(
                        Convert.ToInt32(width),
                        Convert.ToInt32(height),
                        _dpiScale100,
                        _dpiScale100,
                        PixelFormats.Pbgra32);

                    bitmap.Render(visual);

                    return(bitmap);
                }
                else
                {
                    ProgramLogger.Exception($"Unable to convert background string {BackgroundColor} to color for {Package.Location}", new InvalidOperationException(), GetType(), Package.Location);

                    return(new BitmapImage(new Uri(Constant.ErrorIcon)));
                }
            }
            else
            {
                // todo use windows theme as background
                return(image);
            }
        }
Beispiel #25
0
        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;
                }
                else if (key.StartsWith("/", StringComparison.Ordinal))
                {
                    parsed = prefix + "//" + key;
                }
                else if (key.Contains("resources", StringComparison.OrdinalIgnoreCase))
                {
                    parsed = prefix + key;
                }
                else
                {
                    parsed = prefix + "///resources/" + key;
                }

                var    outBuffer = new StringBuilder(128);
                string source    = $"@{{{packageFullName}? {parsed}}}";
                var    capacity  = (uint)outBuffer.Capacity;
                var    hResult   = NativeMethods.SHLoadIndirectString(source, outBuffer, capacity, IntPtr.Zero);
                if (hResult == Hresult.Ok)
                {
                    var loaded = outBuffer.ToString();
                    if (!string.IsNullOrEmpty(loaded))
                    {
                        return(loaded);
                    }
                    else
                    {
                        ProgramLogger.Exception($"Can't load null or empty result pri {source} in uwp location {Package.Location}", new NullReferenceException(), GetType(), Package.Location);

                        return(string.Empty);
                    }
                }
                else
                {
                    // https://github.com/Wox-launcher/Wox/issues/964
                    // known hresult 2147942522:
                    // 'Microsoft Corporation' violates pattern constraint of '\bms-resource:.{1,256}'.
                    // for
                    // Microsoft.MicrosoftOfficeHub_17.7608.23501.0_x64__8wekyb3d8bbwe: ms-resource://Microsoft.MicrosoftOfficeHub/officehubintl/AppManifest_GetOffice_Description
                    // Microsoft.BingFoodAndDrink_3.0.4.336_x64__8wekyb3d8bbwe: ms-resource:AppDescription
                    var e = Marshal.GetExceptionForHR((int)hResult);
                    ProgramLogger.Exception($"Load pri failed {source} with HResult {hResult} and location {Package.Location}", e, GetType(), Package.Location);

                    return(string.Empty);
                }
            }
            else
            {
                return(resourceReference);
            }
        }
Beispiel #26
0
        private static IEnumerable <string> ProgramPaths(string directory, IList <string> suffixes, bool recursiveSearch = true)
        {
            if (!Directory.Exists(directory))
            {
                return(Array.Empty <string>());
            }

            var files       = new List <string>();
            var folderQueue = new Queue <string>();

            folderQueue.Enqueue(directory);

            // Keep track of already visited directories to avoid cycles.
            var alreadyVisited = new HashSet <string>();

            do
            {
                var currentDirectory = folderQueue.Dequeue();

                if (alreadyVisited.Contains(currentDirectory))
                {
                    continue;
                }

                alreadyVisited.Add(currentDirectory);

                try
                {
                    foreach (var suffix in suffixes)
                    {
                        try
                        {
                            files.AddRange(Directory.EnumerateFiles(currentDirectory, $"*.{suffix}", SearchOption.TopDirectoryOnly));
                        }
                        catch (DirectoryNotFoundException e)
                        {
                            ProgramLogger.Warn("|The directory trying to load the program from does not exist", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory);
                        }
                    }
                }
                catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
                {
                    ProgramLogger.Warn($"|Permission denied when trying to load programs from {currentDirectory}", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory);
                }
                catch (Exception e)
                {
                    ProgramLogger.Exception($"|An unexpected error occurred in the calling method ProgramPaths at {currentDirectory}", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory);
                }

                try
                {
                    // If the search is set to be non-recursive, then do not enqueue the child directories.
                    if (!recursiveSearch)
                    {
                        continue;
                    }

                    foreach (var childDirectory in Directory.EnumerateDirectories(currentDirectory, "*", new EnumerationOptions()
                    {
                        // https://docs.microsoft.com/en-us/dotnet/api/system.io.enumerationoptions?view=net-6.0
                        // Exclude directories with the Reparse Point file attribute, to avoid loops due to symbolic links / directory junction / mount points.
                        AttributesToSkip = FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint,
                        RecurseSubdirectories = false,
                    }))
                    {
                        folderQueue.Enqueue(childDirectory);
                    }
                }
                catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
                {
                    ProgramLogger.Warn($"|Permission denied when trying to load programs from {currentDirectory}", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory);
                }
                catch (Exception e)
                {
                    ProgramLogger.Exception($"|An unexpected error occurred in the calling method ProgramPaths at {currentDirectory}", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory);
                }
            }while (folderQueue.Count > 0);

            return(files);
        }