Ejemplo n.º 1
0
        private void Edit_SubmenuOpening(object sender, RoutedEventArgs e)
        {
            this.FilePlayer_Stop(); // In case the FilePlayer is going

            // Enable / disable various edit menu items depending on whether we are looking at the single image view or overview
            bool state = this.IsDisplayingSingleImage();

            this.MenuItemCopyPreviousValues.IsEnabled = state;

            // Enable the FindMissingImage menu only if the current image is missing
            ImageRow currentImage = this.DataHandler?.ImageCache?.Current;

            this.MenuItemFindMissingImage.IsEnabled =
                this.DataHandler?.ImageCache?.Current != null &&
                false == File.Exists(FilesFolders.GetFullPath(this.DataHandler.FileDatabase, currentImage));

            if (this.MarkableCanvas.ThumbnailGrid.IsVisible == false && this.MarkableCanvas.ThumbnailGrid.IsGridActive == false)
            {
                this.MenuItemRestoreDefaults.Header  = "Restore default values for this file";
                this.MenuItemRestoreDefaults.ToolTip = "For the currently displayed file, revert all fields to its default values (excepting file paths and dates/times)";
            }
            else
            {
                this.MenuItemRestoreDefaults.Header  = "Restore default values for the checkmarked files";
                this.MenuItemRestoreDefaults.ToolTip = "For all checkmarked files, revert their fields to their default values (excepting file paths and dates/times)";
            }
        }
Ejemplo n.º 2
0
        private static Result CreateFileResult(string filePath, Query query)
        {
            var result = new Result
            {
                Title              = Path.GetFileName(filePath),
                SubTitle           = filePath,
                IcoPath            = filePath,
                TitleHighlightData = StringMatcher.FuzzySearch(query.Search, Path.GetFileName(filePath)).MatchData,
                Action             = c =>
                {
                    try
                    {
                        FilesFolders.OpenPath(filePath);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Could not start " + filePath);
                    }

                    return(true);
                },
                ContextData = new SearchResult {
                    Type = ResultType.File, FullPath = filePath
                }
            };

            return(result);
        }
Ejemplo n.º 3
0
        private static Result CreateOpenCurrentFolderResult(string incompleteName, string search)
        {
            var firstResult = "Open current directory";

            if (incompleteName.Length > 0)
            {
                firstResult = "Open " + search;
            }

            var folderName = search.TrimEnd('\\').Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.None).Last();

            return(new Result
            {
                Title = firstResult,
                SubTitle = $"Use > to search files and subfolders within {folderName}, " +
                           $"* to search for file extensions in {folderName} or both >* to combine the search",
                IcoPath = search,
                Score = 500,
                Action = c =>
                {
                    FilesFolders.OpenPath(search);
                    return true;
                }
            });
        }
Ejemplo n.º 4
0
        private Result CreateOpenContainingFolderResult(SearchResult record)
        {
            return(new Result
            {
                Title = Context.API.GetTranslation("plugin_explorer_opencontainingfolder"),
                SubTitle = Context.API.GetTranslation("plugin_explorer_opencontainingfolder_subtitle"),
                Action = _ =>
                {
                    try
                    {
                        FilesFolders.OpenContainingFolder(record.FullPath);
                    }
                    catch (Exception e)
                    {
                        var message = $"Fail to open file at {record.FullPath}";
                        LogException(message, e);
                        Context.API.ShowMsg(message);
                        return false;
                    }

                    return true;
                },
                IcoPath = Constants.FolderImagePath
            });
        }
Ejemplo n.º 5
0
        private Result CreateFolderResult(string title, string subtitle, string path, Query query)
        {
            return(new Result
            {
                Title = title,
                IcoPath = path,
                SubTitle = subtitle,
                TitleHighlightData = StringMatcher.FuzzySearch(query.Search, title).MatchData,
                Action = c =>
                {
                    if (c.SpecialKeyState.CtrlPressed)
                    {
                        try
                        {
                            FilesFolders.OpenPath(path);
                            return true;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Could not start " + path);
                            return false;
                        }
                    }

                    string changeTo = path.EndsWith("\\") ? path : path + "\\";
                    _context.API.ChangeQuery(string.IsNullOrEmpty(query.ActionKeyword) ?
                                             changeTo :
                                             query.ActionKeyword + " " + changeTo);
                    return false;
                },
                ContextData = new SearchResult {
                    Type = ResultType.Folder, FullPath = path
                }
            });
        }
