Esempio n. 1
0
File: Main.cs Progetto: xiaoqz/Wox
        public static void IndexPrograms()
        {
            var a = Task.Run(() =>
            {
                Logger.StopWatchNormal("Win32 index cost", IndexWin32Programs);
            });

            var b = Task.Run(() =>
            {
                Logger.StopWatchNormal("UWP index cost", IndexUWPPrograms);
            });

            Task.WaitAll(a, b);

            Logger.WoxInfo($"Number of indexed win32 programs <{_win32s.Length}>");
            foreach (var win32 in _win32s)
            {
                Logger.WoxDebug($" win32: <{win32.Name}> <{win32.ExecutableName}> <{win32.FullPath}>");
            }
            Logger.WoxInfo($"Number of indexed uwps <{_uwps.Length}>");
            foreach (var uwp in _uwps)
            {
                Logger.WoxDebug($" uwp: <{uwp.DisplayName}> <{uwp.UserModelId}>");
            }
            _settings.LastIndexTime = DateTime.Today;
        }
Esempio n. 2
0
        public static ImageSource Load(string path)
        {
            Logger.WoxDebug($"load begin {path}");
            var img = LoadInternal(path);

            Logger.WoxDebug($"load end {path}");
            return(img);
        }
Esempio n. 3
0
        private void ExpirationCheck(object state)
        {
            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}>");
            }
        }
