예제 #1
0
파일: Portable.cs 프로젝트: SixGodZhang/Wox
        public void DisablePortableMode()
        {
            try
            {
                MoveUserDataFolder(DataLocation.PortableDataPath, DataLocation.RoamingDataPath);
#if DEBUG
                // Create shortcuts and uninstaller are not required in debug mode,
                // otherwise will repoint the path of the actual installed production version to the debug version
#else
                CreateShortcuts();
                CreateUninstallerEntry();
#endif
                IndicateDeletion(DataLocation.PortableDataPath);

                MessageBox.Show("Wox needs to restart to finish disabling portable mode, " +
                                "after the restart your portable data profile will be deleted and roaming data profile kept");

                UpdateManager.RestartApp();
            }
            catch (Exception e)
            {
#if !DEBUG
                Logger.WoxError("Error occured while disabling portable mode", e);
#endif
                throw;
            }
        }
예제 #2
0
파일: UWP.cs 프로젝트: ncheng8/Wox
        private void InitializeAppInfo()
        {
            var path = Path.Combine(Location, "AppxManifest.xml");

            try
            {
                var namespaces = XmlNamespaces(path);
                InitPackageVersion(namespaces);
            }
            catch (ArgumentException e)
            {
                Logger.WoxError(e.Message);
                Apps = Apps = new List <Application>().ToArray();
                return;
            }


            var        appxFactory = new AppxFactory();
            IStream    stream;
            const uint noAttribute = 0x80;
            // shared read will slow speed https://docs.microsoft.com/en-us/windows/win32/stg/stgm-constants
            // but cannot find a way to release stearm, so use shared read
            // exclusive read will cause exception during reinexing
            // System.IO.FileLoadException: The process cannot access the file because it is being used by another process
            const Stgm sharedRead = Stgm.Read | Stgm.ShareDenyNone;
            var        hResult    = SHCreateStreamOnFileEx(path, sharedRead, noAttribute, false, null, out stream);

            if (hResult == Hresult.Ok)
            {
                var reader       = appxFactory.CreateManifestReader(stream);
                var manifestApps = reader.GetApplications();
                var apps         = new List <Application>();
                while (manifestApps.GetHasCurrent() != 0)
                {
                    var manifestApp  = manifestApps.GetCurrent();
                    var appListEntry = manifestApp.GetStringValue("AppListEntry");
                    if (appListEntry != "none")
                    {
                        var app = new Application(manifestApp, this);
                        apps.Add(app);
                    }
                    manifestApps.MoveNext();
                }
                Apps = apps.Where(a => a.AppListEntry != "none").ToArray();
                return;
            }
            else
            {
                var e = Marshal.GetExceptionForHR((int)hResult);
                e.Data.Add(nameof(path), path);
                Logger.WoxError($"Cannot not get UWP details {path}", e);
                Apps = new List <Application>().ToArray();
                return;
            }
        }
예제 #3
0
파일: Win32.cs 프로젝트: ncheng8/Wox
 private static Win32 Win32Program(string path)
 {
     try
     {
         var p = new Win32
         {
             Name            = Path.GetFileNameWithoutExtension(path),
             IcoPath         = path,
             FullPath        = path,
             ParentDirectory = Directory.GetParent(path).FullName,
             Description     = string.Empty,
             Valid           = true,
             Enabled         = true
         };
         return(p);
     }
     catch (Exception e) when(e is SecurityException || e is UnauthorizedAccessException)
     {
         Logger.WoxError($"Permission denied {path}");
         return(new Win32()
         {
             Valid = false, Enabled = false
         });
     }
 }
예제 #4
0
        public static void Copy(this string sourcePath, string targetPath)
        {
            // Get the subdirectories for the specified directory.
            var dir = new DirectoryInfo(sourcePath);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                          "Source directory does not exist or could not be found: "
                          + sourcePath);
            }

            try
            {
                var dirs = dir.GetDirectories();
                // If the destination directory doesn't exist, create it.
                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                }

                // Get the files in the directory and copy them to the new location.
                var files = dir.GetFiles();
                foreach (var file in files)
                {
                    var path = Path.Combine(targetPath, file.Name);
                    file.CopyTo(path, false);
                }

                // Recursively copy subdirectories by calling itself on each subdirectory until there are no more to copy
                foreach (var subDirInfo in dirs)
                {
                    var path = Path.Combine(targetPath, subDirInfo.Name);
                    Copy(subDirInfo.FullName, path);
                }
            }
            catch (System.Exception e)
            {
                var message = $"Copying path {targetPath} has failed, it will now be deleted for consistency";
                Logger.WoxError(message, e);
                MessageBox.Show(message);
                RemoveFolderIfExists(targetPath);
            }
        }