Ejemplo n.º 6
0
        ///<summary>
        ///This method should be run at first before all methods during start up and should be run before determining which data location
        ///will be used for Flow Launcher.
        ///</summary>
        public void PreStartCleanUpAfterPortabilityUpdate()
        {
            // Specify here so this method does not rely on other environment variables to initialise
            var portableDataDir = Path.Combine(Directory.GetParent(Assembly.GetExecutingAssembly().Location.NonNull()).ToString(), "UserData");
            var roamingDataDir  = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FlowLauncher");

            // Get full path to the .dead files for each case
            var portableDataDeleteFilePath = Path.Combine(portableDataDir, DataLocation.DeletionIndicatorFile);
            var roamingDataDeleteFilePath  = Path.Combine(roamingDataDir, DataLocation.DeletionIndicatorFile);

            // If the data folder in %appdata% is marked for deletion,
            // delete it and prompt the user to pick the portable data location
            if (File.Exists(roamingDataDeleteFilePath))
            {
                FilesFolders.RemoveFolderIfExists(roamingDataDir);

                if (MessageBox.Show("Flow Launcher has detected you enabled portable mode, " +
                                    "would you like to move it to a different location?", string.Empty,
                                    MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    FilesFolders.OpenPath(Constant.RootDirectory);

                    Environment.Exit(0);
                }
            }
            // Otherwise, if the portable data folder is marked for deletion,
            // delete it and notify the user about it.
            else if (File.Exists(portableDataDeleteFilePath))
            {
                FilesFolders.RemoveFolderIfExists(portableDataDir);

                MessageBox.Show("Flow Launcher has detected you disabled portable mode, " +
                                "the relevant shortcuts and uninstaller entry have been created");
            }
        }
Ejemplo n.º 7
0
 private void OnPluginDirecotyClick(object sender, MouseButtonEventArgs e)
 {
     if (e.ChangedButton == MouseButton.Left)
     {
         var directory = viewModel.SelectedPlugin.PluginPair.Metadata.PluginDirectory;
         if (!string.IsNullOrEmpty(directory))
             FilesFolders.OpenPath(directory);
     }
 }
Ejemplo n.º 8
0
        internal List <Result> Search(Query query)
        {
            var results = new List <Result>();

            var querySearch = query.Search;

            var quickFolderLinks = quickFolderAccess.FolderList(query, settings.QuickFolderAccessLinks, context);

            if (quickFolderLinks.Count > 0)
            {
                return(quickFolderLinks);
            }

            if (string.IsNullOrEmpty(querySearch))
            {
                return(results);
            }

            var isEnvironmentVariable = EnvironmentVariables.IsEnvironmentVariableSearch(querySearch);

            if (isEnvironmentVariable)
            {
                return(EnvironmentVariables.GetEnvironmentStringPathSuggestions(querySearch, query, context));
            }

            // Query is a location path with a full environment variable, eg. %appdata%\somefolder\
            var isEnvironmentVariablePath = querySearch.Substring(1).Contains("%\\");

            if (!FilesFolders.IsLocationPathString(querySearch) && !isEnvironmentVariablePath)
            {
                return(WindowsIndexFilesAndFoldersSearch(query, querySearch));
            }

            var locationPath = querySearch;

            if (isEnvironmentVariablePath)
            {
                locationPath = EnvironmentVariables.TranslateEnvironmentVariablePath(locationPath);
            }

            if (!FilesFolders.LocationExists(FilesFolders.ReturnPreviousDirectoryIfIncompleteString(locationPath)))
            {
                return(results);
            }

            var useIndexSearch = UseWindowsIndexForDirectorySearch(locationPath);

            results.Add(resultManager.CreateOpenCurrentFolderResult(locationPath, useIndexSearch));

            results.AddRange(TopLevelDirectorySearchBehaviour(WindowsIndexTopLevelFolderSearch,
                                                              DirectoryInfoClassSearch,
                                                              useIndexSearch,
                                                              query,
                                                              locationPath));

            return(results);
        }
Ejemplo n.º 9
0
        public void WhenGivenQuerySearchString_ThenShouldIndicateIfIsLocationPathString(string querySearchString, bool expectedResult)
        {
            // When, Given
            var result = FilesFolders.IsLocationPathString(querySearchString);

            //Then
            Assert.IsTrue(result == expectedResult,
                          $"Expected query search string check result is: {expectedResult} {Environment.NewLine} " +
                          $"Actual check result is {result} {Environment.NewLine}");
        }
Ejemplo n.º 10
0
        public void WhenGivenAPath_ThenShouldReturnThePreviousDirectoryPathIfIncompleteOrOriginalString(
            string path, string expectedString)
        {
            var returnedPath = FilesFolders.ReturnPreviousDirectoryIfIncompleteString(path);

            //Then
            Assert.IsTrue(returnedPath == expectedString,
                          $"Expected path string: {expectedString} {Environment.NewLine} " +
                          $"Actual path string is {returnedPath} {Environment.NewLine}");
        }
Ejemplo n.º 11
0
        internal static Result CreateOpenCurrentFolderResult(string path, bool windowsIndexed = false)
        {
            var retrievedDirectoryPath = FilesFolders.ReturnPreviousDirectoryIfIncompleteString(path);

            var folderName = retrievedDirectoryPath.TrimEnd(Constants.DirectorySeperator).Split(new[]
            {
                Path.DirectorySeparatorChar
            }, StringSplitOptions.None).Last();

            if (retrievedDirectoryPath.EndsWith(":\\"))
            {
                var driveLetter = path.Substring(0, 1).ToUpper();
                folderName = driveLetter + " drive";
            }

            var title = "Open current directory";

            if (retrievedDirectoryPath != path)
            {
                title = "Open " + folderName;
            }


            var subtitleFolderName = folderName;

            // ie. max characters can be displayed without subtitle cutting off: "Program Files (x86)"
            if (folderName.Length > 19)
            {
                subtitleFolderName = "the directory";
            }

            return(new Result
            {
                Title = title,
                SubTitle = $"Use > to search within {subtitleFolderName}, " +
                           $"* to search for file extensions or >* to combine both searches.",
                AutoCompleteText = GetPathWithActionKeyword(retrievedDirectoryPath, ResultType.Folder),
                IcoPath = retrievedDirectoryPath,
                Score = 500,
                Action = c =>
                {
                    Context.API.OpenDirectory(retrievedDirectoryPath);
                    return true;
                },
                TitleToolTip = retrievedDirectoryPath,
                SubTitleToolTip = retrievedDirectoryPath,
                ContextData = new SearchResult
                {
                    Type = ResultType.Folder,
                    FullPath = retrievedDirectoryPath,
                    ShowIndexState = true,
                    WindowsIndexed = windowsIndexed
                }
            });
        }
Ejemplo n.º 12
0
        private List <Result> DirectorySearch(SearchOption searchOption, Query query, string search, string searchCriteria)
        {
            var results = new List <Result>();

            var path = FilesFolders.ReturnPreviousDirectoryIfIncompleteString(search);

            var folderList = new List <Result>();
            var fileList   = new List <Result>();

            try
            {
                var directoryInfo   = new System.IO.DirectoryInfo(path);
                var fileSystemInfos = directoryInfo.GetFileSystemInfos(searchCriteria, searchOption);

                foreach (var fileSystemInfo in fileSystemInfos)
                {
                    if ((fileSystemInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                    {
                        continue;
                    }

                    if (fileSystemInfo is System.IO.DirectoryInfo)
                    {
                        folderList.Add(resultManager.CreateFolderResult(fileSystemInfo.Name, fileSystemInfo.FullName, fileSystemInfo.FullName, query, true, false));
                    }
                    else
                    {
                        fileList.Add(resultManager.CreateFileResult(fileSystemInfo.FullName, query, true, false));
                    }
                }
            }
            catch (Exception e)
            {
                if (e is UnauthorizedAccessException || e is ArgumentException)
                {
                    results.Add(new Result {
                        Title = e.Message, Score = 501
                    });

                    return(results);
                }

#if DEBUG // Please investigate and handle error from DirectoryInfo search
                throw e;
#else
                Log.Exception($"|Flow.Launcher.Plugin.Explorer.DirectoryInfoSearch|Error from performing DirectoryInfoSearch", e);
#endif
            }

            // Intial ordering, this order can be updated later by UpdateResultView.MainViewModel based on history of user selection.
            return(results.Concat(folderList.OrderBy(x => x.Title)).Concat(fileList.OrderBy(x => x.Title)).ToList());
        }
Ejemplo n.º 13
0
        private static List <Result> DirectorySearch(EnumerationOptions enumerationOption, Query query, string search,
                                                     string searchCriteria, CancellationToken token)
        {
            var results = new List <Result>();

            var path = FilesFolders.ReturnPreviousDirectoryIfIncompleteString(search);

            var folderList = new List <Result>();
            var fileList   = new List <Result>();

            try
            {
                var directoryInfo = new System.IO.DirectoryInfo(path);

                foreach (var fileSystemInfo in directoryInfo.EnumerateFileSystemInfos(searchCriteria, enumerationOption))
                {
                    if (fileSystemInfo is System.IO.DirectoryInfo)
                    {
                        folderList.Add(ResultManager.CreateFolderResult(fileSystemInfo.Name, fileSystemInfo.FullName,
                                                                        fileSystemInfo.FullName, query, true, false));
                    }
                    else
                    {
                        fileList.Add(ResultManager.CreateFileResult(fileSystemInfo.FullName, query, true, false));
                    }

                    token.ThrowIfCancellationRequested();
                }
            }
            catch (Exception e)
            {
                if (!(e is ArgumentException))
                {
                    throw e;
                }

                results.Add(new Result {
                    Title = e.Message, Score = 501
                });

                return(results);

#if DEBUG // Please investigate and handle error from DirectoryInfo search
#else
                Log.Exception($"|Flow.Launcher.Plugin.Explorer.DirectoryInfoSearch|Error from performing DirectoryInfoSearch", e);
#endif
            }

            // Initial ordering, this order can be updated later by UpdateResultView.MainViewModel based on history of user selection.
            return(results.Concat(folderList.OrderBy(x => x.Title)).Concat(fileList.OrderBy(x => x.Title)).ToList());
        }
Ejemplo n.º 14
0
        private bool UseWindowsIndexForDirectorySearch(string locationPath)
        {
            if (!settings.UseWindowsIndexForDirectorySearch)
            {
                return(false);
            }

            if (settings.IndexSearchExcludedSubdirectoryPaths
                .Any(x => FilesFolders.ReturnPreviousDirectoryIfIncompleteString(locationPath)
                     .StartsWith(x.Path, StringComparison.OrdinalIgnoreCase)))
            {
                return(false);
            }

            return(indexSearch.PathIsIndexed(locationPath));
        }
Ejemplo n.º 15
0
        private void Install(UserPlugin plugin, string downloadedFilePath)
        {
            if (!File.Exists(downloadedFilePath))
            {
                return;
            }

            var tempFolderPath       = Path.Combine(Path.GetTempPath(), "flowlauncher");
            var tempFolderPluginPath = Path.Combine(tempFolderPath, "plugin");

            if (Directory.Exists(tempFolderPath))
            {
                Directory.Delete(tempFolderPath, true);
            }

            Directory.CreateDirectory(tempFolderPath);

            var zipFilePath = Path.Combine(tempFolderPath, Path.GetFileName(downloadedFilePath));

            File.Copy(downloadedFilePath, zipFilePath);

            File.Delete(downloadedFilePath);

            Utilities.UnZip(zipFilePath, tempFolderPluginPath, true);

            var pluginFolderPath = Utilities.GetContainingFolderPathAfterUnzip(tempFolderPluginPath);

            var metadataJsonFilePath = string.Empty;

            if (File.Exists(Path.Combine(pluginFolderPath, Constant.PluginMetadataFileName)))
            {
                metadataJsonFilePath = Path.Combine(pluginFolderPath, Constant.PluginMetadataFileName);
            }

            if (string.IsNullOrEmpty(metadataJsonFilePath) || string.IsNullOrEmpty(pluginFolderPath))
            {
                MessageBox.Show(Context.API.GetTranslation("plugin_pluginsmanager_install_errormetadatafile"));
                return;
            }

            string newPluginPath = Path.Combine(DataLocation.PluginsDirectory, $"{plugin.Name}-{plugin.Version}");

            FilesFolders.CopyAll(pluginFolderPath, newPluginPath);

            Directory.Delete(pluginFolderPath, true);
        }
Ejemplo n.º 16
0
        ///<summary>
        ///This method should be run at first before all methods during start up and should be run before determining which data location
        ///will be used for Flow Launcher.
        ///</summary>
        public void PreStartCleanUpAfterPortabilityUpdate()
        {
            // Specify here so this method does not rely on other environment variables to initialise
            var portableDataPath = Path.Combine(Directory.GetParent(Assembly.GetExecutingAssembly().Location.NonNull()).ToString(), "UserData");
            var roamingDataPath  = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FlowLauncher");

            bool DataLocationPortableDeleteRequired = false;
            bool DataLocationRoamingDeleteRequired  = false;

            if ((roamingDataPath + "\\" + DataLocation.DeletionIndicatorFile).FileExits())
            {
                DataLocationRoamingDeleteRequired = true;
            }

            if ((portableDataPath + "\\" + DataLocation.DeletionIndicatorFile).FileExits())
            {
                DataLocationPortableDeleteRequired = true;
            }

            if (DataLocationRoamingDeleteRequired)
            {
                FilesFolders.RemoveFolderIfExists(roamingDataPath);

                if (MessageBox.Show("Flow Launcher has detected you enabled portable mode, " +
                                    "would you like to move it to a different location?", string.Empty,
                                    MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    FilesFolders.OpenPath(Constant.RootDirectory);

                    Environment.Exit(0);
                }

                return;
            }

            if (DataLocationPortableDeleteRequired)
            {
                FilesFolders.RemoveFolderIfExists(portableDataPath);

                MessageBox.Show("Flow Launcher has detected you disabled portable mode, " +
                                "the relevant shortcuts and uninstaller entry have been created");

                return;
            }
        }
Ejemplo n.º 17
0
        private async void MenuItemMergeDatabases_Click(object sender, RoutedEventArgs e)
        {
            if (this.State.SuppressMergeDatabasesPrompt == false)
            {
                if (Dialogs.MenuFileMergeDatabasesExplainedDialog(this) == false)
                {
                    return;
                }
            }
            // Get the location of the template, which also determines the root folder
            if (this.TryGetTemplatePath(out string templateDatabasePath) == false)
            {
                return;
            }

            // Set up progress indicators
            Mouse.OverrideCursor = Cursors.Wait;
            this.StatusBar.SetMessage("Creating a merged database, please wait...");
            IProgress <ProgressBarArguments> progress = progressHandler;

            this.BusyCancelIndicator.EnableForMerging(true);

            // Find all the .DDB files located in subfolders under the root folder (excluding backup folders)
            string        startFolder = Path.GetDirectoryName(templateDatabasePath);
            List <string> allDDBFiles = new List <string>();

            FilesFolders.GetAllFilesInFoldersAndSubfoldersMatchingPattern(startFolder, "*" + Constant.File.FileDatabaseFileExtension, true, true, allDDBFiles);

            // Merge the found databases into a new (or replaced) TimelapseData_merged.ddb file located in the same folder as the template.
            // Note: .ddb files found in a Backup folder will be ignored
            ErrorsAndWarnings errorMessages = await MergeDatabases.TryMergeDatabasesAsync(templateDatabasePath, allDDBFiles, progress).ConfigureAwait(true);

            // Turn off progress indicators
            this.BusyCancelIndicator.EnableForSelection(false);
            Mouse.OverrideCursor = null;

            if (errorMessages.Errors.Count != 0 || errorMessages.Warnings.Count != 0)
            {
                // Merge databases: Show errors and/or warnings, if any.
                Dialogs.MenuFileMergeDatabasesErrorsAndWarningsDialog(this, errorMessages);
            }
            this.StatusBar.SetMessage(errorMessages.Errors.Count == 0 ? "Merged database created" : "Aborted creation of merged database");
        }
Ejemplo n.º 18
0
        public void GivenAPartialPath_WhenPreviousLevelDirectoryExists_ThenShouldReturnThePreviousDirectoryPathString(
            string path, bool previousDirectoryExists, string expectedString)
        {
            // When
            Func <string, bool> previousLocationExists = null;

            if (previousDirectoryExists)
            {
                previousLocationExists = PreviousLocationExistsReturnsTrue;
            }
            else
            {
                previousLocationExists = PreviousLocationNotExistReturnsFalse;
            }

            // Given
            var previousDirectoryPath = FilesFolders.GetPreviousExistingDirectory(previousLocationExists, path);

            //Then
            Assert.IsTrue(previousDirectoryPath == expectedString,
                          $"Expected path string: {expectedString} {Environment.NewLine} " +
                          $"Actual path string is {previousDirectoryPath} {Environment.NewLine}");
        }
Ejemplo n.º 19
0
        internal Result CreateFileResult(string filePath, Query query, bool showIndexState = false, bool windowsIndexed = false)
        {
            var result = new Result
            {
                Title              = Path.GetFileName(filePath),
                SubTitle           = filePath,
                IcoPath            = filePath,
                TitleHighlightData = StringMatcher.FuzzySearch(query.Search, Path.GetFileName(filePath)).MatchData,
                Action             = c =>
                {
                    try
                    {
                        if (c.SpecialKeyState.CtrlPressed)
                        {
                            FilesFolders.OpenContainingFolder(filePath);
                        }
                        else
                        {
                            FilesFolders.OpenPath(filePath);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Could not start " + filePath);
                    }

                    return(true);
                },
                TitleToolTip    = Constants.ToolTipOpenContainingFolder,
                SubTitleToolTip = Constants.ToolTipOpenContainingFolder,
                ContextData     = new SearchResult {
                    Type = ResultType.File, FullPath = filePath, ShowIndexState = showIndexState, WindowsIndexed = windowsIndexed
                }
            };

            return(result);
        }
Ejemplo n.º 20
0
        internal Result CreateFolderResult(string title, string subtitle, string path, Query query, bool showIndexState = false, bool windowsIndexed = false)
        {
            return(new Result
            {
                Title = title,
                IcoPath = path,
                SubTitle = subtitle,
                TitleHighlightData = StringMatcher.FuzzySearch(query.Search, title).MatchData,
                Action = c =>
                {
                    if (c.SpecialKeyState.CtrlPressed)
                    {
                        try
                        {
                            FilesFolders.OpenPath(path);
                            return true;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Could not start " + path);
                            return false;
                        }
                    }

                    string changeTo = path.EndsWith(Constants.DirectorySeperator) ? path : path + Constants.DirectorySeperator;
                    context.API.ChangeQuery(string.IsNullOrEmpty(query.ActionKeyword) ?
                                            changeTo :
                                            query.ActionKeyword + " " + changeTo);
                    return false;
                },
                TitleToolTip = Constants.ToolTipOpenDirectory,
                SubTitleToolTip = Constants.ToolTipOpenDirectory,
                ContextData = new SearchResult {
                    Type = ResultType.Folder, FullPath = path, ShowIndexState = showIndexState, WindowsIndexed = windowsIndexed
                }
            });
        }
Ejemplo n.º 21
0
        // Load template, images, and video files...
        private async void MenuItemLoadImages_Click(object sender, RoutedEventArgs e)
        {
            if (this.TryGetTemplatePath(out string templateDatabasePath))
            {
                // We don't allow templates in root drive letters (e.g., D:) or in System or Hidden folders
                if (FilesFolders.IsFolderPathADriveLetter(Path.GetDirectoryName(templateDatabasePath)))
                {
                    Dialog.Dialogs.TemplateInDisallowedFolder(this, true, Path.GetDirectoryName(templateDatabasePath));
                    return;
                }
                if (FilesFolders.IsFolderSystemOrHidden(Path.GetDirectoryName(templateDatabasePath)))
                {
                    Dialog.Dialogs.TemplateInDisallowedFolder(this, false, Path.GetDirectoryName(templateDatabasePath));
                    return;
                }

                Mouse.OverrideCursor = Cursors.Wait;
                this.StatusBar.SetMessage("Loading images, please wait...");
                await this.TryOpenTemplateAndBeginLoadFoldersAsync(templateDatabasePath).ConfigureAwait(true);

                this.StatusBar.SetMessage("Image set is now loaded.");
                Mouse.OverrideCursor = null;
            }
        }
Ejemplo n.º 22
0
 public void MoveUserDataFolder(string fromLocation, string toLocation)
 {
     FilesFolders.Copy(fromLocation, toLocation);
     VerifyUserDataAfterMove(fromLocation, toLocation);
 }
Ejemplo n.º 23
0
 private void OpenPluginFolder(object sender, RoutedEventArgs e)
 {
     FilesFolders.OpenPath(Path.Combine(DataLocation.DataDirectory(), Constant.Themes));
 }
Ejemplo n.º 24
0
        public async Task UpdateApp(IPublicAPI api, bool silentUpdate = true)
        {
            try
            {
                UpdateInfo newUpdateInfo;

                if (!silentUpdate)
                {
                    api.ShowMsg(api.GetTranslation("pleaseWait"),
                                api.GetTranslation("update_flowlauncher_update_check"));
                }

                using var updateManager = await GitHubUpdateManager(GitHubRepository).ConfigureAwait(false);


                // UpdateApp CheckForUpdate will return value only if the app is squirrel installed
                newUpdateInfo = await updateManager.CheckForUpdate().NonNull().ConfigureAwait(false);

                var newReleaseVersion = Version.Parse(newUpdateInfo.FutureReleaseEntry.Version.ToString());
                var currentVersion    = Version.Parse(Constant.Version);

                Log.Info($"|Updater.UpdateApp|Future Release <{newUpdateInfo.FutureReleaseEntry.Formatted()}>");

                if (newReleaseVersion <= currentVersion)
                {
                    if (!silentUpdate)
                    {
                        MessageBox.Show(api.GetTranslation("update_flowlauncher_already_on_latest"));
                    }
                    return;
                }

                if (!silentUpdate)
                {
                    api.ShowMsg(api.GetTranslation("update_flowlauncher_update_found"),
                                api.GetTranslation("update_flowlauncher_updating"));
                }

                await updateManager.DownloadReleases(newUpdateInfo.ReleasesToApply).ConfigureAwait(false);

                await updateManager.ApplyReleases(newUpdateInfo).ConfigureAwait(false);

                if (DataLocation.PortableDataLocationInUse())
                {
                    var targetDestination = updateManager.RootAppDirectory + $"\\app-{newReleaseVersion.ToString()}\\{DataLocation.PortableFolderName}";
                    FilesFolders.CopyAll(DataLocation.PortableDataPath, targetDestination);
                    if (!FilesFolders.VerifyBothFolderFilesEqual(DataLocation.PortableDataPath, targetDestination))
                    {
                        MessageBox.Show(string.Format(api.GetTranslation("update_flowlauncher_fail_moving_portable_user_profile_data"),
                                                      DataLocation.PortableDataPath,
                                                      targetDestination));
                    }
                }
                else
                {
                    await updateManager.CreateUninstallerRegistryEntry().ConfigureAwait(false);
                }

                var newVersionTips = NewVersinoTips(newReleaseVersion.ToString());

                Log.Info($"|Updater.UpdateApp|Update success:{newVersionTips}");

                if (MessageBox.Show(newVersionTips, api.GetTranslation("update_flowlauncher_new_update"), MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    UpdateManager.RestartApp(Constant.ApplicationFileName);
                }
            }
            catch (Exception e) when(e is HttpRequestException || e is WebException || e is SocketException || e is TaskCanceledException)
            {
                Log.Exception($"|Updater.UpdateApp|Check your connection and proxy settings to github-cloud.s3.amazonaws.com.", e);
                api.ShowMsg(api.GetTranslation("update_flowlauncher_fail"),
                            api.GetTranslation("update_flowlauncher_check_connection"));
                return;
            }
        }
        /// <summary>
        /// looks what in the given folder, and makes a recursive call to itself, with the folders that is in the given folder.
        /// To ensure that it doesn't make a endless recursive call, it check the foldername, to see that it is not the same as the last
        /// uses the extentionVerifier to ensure, that only musiknumbers are added to the List MusicList
        /// </summary>
        /// <param name="folderpath">The folder that are to be indexed.</param>
        private void SubFoldersLookup(string folderpath)
        {
            if (folderpath == null) throw new ArgumentNullException("folderpath");

            if (folderpath == testsubfolder) throw new Exception("Recursive subfolder call");
            testsubfolder = folderpath;

            FilesFolders subContainer = new FilesFolders(folderpath);
            foreach (IOitem ioitem in subContainer.IndexContainer)
            {
                if (extentionVerifier.TestExtention(ioitem.Extention))
                {
                    MusikList.Add(ioitem);
                    //Console.WriteLine("subfolder added " + ioitem.FullName);
                }

                if (ioitem.Tag == "folder")
                {
                    //Console.WriteLine(ioitem.FullName);
                    SubFoldersLookup(ioitem.FullName);

                }
            }
        }
        /// <summary>
        /// Look's up what in the given folder, and calls a subFoldersLookup with the folders in the first folder
        /// uses the extentionVerifier to ensure, that only musiknumbers are added to the List MusicList
        /// </summary>
        private void foldersVers_One()
        {
            Container = new FilesFolders(Folderpath);

            foreach (IOitem ioitem in Container.IndexContainer)
            {
                if (extentionVerifier.TestExtention(ioitem.Extention))
                {
                    MusikList.Add(ioitem);
                    //Console.WriteLine("added " + ioitem.FullName);
                }

                if (ioitem.Tag == "folder")
                {
                    //Console.WriteLine(ioitem.FullName);
                    SubFoldersLookup(ioitem.FullName);
                }
            }
            testsubfolder = null;
        }
 /// <summary>
 /// Sets the folderpath, and starts the runner
 /// </summary>
 /// <param name="folderpath">The folder that are to indexed</param>
 public void SetIndexPath(string folderpath)
 {
     Folderpath = folderpath;
     _folder = new FilesFolders(Folderpath);
     Runner();
 }
Ejemplo n.º 28
0
        public List <Result> Query(Query query)
        {
            if (FilesFolders.IsLocationPathString(query.Search))
            {
                return(new List <Result>());
            }

            var searchSourceList = new List <SearchSource>();
            var results          = new List <Result>();

            _updateSource?.Cancel();
            _updateSource = new CancellationTokenSource();
            _updateToken  = _updateSource.Token;

            _settings.SearchSources.Where(o => (o.ActionKeyword == query.ActionKeyword || o.ActionKeyword == SearchSourceGlobalPluginWildCardSign) &&
                                          o.Enabled)
            .ToList()
            .ForEach(x => searchSourceList.Add(x));

            if (searchSourceList.Any())
            {
                foreach (SearchSource searchSource in searchSourceList)
                {
                    string keyword = string.Empty;
                    keyword = searchSource.ActionKeyword == SearchSourceGlobalPluginWildCardSign?query.ToString() : query.Search;

                    var    title    = keyword;
                    string subtitle = _context.API.GetTranslation("flowlauncher_plugin_websearch_search") + " " + searchSource.Title;

                    if (string.IsNullOrEmpty(keyword))
                    {
                        var result = new Result
                        {
                            Title    = subtitle,
                            SubTitle = string.Empty,
                            IcoPath  = searchSource.IconPath
                        };
                        results.Add(result);
                    }
                    else
                    {
                        var result = new Result
                        {
                            Title    = title,
                            SubTitle = subtitle,
                            Score    = 6,
                            IcoPath  = searchSource.IconPath,
                            ActionKeywordAssigned = searchSource.ActionKeyword == SearchSourceGlobalPluginWildCardSign ? string.Empty : searchSource.ActionKeyword,
                            Action = c =>
                            {
                                if (_settings.OpenInNewBrowser)
                                {
                                    searchSource.Url.Replace("{q}", Uri.EscapeDataString(keyword)).NewBrowserWindow(_settings.BrowserPath);
                                }
                                else
                                {
                                    searchSource.Url.Replace("{q}", Uri.EscapeDataString(keyword)).NewTabInBrowser(_settings.BrowserPath);
                                }

                                return(true);
                            }
                        };

                        results.Add(result);
                        ResultsUpdated?.Invoke(this, new ResultUpdatedEventArgs
                        {
                            Results = results,
                            Query   = query
                        });

                        UpdateResultsFromSuggestion(results, keyword, subtitle, searchSource, query);
                    }
                }
            }

            return(results);
        }
Ejemplo n.º 29
0
        //Try to find a missing image
        private async void MenuItemEditFindMissingImage_Click(object sender, RoutedEventArgs e)
        {
            // Don't do anything if the image actually exists. This should not fire, as this menu item is only enabled
            // if there is a current image that doesn't exist. But just in case...
            if (null == this.DataHandler?.ImageCache?.Current || File.Exists(FilesFolders.GetFullPath(this.DataHandler.FileDatabase.FolderPath, this.DataHandler?.ImageCache?.Current)))
            {
                return;
            }

            string   folderPath   = this.DataHandler.FileDatabase.FolderPath;
            ImageRow currentImage = this.DataHandler?.ImageCache?.Current;

            // Search for - and return as list of relative path / filename tuples -  all folders under the root folder for files with the same name as the fileName.
            List <Tuple <string, string> > matchingRelativePathFileNameList = Util.FilesFolders.SearchForFoldersContainingFileName(folderPath, currentImage.File);

            // Remove any of the tuples that are spoken for i.e., that are already associated with a row in the database
            for (int i = matchingRelativePathFileNameList.Count - 1; i >= 0; i--)
            {
                if (this.DataHandler.FileDatabase.ExistsRelativePathAndFileInDataTable(matchingRelativePathFileNameList[i].Item1, matchingRelativePathFileNameList[i].Item2))
                {
                    // We only want matching files that are not already assigned to another datafield in the database
                    matchingRelativePathFileNameList.RemoveAt(i);
                }
            }

            // If there are no remaining tuples, it means no potential matches were found.
            // Display a message saying so and abort.
            if (matchingRelativePathFileNameList.Count == 0)
            {
                Dialogs.MissingFileSearchNoMatchesFoundDialog(this, currentImage.File);
                return;
            }

            // Now retrieve a list of all filenames located in the same folder (i.e., that have the same relative path) as the missing file.
            List <string> otherMissingFiles = this.DataHandler.FileDatabase.SelectFileNamesWithRelativePathFromDatabase(currentImage.RelativePath);

            // Remove the current missing file from the list, as well as any file that exists i.e., that is not missing.
            for (int i = otherMissingFiles.Count - 1; i >= 0; i--)
            {
                if (String.Equals(otherMissingFiles[i], currentImage.File) || File.Exists(Path.Combine(folderPath, currentImage.RelativePath, otherMissingFiles[i])))
                {
                    otherMissingFiles.RemoveAt(i);
                }
            }

            // For those that are left (if any), see if other files in the returned locations are in each path. Get their count, save them, and pass the count as a parameter e.g., a Dict with matching files, etc.
            // Or perhapse even better, a list of file names for each path Dict<string, List<string>>
            // As we did above, go through the other missing files and remove those that are spoken for i.e., that are already associated with a row in the database.
            // What remains will be a list of  root paths, each with a list of  missing (unassociated) files that could be candidates for locating
            Dictionary <string, List <string> > otherMissingFileCandidates = new Dictionary <string, List <string> >();

            foreach (Tuple <string, string> matchingPath in matchingRelativePathFileNameList)
            {
                List <string> orphanMissingFiles = new List <string>();
                foreach (string otherMissingFile in otherMissingFiles)
                {
                    // Its a potential candidate if its not already referenced but it exists in that relative path folder
                    if (false == this.DataHandler.FileDatabase.ExistsRelativePathAndFileInDataTable(matchingPath.Item1, otherMissingFile) &&
                        File.Exists(FilesFolders.GetFullPath(FolderPath, matchingPath.Item1, otherMissingFile)))
                    {
                        orphanMissingFiles.Add(otherMissingFile);
                    }
                }
                otherMissingFileCandidates.Add(matchingPath.Item1, orphanMissingFiles);
            }

            Dialog.MissingImageLocateRelativePaths dialog = new Dialog.MissingImageLocateRelativePaths(this, this.DataHandler.FileDatabase, currentImage.RelativePath, currentImage.File, otherMissingFileCandidates);

            bool?result = dialog.ShowDialog();

            if (result == true)
            {
                Tuple <string, string> locatedMissingFile = dialog.LocatedMissingFile;
                if (String.IsNullOrEmpty(locatedMissingFile.Item2))
                {
                    return;
                }

                // Update the original missing file
                List <ColumnTuplesWithWhere> columnTuplesWithWhereList = new List <ColumnTuplesWithWhere>();
                ColumnTuplesWithWhere        columnTuplesWithWhere     = new ColumnTuplesWithWhere();
                columnTuplesWithWhere.Columns.Add(new ColumnTuple(Constant.DatabaseColumn.RelativePath, locatedMissingFile.Item1)); // The new relative path
                columnTuplesWithWhere.SetWhere(currentImage.RelativePath, currentImage.File);                                       // Where the original relative path/file terms are met
                columnTuplesWithWhereList.Add(columnTuplesWithWhere);

                // Update the other missing files in the database, if any
                foreach (string otherMissingFileName in otherMissingFileCandidates[locatedMissingFile.Item1])
                {
                    columnTuplesWithWhere = new ColumnTuplesWithWhere();
                    columnTuplesWithWhere.Columns.Add(new ColumnTuple(Constant.DatabaseColumn.RelativePath, locatedMissingFile.Item1)); // The new value
                    columnTuplesWithWhere.SetWhere(currentImage.RelativePath, otherMissingFileName);                                    // Where the original relative path/file terms are met
                    columnTuplesWithWhereList.Add(columnTuplesWithWhere);
                }

                // Now update the database
                this.DataHandler.FileDatabase.UpdateFiles(columnTuplesWithWhereList);
                await this.FilesSelectAndShowAsync().ConfigureAwait(true);
            }
        }
Ejemplo n.º 30
0
        public void Init(PluginInitContext context)
        {
            _context  = context;
            _settings = context.API.LoadSettingJsonStorage <Settings>();
            SortOptionTranlationHelper.API = context.API;

            if (_settings.MaxSearchCount <= 0)
            {
                _settings.MaxSearchCount = Settings.DefaultMaxSearchCount;
            }

            if (!_settings.EverythingInstalledPath.FileExists())
            {
                var installedLocation = Utilities.GetInstalledPath();

                if (string.IsNullOrEmpty(installedLocation) &&
                    System.Windows.Forms.MessageBox.Show(
                        string.Format(context.API.GetTranslation("flowlauncher_plugin_everything_installing_select"), Environment.NewLine),
                        context.API.GetTranslation("flowlauncher_plugin_everything_installing_title"),
                        System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    // Solves single thread apartment (STA) mode requirement error when using OpenFileDialog
                    Thread t = new Thread(() =>
                    {
                        var dlg = new System.Windows.Forms.OpenFileDialog
                        {
                            InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
                        };

                        var result = dlg.ShowDialog();
                        if (result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(dlg.FileName))
                        {
                            installedLocation = dlg.FileName;
                        }
                    });

                    // Run your code from a thread that joins the STA Thread
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();
                    t.Join();
                }

                if (string.IsNullOrEmpty(installedLocation))
                {
                    Task.Run(async delegate
                    {
                        context.API.ShowMsg(context.API.GetTranslation("flowlauncher_plugin_everything_installing_title"),
                                            context.API.GetTranslation("flowlauncher_plugin_everything_installing_subtitle"), "", useMainWindowAsOwner: false);

                        await DroplexPackage.Drop(App.Everything1_4_1_1009).ConfigureAwait(false);

                        context.API.ShowMsg(context.API.GetTranslation("flowlauncher_plugin_everything_installing_title"),
                                            context.API.GetTranslation("flowlauncher_plugin_everything_installationsuccess_subtitle"), "", useMainWindowAsOwner: false);

                        _settings.EverythingInstalledPath = "C:\\Program Files\\Everything\\Everything.exe";

                        FilesFolders.OpenPath(_settings.EverythingInstalledPath);
                    }).ContinueWith(t =>
                    {
                        _context.API.LogException("Everything.Main", $"Failed to install Everything service", t.Exception.InnerException, "DroplexPackage.Drop");
                        MessageBox.Show(context.API.GetTranslation("flowlauncher_plugin_everything_installationfailed_subtitle"),
                                        context.API.GetTranslation("flowlauncher_plugin_everything_installing_title"));
                    }, TaskContinuationOptions.OnlyOnFaulted);
                }
                else
                {
                    _settings.EverythingInstalledPath = installedLocation;
                }
            }

            var          pluginDirectory     = context.CurrentPluginMetadata.PluginDirectory;
            const string sdk                 = "EverythingSDK";
            var          bundledSdkDirectory = Path.Combine(pluginDirectory, sdk, CpuType());

            var sdkPath = Path.Combine(bundledSdkDirectory, DLL);

            _api.Load(sdkPath);
        }
Ejemplo n.º 31
0
 public void VerifyUserDataAfterMove(string fromLocation, string toLocation)
 {
     FilesFolders.VerifyBothFolderFilesEqual(fromLocation, toLocation);
 }
Ejemplo n.º 32
0
        public List <Result> Query(Query query)
        {
            _cancellationTokenSource?.Cancel(); // cancel if already exist
            var cts     = _cancellationTokenSource = new CancellationTokenSource();
            var results = new List <Result>();

            if (!string.IsNullOrEmpty(query.Search))
            {
                var keyword = query.Search;

                try
                {
                    var searchList = _api.Search(keyword, cts.Token, _settings.SortOption, maxCount: _settings.MaxSearchCount);
                    if (searchList == null)
                    {
                        return(results);
                    }

                    foreach (var searchResult in searchList)
                    {
                        var r = CreateResult(keyword, searchResult);
                        results.Add(r);
                    }
                }
                catch (IPCErrorException)
                {
                    results.Add(new Result
                    {
                        Title    = _context.API.GetTranslation("flowlauncher_plugin_everything_is_not_running"),
                        SubTitle = _context.API.GetTranslation("flowlauncher_plugin_everything_run_service"),
                        IcoPath  = "Images\\warning.png",
                        Action   = _ =>
                        {
                            if (FilesFolders.FileExists(_settings.EverythingInstalledPath))
                            {
                                FilesFolders.OpenPath(_settings.EverythingInstalledPath);
                            }

                            return(true);
                        }
                    });
                }
                catch (Exception e)
                {
                    _context.API.LogException("EverythingPlugin", "Query Error", e);
                    results.Add(new Result
                    {
                        Title    = _context.API.GetTranslation("flowlauncher_plugin_everything_query_error"),
                        SubTitle = e.Message,
                        Action   = _ =>
                        {
                            Clipboard.SetText(e.Message + "\r\n" + e.StackTrace);
                            _context.API.ShowMsg(_context.API.GetTranslation("flowlauncher_plugin_everything_copied"), null, string.Empty);
                            return(false);
                        },
                        IcoPath = "Images\\error.png"
                    });
                }
            }

            return(results);
        }
Ejemplo n.º 33
0
        public async Task UpdateApp(bool silentIfLatestVersion = true, bool updateToPrereleases = false)
        {
            try
            {
                using (UpdateManager updateManager = await GitHubUpdateManager(GitHubRepository, updateToPrereleases))
                {
                    UpdateInfo newUpdateInfo;
                    try
                    {
                        // UpdateApp CheckForUpdate will return value only if the app is squirrel installed
                        newUpdateInfo = await updateManager.CheckForUpdate().NonNull();
                    }
                    catch (Exception e) when(e is HttpRequestException || e is WebException || e is SocketException)
                    {
                        Logger.WoxError($"Check your connection and proxy settings to api.github.com.", e);
                        updateManager.Dispose();
                        return;
                    }

                    var newReleaseVersion = Version.Parse(newUpdateInfo.FutureReleaseEntry.Version.ToString());
                    var currentVersion    = Version.Parse(Constant.Version);

                    Logger.WoxInfo($"Future Release <{newUpdateInfo.FutureReleaseEntry.Formatted()}>");

                    if (newReleaseVersion <= currentVersion)
                    {
                        if (!silentIfLatestVersion)
                        {
                            MessageBox.Show("You already have the latest Wox version");
                        }
                        updateManager.Dispose();
                        return;
                    }

                    try
                    {
                        await updateManager.DownloadReleases(newUpdateInfo.ReleasesToApply);
                    }
                    catch (Exception e) when(e is HttpRequestException || e is WebException || e is SocketException)
                    {
                        Logger.WoxError($"Check your connection and proxy settings to github-cloud.s3.amazonaws.com.", e);
                        updateManager.Dispose();
                        return;
                    }

                    await updateManager.ApplyReleases(newUpdateInfo);

                    if (DataLocation.PortableDataLocationInUse())
                    {
                        var targetDestination = updateManager.RootAppDirectory + $"\\app-{newReleaseVersion.ToString()}\\{DataLocation.PortableFolderName}";
                        FilesFolders.Copy(DataLocation.PortableDataPath, targetDestination);
                        if (!FilesFolders.VerifyBothFolderFilesEqual(DataLocation.PortableDataPath, targetDestination))
                        {
                            MessageBox.Show(string.Format("Wox was not able to move your user profile data to the new update version. Please manually" +
                                                          "move your profile data folder from {0} to {1}", DataLocation.PortableDataPath, targetDestination));
                        }
                    }
                    else
                    {
                        await updateManager.CreateUninstallerRegistryEntry();
                    }

                    var newVersionTips = NewVersinoTips(newReleaseVersion.ToString());

                    MessageBox.Show(newVersionTips);
                    Logger.WoxInfo($"Update success:{newVersionTips}");
                }
            }
            catch (Exception e) when(e is HttpRequestException || e is WebException || e is SocketException)
            {
                Logger.WoxError($"Please check your connection and proxy settings to api.github.com.", e);
            }
        }