Esempio n. 4
0
        public static async Task <string> Get([NotNull] string url, string encoding = "UTF-8")
        {
            Logger.WoxDebug($"Url <{url}>");
            var request = WebRequest.CreateHttp(url);

            request.Method    = "GET";
            request.Timeout   = 1000;
            request.Proxy     = WebProxy();
            request.UserAgent = UserAgent;
            var response = await request.GetResponseAsync() as HttpWebResponse;

            response = response.NonNull();
            var stream = response.GetResponseStream().NonNull();

            using (var reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
            {
                var content = await reader.ReadToEndAsync();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(content);
                }
                else
                {
                    throw new HttpRequestException($"Error code <{response.StatusCode}> with content <{content}> returned from <{url}>");
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// This stopwatch will appear only in Debug mode
        /// </summary>
        public static long StopWatchDebug(this NLog.Logger logger, string message, Action action, [CallerMemberName] string methodName = "")
        {
            var stopWatch = new System.Diagnostics.Stopwatch();

            stopWatch.Start();
            action();
            stopWatch.Stop();
            var    milliseconds = stopWatch.ElapsedMilliseconds;
            string info         = $"{message} <{milliseconds}ms>";

            logger.WoxDebug(info, methodName);
            return(milliseconds);
        }
        public ImageCache()
        {
            _cache       = new ConcurrentDictionary <string, CacheEntry>();
            _cacheSorted = new SortedSet <CacheEntry>(new CacheEntryComparer());
            _cacheQueue  = new BlockingCollection <CacheEntry>();
            _updateQueue = new BlockingCollection <UpdateCallbackEntry>();

            timer = new System.Threading.Timer(ExpirationCheck, null, _checkInterval, _checkInterval);
            Task.Run(() =>
            {
                while (true)
                {
                    CacheEntry entry = _cacheQueue.Take();
                    int currentCount = _cache.Count;
                    if (currentCount > _cacheLimit)
                    {
                        CacheEntry min = _cacheSorted.Min;
                        _cacheSorted.Remove(min);
                        bool removeResult = _cache.TryRemove(min.Key, out _);
                        Logger.WoxDebug($"remove exceed: <{removeResult}> entry: <{min.Key}>");
                    }
                    else
                    {
                        _cacheSorted.Remove(entry);
                    }
                    _cacheSorted.Add(entry);
                }
            }).ContinueWith(ErrorReporting.UnhandledExceptionHandleTask, TaskContinuationOptions.OnlyOnFaulted);
            Task.Run(() =>
            {
                while (true)
                {
                    UpdateCallbackEntry entry = _updateQueue.Take();
                    CacheEntry addEntry       = Add(entry.Key, entry.ImageFactory);
                    entry.UpdateImageCallback(addEntry.Image);
                }
            }).ContinueWith(ErrorReporting.UnhandledExceptionHandleTask, TaskContinuationOptions.OnlyOnFaulted);
        }
Esempio n. 7
0
        /// <summary>
        /// Searches the places.sqlite db and returns all bookmarks
        /// </summary>
        public List <Bookmark> GetBookmarks()
        {
            // Return empty list if the places.sqlite file cannot be found
            if (string.IsNullOrEmpty(PlacesPath) || !File.Exists(PlacesPath))
            {
                return(new List <Bookmark>());
            }
            Logger.WoxDebug($"Firefox db path {PlacesPath}");

            var bookmarList = new List <Bookmark>();

            // create the connection string and init the connection

            string dbPath = $"Data Source={PlacesPath}";

            using (var dbConnection = new SqliteConnection(dbPath))
            {
                // Open connection to the database file and execute the query
                dbConnection.Open();
                SqliteCommand command = dbConnection.CreateCommand();
                command.CommandText = @"SELECT moz_places.url, moz_bookmarks.title
                        FROM moz_places
                        INNER JOIN moz_bookmarks ON (
                            moz_bookmarks.fk NOT NULL AND moz_bookmarks.fk = moz_places.id
                        )";
                using (SqliteDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string url   = reader.GetString(0) ?? string.Empty;
                        string title = reader.GetString(1) ?? string.Empty;
                        Logger.WoxTrace($"Firefox bookmark: <{title}> <{url}>");
                        bookmarList.Add(new Bookmark()
                        {
                            Name = title,
                            Url  = url,
                        });
                    }
                }
            }

            return(bookmarList);
        }
Esempio n. 8
0
        public List <Result> Query(Query query)
        {
            if (_updateSource != null && !_updateSource.IsCancellationRequested)
            {
                _updateSource.Cancel();
                Logger.WoxDebug($"cancel init {_updateSource.Token.GetHashCode()} {Thread.CurrentThread.ManagedThreadId} {query.RawQuery}");
                _updateSource.Dispose();
            }
            var source = new CancellationTokenSource();

            _updateSource = source;
            var token = source.Token;

            ConcurrentBag <Result> resultRaw = new ConcurrentBag <Result>();

            if (token.IsCancellationRequested)
            {
                return(new List <Result>());
            }
            Parallel.ForEach(_win32s, (program, state) =>
            {
                if (token.IsCancellationRequested)
                {
                    state.Break();
                }
                if (program.Enabled)
                {
                    var r = program.Result(query.Search, _context.API);
                    if (r != null && r.Score > 0)
                    {
                        resultRaw.Add(r);
                    }
                }
            });
            if (token.IsCancellationRequested)
            {
                return(new List <Result>());
            }
            Parallel.ForEach(_uwps, (program, state) =>
            {
                if (token.IsCancellationRequested)
                {
                    state.Break();
                }
                if (program.Enabled)
                {
                    var r = program.Result(query.Search, _context.API);
                    if (token.IsCancellationRequested)
                    {
                        state.Break();
                    }
                    if (r != null && r.Score > 0)
                    {
                        resultRaw.Add(r);
                    }
                }
            });

            if (token.IsCancellationRequested)
            {
                return(new List <Result>());
            }
            OrderedParallelQuery <Result> sorted = resultRaw.AsParallel().OrderByDescending(r => r.Score);
            List <Result> results = new List <Result>();

            foreach (Result r in sorted)
            {
                if (token.IsCancellationRequested)
                {
                    return(new List <Result>());
                }
                var ignored = _settings.IgnoredSequence.Any(entry =>
                {
                    if (entry.IsRegex)
                    {
                        return(Regex.Match(r.Title, entry.EntryString).Success);
                    }
                    else
                    {
                        return(r.Title.ToLower().Contains(entry.EntryString));
                    }
                });
                if (!ignored)
                {
                    results.Add(r);
                }
                if (results.Count == 30)
                {
                    break;
                }
            }
            return(results);
        }
Esempio n. 9
0
        private static ImageSource LoadInternal(string path)
        {
            Logger.WoxDebug($"image {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);
            }
        }
Esempio n. 10
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);
            }
        }