Flow.Launcher/Plugins/Flow.Launcher.Plugin.Folder/Main.cs

396 lines
14 KiB
C#
Raw Normal View History

using System;
2020-05-03 14:02:31 +00:00
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
2015-10-30 23:17:34 +00:00
using System.Windows.Controls;
2020-04-21 09:12:17 +00:00
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Storage;
using Flow.Launcher.Plugin.SharedCommands;
2020-04-21 09:12:17 +00:00
namespace Flow.Launcher.Plugin.Folder
2014-07-19 02:12:11 +00:00
{
2019-12-11 00:21:50 +00:00
public class Main : IPlugin, ISettingProvider, IPluginI18n, ISavable, IContextMenu
2014-07-19 02:12:11 +00:00
{
public const string FolderImagePath = "Images\\folder.png";
public const string FileImagePath = "Images\\file.png";
public const string DeleteFileFolderImagePath = "Images\\deletefilefolder.png";
public const string CopyImagePath = "Images\\copy.png";
private string DefaultFolderSubtitleString = "Ctrl + Enter to open the directory";
2016-06-16 01:59:31 +00:00
private static List<string> _driverNames;
private PluginInitContext _context;
private readonly Settings _settings;
2016-04-26 21:45:31 +00:00
private readonly PluginJsonStorage<Settings> _storage;
private IContextMenu _contextMenuLoader;
private static Dictionary<string, string> _envStringPaths;
2016-05-07 02:55:09 +00:00
public Main()
{
2016-04-26 21:45:31 +00:00
_storage = new PluginJsonStorage<Settings>();
_settings = _storage.Load();
}
public void Save()
{
_storage.Save();
}
2014-07-19 02:12:11 +00:00
public Control CreateSettingPanel()
{
2016-06-16 01:59:31 +00:00
return new FileSystemSettings(_context.API, _settings);
2014-07-19 02:12:11 +00:00
}
public void Init(PluginInitContext context)
2014-07-19 02:12:11 +00:00
{
2016-06-16 01:59:31 +00:00
_context = context;
_contextMenuLoader = new ContextMenuLoader(context);
2019-12-07 10:44:58 +00:00
InitialDriverList();
LoadEnvironmentStringPaths();
2014-07-19 02:12:11 +00:00
}
public List<Result> Query(Query query)
2014-07-19 02:12:11 +00:00
{
2019-12-07 10:44:58 +00:00
var results = GetUserFolderResults(query);
2014-07-19 02:12:11 +00:00
2019-12-07 10:44:58 +00:00
string search = query.Search.ToLower();
if (!IsDriveOrSharedFolder(search) && !IsEnvironmentVariableSearch(search))
{
2014-07-19 02:12:11 +00:00
return results;
}
2014-07-19 02:12:11 +00:00
if (IsEnvironmentVariableSearch(search))
{
results.AddRange(GetEnvironmentStringPathResults(search, query));
}
else
{
results.AddRange(QueryInternal_Directory_Exists(query.Search, query));
}
2014-07-19 02:12:11 +00:00
2019-12-07 10:44:58 +00:00
// todo why was this hack here?
2016-05-05 15:30:56 +00:00
foreach (var result in results)
{
result.Score += 10;
}
2014-07-19 02:12:11 +00:00
return results;
2016-05-20 18:19:32 +00:00
}
2019-12-07 10:44:58 +00:00
private static bool IsEnvironmentVariableSearch(string search)
{
return _envStringPaths != null && search.StartsWith("%");
}
2019-12-10 10:38:03 +00:00
private static bool IsDriveOrSharedFolder(string search)
{
if (search.StartsWith(@"\\"))
{ // shared folder
return true;
}
2019-12-10 10:38:03 +00:00
if (_driverNames != null && _driverNames.Any(search.StartsWith))
{ // normal drive letter
return true;
}
if (_driverNames == null && search.Length > 2 && char.IsLetter(search[0]) && search[1] == ':')
{ // when we don't have the drive letters we can try...
return true; // we don't know so let's give it the possibility
}
return false;
}
private Result CreateFolderResult(string title, string subtitle, string path, Query query)
2019-12-07 10:44:58 +00:00
{
return new Result
{
Title = title,
IcoPath = path,
SubTitle = subtitle,
TitleHighlightData = StringMatcher.FuzzySearch(query.Search, title).MatchData,
2019-12-07 10:44:58 +00:00
Action = c =>
{
if (c.SpecialKeyState.CtrlPressed)
{
try
{
2020-04-29 08:58:52 +00:00
FilesFolders.OpenPath(path);
2019-12-07 10:44:58 +00:00
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);
2019-12-07 10:44:58 +00:00
return false;
2019-12-11 00:21:50 +00:00
},
ContextData = new SearchResult { Type = ResultType.Folder, FullPath = path }
2019-12-07 10:44:58 +00:00
};
}
private List<Result> GetUserFolderResults(Query query)
{
string search = query.Search.ToLower();
var userFolderLinks = _settings.FolderLinks.Where(
x => x.Nickname.StartsWith(search, StringComparison.OrdinalIgnoreCase));
var results = userFolderLinks.Select(item =>
CreateFolderResult(item.Nickname, DefaultFolderSubtitleString, item.Path, query)).ToList();
2019-12-07 10:44:58 +00:00
return results;
}
2016-05-20 18:19:32 +00:00
private void InitialDriverList()
2014-07-19 02:12:11 +00:00
{
2016-06-16 01:59:31 +00:00
if (_driverNames == null)
2014-07-19 02:12:11 +00:00
{
2016-06-16 01:59:31 +00:00
_driverNames = new List<string>();
2019-12-07 10:44:58 +00:00
var allDrives = DriveInfo.GetDrives();
2014-07-19 02:12:11 +00:00
foreach (DriveInfo driver in allDrives)
{
2016-06-16 01:59:31 +00:00
_driverNames.Add(driver.Name.ToLower().TrimEnd('\\'));
2014-07-19 02:12:11 +00:00
}
}
}
private void LoadEnvironmentStringPaths()
{
_envStringPaths = new Dictionary<string, string>();
2020-05-03 14:01:38 +00:00
foreach (DictionaryEntry special in Environment.GetEnvironmentVariables())
{
2020-05-03 14:01:38 +00:00
if (Directory.Exists(special.Value.ToString()))
{
_envStringPaths.Add(special.Key.ToString().ToLower(), special.Value.ToString());
}
}
}
2019-12-07 10:44:58 +00:00
private static readonly char[] _specialSearchChars = new char[]
{
'?', '*', '>'
};
private List<Result> QueryInternal_Directory_Exists(string search, Query query)
2014-07-19 02:12:11 +00:00
{
var results = new List<Result>();
2019-12-07 10:44:58 +00:00
var hasSpecial = search.IndexOfAny(_specialSearchChars) >= 0;
2015-08-23 07:40:18 +00:00
string incompleteName = "";
2019-12-07 10:44:58 +00:00
if (hasSpecial || !Directory.Exists(search + "\\"))
2015-08-23 07:40:18 +00:00
{
2019-12-07 10:44:58 +00:00
// if folder doesn't exist, we want to take the last part and use it afterwards to help the user
// find the right folder.
2016-05-20 18:19:32 +00:00
int index = search.LastIndexOf('\\');
if (index > 0 && index < (search.Length - 1))
2015-08-23 07:40:18 +00:00
{
2019-12-07 10:44:58 +00:00
incompleteName = search.Substring(index + 1).ToLower();
2016-05-20 18:19:32 +00:00
search = search.Substring(0, index + 1);
if (!Directory.Exists(search))
{
2015-08-23 07:40:18 +00:00
return results;
}
2015-08-23 07:40:18 +00:00
}
else
{
2015-08-23 07:40:18 +00:00
return results;
}
2015-08-23 07:40:18 +00:00
}
else
{
// folder exist, add \ at the end of doesn't exist
2016-05-20 18:19:32 +00:00
if (!search.EndsWith("\\"))
{
2016-05-20 18:19:32 +00:00
search += "\\";
}
2015-08-23 07:40:18 +00:00
}
2014-07-19 02:12:11 +00:00
2019-12-07 10:44:58 +00:00
results.Add(CreateOpenCurrentFolderResult(incompleteName, search));
var searchOption = SearchOption.TopDirectoryOnly;
2019-12-07 10:44:58 +00:00
incompleteName += "*";
2014-07-19 02:12:11 +00:00
// give the ability to search all folder when starting with >
if (incompleteName.StartsWith(">"))
2014-07-19 02:12:11 +00:00
{
2019-12-07 10:44:58 +00:00
searchOption = SearchOption.AllDirectories;
// match everything before and after search term using supported wildcard '*', ie. *searchterm*
incompleteName = "*" + incompleteName.Substring(1);
2019-12-07 10:44:58 +00:00
}
var folderList = new List<Result>();
var fileList = new List<Result>();
var folderSubtitleString = DefaultFolderSubtitleString;
try
{
// search folder and add results
var directoryInfo = new DirectoryInfo(search);
var fileSystemInfos = directoryInfo.GetFileSystemInfos(incompleteName, searchOption);
foreach (var fileSystemInfo in fileSystemInfos)
{
if ((fileSystemInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) continue;
2014-07-19 02:12:11 +00:00
if(fileSystemInfo is DirectoryInfo)
{
if (searchOption == SearchOption.AllDirectories)
folderSubtitleString = fileSystemInfo.FullName;
folderList.Add(CreateFolderResult(fileSystemInfo.Name, folderSubtitleString, fileSystemInfo.FullName, query));
}
else
{
fileList.Add(CreateFileResult(fileSystemInfo.FullName, query));
}
}
}
catch (Exception e)
2019-12-07 10:44:58 +00:00
{
if (e is UnauthorizedAccessException || e is ArgumentException)
{
results.Add(new Result { Title = e.Message, Score = 501 });
return results;
}
2019-12-07 10:44:58 +00:00
throw;
2014-07-19 02:12:11 +00:00
}
// 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();
2019-12-07 10:44:58 +00:00
}
private List<Result> GetEnvironmentStringPathSuggestions(string search, Query query)
{
var results = new List<Result>();
foreach (var p in _envStringPaths)
{
if (p.Key.StartsWith(search))
{
results.Add(CreateFolderResult($"%{p.Key}%", p.Value, p.Value, query));
}
}
return results;
}
private List<Result> GetEnvironmentStringPathResults(string envStringSearch, Query query)
{
if (envStringSearch == "%")
{ // return all environment string options as path suggestions
return GetEnvironmentStringPathSuggestions("", query);
}
var results = new List<Result>();
var search = envStringSearch.Substring(1);
if (search.EndsWith("%") && search.Length > 1)
{ // query starts and ends with a %, find an exact match from env-string paths
var exactEnvStringPath = search.Substring(0, search.Length-1);
if (_envStringPaths.ContainsKey(exactEnvStringPath))
{
var expandedPath = _envStringPaths[exactEnvStringPath];
results.Add(CreateFolderResult($"%{exactEnvStringPath}%", expandedPath, expandedPath, query));
}
}
else if (search.Contains("%"))
{ // query starts with a % and contains another % somewhere before the end
var splitSearch = search.Split("%");
var exactEnvStringPath = splitSearch[0];
// if there are more than 2 % characters in the query, don't bother
if (splitSearch.Length == 2 && _envStringPaths.ContainsKey(exactEnvStringPath))
{
var queryPartToReplace = $"%{exactEnvStringPath}%";
var expandedPath = _envStringPaths[exactEnvStringPath];
// replace the %envstring% part of the query with its expanded equivalent
var updatedSearch = envStringSearch.Replace(queryPartToReplace, expandedPath);
results.AddRange(QueryInternal_Directory_Exists(updatedSearch, query));
}
}
else
{ // query simply starts wtih a %, suggest env-string paths that match the rest of the search
results.AddRange(GetEnvironmentStringPathSuggestions(search, query));
}
return results;
}
private static Result CreateFileResult(string filePath, Query query)
2019-12-07 10:44:58 +00:00
{
var result = new Result
2014-07-19 02:12:11 +00:00
{
2019-12-07 10:44:58 +00:00
Title = Path.GetFileName(filePath),
SubTitle = filePath,
2019-12-07 10:44:58 +00:00
IcoPath = filePath,
TitleHighlightData = StringMatcher.FuzzySearch(query.Search, Path.GetFileName(filePath)).MatchData,
2019-12-07 10:44:58 +00:00
Action = c =>
2014-07-19 02:12:11 +00:00
{
2019-12-07 10:44:58 +00:00
try
2014-07-19 02:12:11 +00:00
{
2020-04-29 08:58:52 +00:00
FilesFolders.OpenPath(filePath);
2019-12-07 10:44:58 +00:00
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Could not start " + filePath);
2014-07-19 02:12:11 +00:00
}
2019-12-07 10:44:58 +00:00
return true;
2019-12-11 00:21:50 +00:00
},
ContextData = new SearchResult { Type = ResultType.File, FullPath = filePath}
2019-12-07 10:44:58 +00:00
};
return result;
}
2014-07-19 02:12:11 +00:00
2019-12-07 10:44:58 +00:00
private static Result CreateOpenCurrentFolderResult(string incompleteName, string search)
{
2019-12-09 10:27:33 +00:00
var firstResult = "Open current directory";
2019-12-07 10:44:58 +00:00
if (incompleteName.Length > 0)
firstResult = "Open " + search;
2019-12-09 10:27:33 +00:00
var folderName = search.TrimEnd('\\').Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.None).Last();
2019-12-07 10:44:58 +00:00
return new Result
{
Title = firstResult,
2019-12-09 10:27:33 +00:00
SubTitle = $"Use > to search files and subfolders within {folderName}, " +
$"* to search for file extensions in {folderName} or both >* to combine the search",
2019-12-07 10:44:58 +00:00
IcoPath = search,
Score = 500,
2019-12-07 10:44:58 +00:00
Action = c =>
{
2020-04-29 08:58:52 +00:00
FilesFolders.OpenPath(search);
2019-12-07 10:44:58 +00:00
return true;
}
};
2014-07-19 02:12:11 +00:00
}
2015-01-07 10:59:55 +00:00
2015-02-07 12:17:49 +00:00
public string GetTranslatedPluginTitle()
{
2020-04-21 12:54:41 +00:00
return _context.API.GetTranslation("flowlauncher_plugin_folder_plugin_name");
2015-02-07 12:17:49 +00:00
}
public string GetTranslatedPluginDescription()
{
2020-04-21 12:54:41 +00:00
return _context.API.GetTranslation("flowlauncher_plugin_folder_plugin_description");
2015-02-07 12:17:49 +00:00
}
2019-12-11 00:21:50 +00:00
public List<Result> LoadContextMenus(Result selectedResult)
{
return _contextMenuLoader.LoadContextMenus(selectedResult);
}
2014-07-19 02:12:11 +00:00
}
}