예제 #5
0
파일: Main.cs 프로젝트: yongzhi444/Wox
        public List <Result> Query(Query query)
        {
            List <Result> results = new List <Result>();

            foreach (var item in controlPanelItems)
            {
                var titleMatch    = StringMatcher.FuzzySearch(query.Search, item.LocalizedString);
                var subTitleMatch = StringMatcher.FuzzySearch(query.Search, item.InfoTip);

                item.Score = Math.Max(titleMatch.Score, subTitleMatch.Score);
                if (item.Score > 0)
                {
                    var result = new Result
                    {
                        Title    = item.LocalizedString,
                        SubTitle = item.InfoTip,
                        Score    = item.Score,
                        IcoPath  = item.IconPath,
                        Action   = e =>
                        {
                            try
                            {
                                Process.Start(item.ExecutablePath);
                            }
                            catch (Exception ex)
                            {
                                ex.Data.Add(nameof(item.LocalizedString), item.LocalizedString);
                                ex.Data.Add(nameof(item.ExecutablePath), item.ExecutablePath);
                                ex.Data.Add(nameof(item.IconPath), item.IconPath);
                                ex.Data.Add(nameof(item.GUID), item.GUID);
                                Logger.WoxError($"cannot start control panel item {item.ExecutablePath}", ex);
                            }
                            return(true);
                        }
                    };

                    if (item.Score == titleMatch.Score)
                    {
                        result.TitleHighlightData = titleMatch.MatchData;
                    }
                    else
                    {
                        result.SubTitleHighlightData = subTitleMatch.MatchData;
                    }

                    results.Add(result);
                }
            }

            List <Result> panelItems = results.OrderByDescending(o => o.Score).Take(5).ToList();

            return(panelItems);
        }
        public static List <ControlPanelItem> Create()
        {
            RegistryKey             currentKey;
            ProcessStartInfo        executablePath;
            List <ControlPanelItem> controlPanelItems = new List <ControlPanelItem>();
            string localizedString;
            string infoTip;

            foreach (string guid in nameSpace.GetSubKeyNames())
            {
                try
                {
                    currentKey = clsid.OpenSubKey(guid);
                    if (currentKey != null)
                    {
                        executablePath = getExecutablePath(currentKey);

                        if (!(executablePath == null)) //Cannot have item without executable path
                        {
                            localizedString = getLocalizedString(currentKey);

                            if (!string.IsNullOrEmpty(localizedString))//Cannot have item without Title
                            {
                                infoTip = getInfoTip(currentKey);

                                string iconPath;
                                if (currentKey.OpenSubKey("DefaultIcon") != null && currentKey.OpenSubKey("DefaultIcon").GetValue(null) != null)
                                {
                                    iconPath = currentKey.OpenSubKey("DefaultIcon").GetValue(null).ToString();
                                }
                                else
                                {
                                    iconPath = Constant.ErrorIcon;
                                }
                                controlPanelItems.Add(new ControlPanelItem(localizedString, infoTip, guid, executablePath, iconPath));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    e.Data.Add(nameof(guid), guid);
                    Logger.WoxError($"cannot parse control panel item {guid}", e);
                    continue;
                }
            }

            return(controlPanelItems);
        }
예제 #7
0
 private void OnMouseDown(object sender, MouseButtonEventArgs e)
 {
     if (e.ChangedButton == MouseButton.Left)
     {
         try
         {
             DragMove();
         }
         catch (InvalidOperationException ex)
         {
             // https://github.com/Wox-launcher/Wox/issues/811
             Logger.WoxError($"Cannot dray {ex.Message}");
         }
     }
 }
예제 #8
0
        public T TryLoad(T defaultData)
        {
            if (File.Exists(FilePath))
            {
                if (new FileInfo(FilePath).Length == 0)
                {
                    Logger.WoxError($"Zero length cache file <{FilePath}>");
                    Save(defaultData);
                    return(defaultData);
                }

                using (var stream = new FileStream(FilePath, FileMode.Open))
                {
                    var d = Deserialize(stream, defaultData);
                    return(d);
                }
            }
            else
            {
                Logger.WoxInfo("Cache file not exist, load default data");
                Save(defaultData);
                return(defaultData);
            }
        }
예제 #9
0
        private void Deserialize(string searlized)
        {
            try
            {
                _data = JsonConvert.DeserializeObject <T>(searlized, _serializerSettings);
            }
            catch (JsonException e)
            {
                LoadDefault();
                Logger.WoxError($"Deserialize error for json <{FilePath}>", e);
            }

            if (_data == null)
            {
                LoadDefault();
            }
        }
예제 #10
0
        private void ExpirationCheck(object state)
        {
            try
            {
                DateTime now = DateTime.Now;
                Logger.WoxDebug($"ExpirationCheck start {now}");
                List <KeyValuePair <string, CacheEntry> > pairs = _cache.Where(pair => now > pair.Value.ExpiredDate).ToList();

                foreach (KeyValuePair <string, CacheEntry> pair in pairs)
                {
                    bool success = _cache.TryRemove(pair.Key, out CacheEntry entry);
                    Logger.WoxDebug($"remove expired: <{success}> entry: <{pair.Key}>");
                }
            }
            catch (Exception e)
            {
                e.Data.Add(nameof(state), state);
                Logger.WoxError($"error check image cache with state: {state}", e);
            }
        }
예제 #11
0
        public static Application[] All()
        {
            ConcurrentBag <Application> bag = new ConcurrentBag <Application>();

            Parallel.ForEach(PackageFoldersFromRegistry(), (package, state) =>
            {
                try
                {
                    package.InitializeAppInfo();
                    foreach (var a in package.Apps)
                    {
                        bag.Add(a);
                    }
                }
                catch (Exception e)
                {
                    e.Data.Add(nameof(package.FullName), package.FullName);
                    e.Data.Add(nameof(package.Location), package.Location);
                    Logger.WoxError($"Cannot parse UWP {package.Location}", e);
                }
            }
                             );
            return(bag.ToArray());
        }
예제 #12
0
파일: ImageLoader.cs 프로젝트: usanyken/Wox
        private static ImageSource LoadInternal(string path)
        {
            ImageSource image;

            if (string.IsNullOrEmpty(path))
            {
                image = GetErrorImage();
                return(image);
            }

            if (path.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
            {
                image = new BitmapImage(new Uri(path));
                image.Freeze();
                return(image);
            }

            if (!Path.IsPathRooted(path))
            {
                path = Path.Combine(Constant.ProgramDirectory, "Images", Path.GetFileName(path));
            }

            if (Directory.Exists(path))
            {
                // can be extended to support guid things
                ShellObject shell = ShellFile.FromParsingName(path);
                image = shell.Thumbnail.SmallBitmapSource;
                image.Freeze();
                return(image);
            }

            if (File.Exists(path))
            {
                try
                {
                    // https://stackoverflow.com/a/1751610/2833083
                    // https://stackoverflow.com/questions/21751747/extract-thumbnail-for-any-file-in-windows
                    // https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishellitemimagefactory-getimage
                    ShellFile shell = ShellFile.FromFilePath(path);
                    // https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Common/ShellThumbnail.cs#L333
                    // https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Common/DefaultShellImageSizes.cs#L46
                    // small is (32, 32)
                    image = shell.Thumbnail.SmallBitmapSource;
                    image.Freeze();
                    return(image);
                }
                catch (ShellException e1)
                {
                    try
                    {
                        // sometimes first try will throw exception, but second try will be ok.
                        // so we try twice
                        // Error while extracting thumbnail for C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Steam\\Steam.lnk
                        ShellFile shellFile = ShellFile.FromFilePath(path);
                        image = shellFile.Thumbnail.SmallBitmapSource;
                        image.Freeze();
                        return(image);
                    }
                    catch (System.Exception e2)
                    {
                        Logger.WoxError($"Failed to get thumbnail, first, {path}", e1);
                        Logger.WoxError($"Failed to get thumbnail, second, {path}", e2);
                        image = GetErrorImage();
                        return(image);
                    }
                }
            }
            else
            {
                image = GetErrorImage();
                return(image);
            }
        }
예제 #13
0
        private static ImageSource LoadInternal(string path)
        {
            Logger.WoxDebug($"load from disk {path}");

            ImageSource image;

            if (string.IsNullOrEmpty(path))
            {
                image = GetErrorImage();
                return(image);
            }


            string key = "EmbededIcon:";

            if (path.StartsWith(key))
            {
                return(EmbededIcon.GetImage(key, path, 32));
            }

            if (path.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    image = new BitmapImage(new Uri(path))
                    {
                        DecodePixelHeight = 32,
                        DecodePixelWidth  = 32
                    };
                }
                catch (Exception e)
                {
                    e.Data.Add(nameof(path), path);
                    Logger.WoxError($"cannot load {path}", e);
                    return(GetErrorImage());
                }
                image.Freeze();
                return(image);
            }

            bool normalImage = ImageExtensions.Any(e => path.EndsWith(e));

            if (!Path.IsPathRooted(path) && normalImage)
            {
                path = Path.Combine(Constant.ProgramDirectory, "Images", Path.GetFileName(path));
            }


            var parent1 = new DirectoryInfo(Constant.ProgramDirectory);
            var parent2 = new DirectoryInfo(DataLocation.DataDirectory());
            var subPath = new DirectoryInfo(path);

            Logger.WoxTrace($"{path} {subPath} {parent1} {parent2}");
            bool imageInsideWoxDirectory = IsSubdirectory(parent1, subPath) || IsSubdirectory(parent2, subPath);

            if (normalImage && imageInsideWoxDirectory)
            {
                try
                {
                    image = new BitmapImage(new Uri(path))
                    {
                        DecodePixelHeight = 32,
                        DecodePixelWidth  = 32
                    };
                }
                catch (Exception e)
                {
                    e.Data.Add(nameof(path), path);
                    Logger.WoxError($"cannot load {path}", e);
                    return(GetErrorImage());
                }
                image.Freeze();
                return(image);
            }

            if (Directory.Exists(path))
            {
                try
                {
                    // can be extended to support guid things
                    ShellObject shell = ShellFile.FromParsingName(path);
                    image = shell.Thumbnail.SmallBitmapSource;
                }
                catch (Exception e)
                {
                    e.Data.Add(nameof(path), path);
                    Logger.WoxError($"cannot load {path}", e);
                    return(GetErrorImage());
                }
                image.Freeze();
                return(image);
            }

            if (File.Exists(path))
            {
                try
                {
                    // https://stackoverflow.com/a/1751610/2833083
                    // https://stackoverflow.com/questions/21751747/extract-thumbnail-for-any-file-in-windows
                    // https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishellitemimagefactory-getimage
                    ShellFile shell = ShellFile.FromFilePath(path);
                    // https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Common/ShellThumbnail.cs#L333
                    // https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Common/DefaultShellImageSizes.cs#L46
                    // small is (32, 32)
                    image = shell.Thumbnail.SmallBitmapSource;
                    image.Freeze();
                    return(image);
                }
                catch (ShellException e1)
                {
                    try
                    {
                        // sometimes first try will throw exception, but second try will be ok.
                        // so we try twice
                        // Error while extracting thumbnail for C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Steam\\Steam.lnk
                        ShellFile shellFile = ShellFile.FromFilePath(path);
                        image = shellFile.Thumbnail.SmallBitmapSource;
                        image.Freeze();
                        return(image);
                    }
                    catch (System.Exception e2)
                    {
                        Logger.WoxError($"Failed to get thumbnail, first, {path}", e1);
                        Logger.WoxError($"Failed to get thumbnail, second, {path}", e2);
                        image = GetErrorImage();
                        return(image);
                    }
                }
            }
            else
            {
                image = GetErrorImage();
                return(image);
            }
        }