Cleaned FileSystemPlugin + Enhanced

THIS NEEDS TESTING!
This commit is contained in:
Aaron Campf 2014-05-09 18:24:16 -07:00
parent 498634fd13
commit 81467a86cc
9 changed files with 626 additions and 718 deletions

View File

@ -8,319 +8,246 @@ using System.Threading;
using System.Windows.Forms;
using Newtonsoft.Json;
namespace Wox.Plugin.PluginManagement
{
public class WoxPlugin
{
public int apiVersion { get; set; }
public List<WoxPluginResult> result { get; set; }
}
namespace Wox.Plugin.PluginManagement {
public class WoxPlugin {
public int apiVersion { get; set; }
public List<WoxPluginResult> result { get; set; }
}
public class WoxPluginResult
{
public string actionkeyword;
public string download;
public string author;
public string description;
public string id;
public int star;
public string name;
public string version;
public string website;
}
public class WoxPluginResult {
public string actionkeyword;
public string download;
public string author;
public string description;
public string id;
public int star;
public string name;
public string version;
public string website;
}
public class Main : IPlugin
{
private static string PluginPath = AppDomain.CurrentDomain.BaseDirectory + "Plugins";
private static string PluginConfigName = "plugin.json";
private static string pluginSearchUrl = "http://www.getwox.com/api/plugin/search/";
private PluginInitContext context;
public class Main : IPlugin {
private static string PluginPath = AppDomain.CurrentDomain.BaseDirectory + "Plugins";
private static string PluginConfigName = "plugin.json";
private static string pluginSearchUrl = "http://www.getwox.com/api/plugin/search/";
private PluginInitContext context;
public List<Result> Query(Query query)
{
List<Result> results = new List<Result>();
if (query.ActionParameters.Count == 0)
{
results.Add(new Result()
{
Title = "wpm install <pluginName>",
SubTitle = "search and install wox plugins",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm install ");
return false;
}
});
results.Add(new Result()
{
Title = "wpm uninstall <pluginName>",
SubTitle = "uninstall plugin",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm uninstall ");
return false;
}
});
results.Add(new Result()
{
Title = "wpm list",
SubTitle = "list plugins installed",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm list");
return false;
}
});
return results;
}
public List<Result> Query(Query query) {
List<Result> results = new List<Result>();
if (query.ActionParameters.Count == 0) {
results.Add(new Result("wpm install <pluginName>", "Images\\plugin.png", "search and install wox plugins") {
Action = e => {
context.ChangeQuery("wpm install ");
return false;
}
});
results.Add(new Result("wpm uninstall <pluginName>", "Images\\plugin.png", "uninstall plugin") {
Action = e => {
context.ChangeQuery("wpm uninstall ");
return false;
}
});
results.Add(new Result("wpm list", "Images\\plugin.png", "list plugins installed") {
Action = e => {
context.ChangeQuery("wpm list");
return false;
}
});
return results;
}
if (query.ActionParameters.Count > 0)
{
bool hit = false;
switch (query.ActionParameters[0].ToLower())
{
case "list":
hit = true;
results = ListInstalledPlugins();
break;
if (query.ActionParameters.Count > 0) {
bool hit = false;
switch (query.ActionParameters[0].ToLower()) {
case "list":
hit = true;
results = ListInstalledPlugins();
break;
case "uninstall":
hit = true;
results = ListUnInstalledPlugins(query);
break;
case "uninstall":
hit = true;
results = ListUnInstalledPlugins(query);
break;
case "install":
hit = true;
if (query.ActionParameters.Count > 1)
{
results = InstallPlugin(query);
}
break;
}
case "install":
hit = true;
if (query.ActionParameters.Count > 1) {
results = InstallPlugin(query);
}
break;
}
if (!hit)
{
if ("install".Contains(query.ActionParameters[0].ToLower()))
{
results.Add(new Result()
{
Title = "wpm install <pluginName>",
SubTitle = "search and install wox plugins",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm install ");
return false;
}
});
}
if ("uninstall".Contains(query.ActionParameters[0].ToLower()))
{
results.Add(new Result()
{
Title = "wpm uninstall <pluginName>",
SubTitle = "uninstall plugin",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm uninstall ");
return false;
}
});
}
if ("list".Contains(query.ActionParameters[0].ToLower()))
{
results.Add(new Result()
{
Title = "wpm list",
SubTitle = "list plugins installed",
IcoPath = "Images\\plugin.png",
Action = e =>
{
context.ChangeQuery("wpm list");
return false;
}
});
}
}
}
if (!hit) {
if ("install".Contains(query.ActionParameters[0].ToLower())) {
results.Add(new Result("wpm install <pluginName>", "Images\\plugin.png", "search and install wox plugins") {
Action = e => {
context.ChangeQuery("wpm install ");
return false;
}
});
}
if ("uninstall".Contains(query.ActionParameters[0].ToLower())) {
results.Add(new Result("wpm uninstall <pluginName>", "Images\\plugin.png", "uninstall plugin") {
Action = e => {
context.ChangeQuery("wpm uninstall ");
return false;
}
});
}
if ("list".Contains(query.ActionParameters[0].ToLower())) {
results.Add(new Result("wpm list", "Images\\plugin.png", "list plugins installed") {
Action = e => {
context.ChangeQuery("wpm list");
return false;
}
});
}
}
}
return results;
}
return results;
}
private List<Result> InstallPlugin(Query query)
{
List<Result> results = new List<Result>();
HttpWebResponse response = HttpRequest.CreateGetHttpResponse(pluginSearchUrl + query.ActionParameters[1], null, null, null);
Stream s = response.GetResponseStream();
if (s != null)
{
StreamReader reader = new StreamReader(s, Encoding.UTF8);
string json = reader.ReadToEnd();
WoxPlugin o = JsonConvert.DeserializeObject<WoxPlugin>(json);
foreach (WoxPluginResult r in o.result)
{
WoxPluginResult r1 = r;
results.Add(new Result()
{
Title = r.name,
SubTitle = r.description,
IcoPath = "Images\\plugin.png",
Action = e =>
{
DialogResult result = MessageBox.Show("Are your sure to install " + r.name + " plugin",
"Install plugin", MessageBoxButtons.YesNo);
private List<Result> InstallPlugin(Query query) {
List<Result> results = new List<Result>();
HttpWebResponse response = HttpRequest.CreateGetHttpResponse(pluginSearchUrl + query.ActionParameters[1], null, null, null);
Stream s = response.GetResponseStream();
if (s != null) {
StreamReader reader = new StreamReader(s, Encoding.UTF8);
string json = reader.ReadToEnd();
WoxPlugin o = JsonConvert.DeserializeObject<WoxPlugin>(json);
foreach (WoxPluginResult r in o.result) {
WoxPluginResult r1 = r;
results.Add(new Result() {
Title = r.name,
SubTitle = r.description,
IcoPath = "Images\\plugin.png",
Action = e => {
DialogResult result = MessageBox.Show("Are your sure to install " + r.name + " plugin",
"Install plugin", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
string folder = Path.Combine(Path.GetTempPath(), "WoxPluginDownload");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
string filePath = Path.Combine(folder, Guid.NewGuid().ToString() + ".wox");
if (result == DialogResult.Yes) {
string folder = Path.Combine(Path.GetTempPath(), "WoxPluginDownload");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
string filePath = Path.Combine(folder, Guid.NewGuid().ToString() + ".wox");
context.StartLoadingBar();
ThreadPool.QueueUserWorkItem(delegate
{
using (WebClient Client = new WebClient())
{
try
{
Client.DownloadFile(r1.download, filePath);
context.InstallPlugin(filePath);
context.ReloadPlugins();
}
catch (Exception exception)
{
MessageBox.Show("download plugin " + r.name + "failed. " + exception.Message);
}
finally
{
context.StopLoadingBar();
}
}
});
}
return false;
}
});
}
}
return results;
}
context.StartLoadingBar();
ThreadPool.QueueUserWorkItem(delegate {
using (WebClient Client = new WebClient()) {
try {
Client.DownloadFile(r1.download, filePath);
context.InstallPlugin(filePath);
context.ReloadPlugins();
}
catch (Exception exception) {
MessageBox.Show("download plugin " + r.name + "failed. " + exception.Message);
}
finally {
context.StopLoadingBar();
}
}
});
}
return false;
}
});
}
}
return results;
}
private List<Result> ListUnInstalledPlugins(Query query)
{
List<Result> results = new List<Result>();
List<PluginMetadata> allInstalledPlugins = ParseThirdPartyPlugins();
if (query.ActionParameters.Count > 1)
{
string pluginName = query.ActionParameters[1];
allInstalledPlugins =
allInstalledPlugins.Where(o => o.Name.ToLower().Contains(pluginName.ToLower())).ToList();
}
private List<Result> ListUnInstalledPlugins(Query query) {
List<Result> results = new List<Result>();
List<PluginMetadata> allInstalledPlugins = ParseThirdPartyPlugins();
if (query.ActionParameters.Count > 1) {
string pluginName = query.ActionParameters[1];
allInstalledPlugins =
allInstalledPlugins.Where(o => o.Name.ToLower().Contains(pluginName.ToLower())).ToList();
}
foreach (PluginMetadata plugin in allInstalledPlugins)
{
results.Add(new Result()
{
Title = plugin.Name,
SubTitle = plugin.Description,
IcoPath = "Images\\plugin.png",
Action = e =>
{
UnInstalledPlugins(plugin);
return false;
}
});
}
return results;
}
foreach (PluginMetadata plugin in allInstalledPlugins) {
results.Add(new Result() {
Title = plugin.Name,
SubTitle = plugin.Description,
IcoPath = "Images\\plugin.png",
Action = e => {
UnInstalledPlugins(plugin);
return false;
}
});
}
return results;
}
private void UnInstalledPlugins(PluginMetadata plugin)
{
string content = string.Format("Do you want to uninstall following plugin?\r\n\r\nName: {0}\r\nVersion: {1}\r\nAuthor: {2}", plugin.Name, plugin.Version, plugin.Author);
if (MessageBox.Show(content, "Wox", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
File.Create(Path.Combine(plugin.PluginDirecotry, "NeedDelete.txt")).Close();
MessageBox.Show("This plugin has been removed, restart Wox to take effect");
}
}
private void UnInstalledPlugins(PluginMetadata plugin) {
string content = string.Format("Do you want to uninstall following plugin?\r\n\r\nName: {0}\r\nVersion: {1}\r\nAuthor: {2}", plugin.Name, plugin.Version, plugin.Author);
if (MessageBox.Show(content, "Wox", MessageBoxButtons.YesNo) == DialogResult.Yes) {
File.Create(Path.Combine(plugin.PluginDirecotry, "NeedDelete.txt")).Close();
MessageBox.Show("This plugin has been removed, restart Wox to take effect");
}
}
private List<Result> ListInstalledPlugins()
{
List<Result> results = new List<Result>();
foreach (PluginMetadata plugin in ParseThirdPartyPlugins())
{
results.Add(new Result()
{
Title = plugin.Name + " - " + plugin.ActionKeyword,
SubTitle = plugin.Description,
IcoPath = "Images\\plugin.png"
});
}
return results;
}
private List<Result> ListInstalledPlugins() {
List<Result> results = new List<Result>();
foreach (PluginMetadata plugin in ParseThirdPartyPlugins()) {
results.Add(new Result() {
Title = plugin.Name + " - " + plugin.ActionKeyword,
SubTitle = plugin.Description,
IcoPath = "Images\\plugin.png"
});
}
return results;
}
private static List<PluginMetadata> ParseThirdPartyPlugins()
{
List<PluginMetadata> pluginMetadatas = new List<PluginMetadata>();
if (!Directory.Exists(PluginPath))
Directory.CreateDirectory(PluginPath);
private static List<PluginMetadata> ParseThirdPartyPlugins() {
List<PluginMetadata> pluginMetadatas = new List<PluginMetadata>();
if (!Directory.Exists(PluginPath))
Directory.CreateDirectory(PluginPath);
string[] directories = Directory.GetDirectories(PluginPath);
foreach (string directory in directories)
{
PluginMetadata metadata = GetMetadataFromJson(directory);
if (metadata != null) pluginMetadatas.Add(metadata);
}
string[] directories = Directory.GetDirectories(PluginPath);
foreach (string directory in directories) {
PluginMetadata metadata = GetMetadataFromJson(directory);
if (metadata != null) pluginMetadatas.Add(metadata);
}
return pluginMetadatas;
}
return pluginMetadatas;
}
private static PluginMetadata GetMetadataFromJson(string pluginDirectory)
{
string configPath = Path.Combine(pluginDirectory, PluginConfigName);
PluginMetadata metadata;
private static PluginMetadata GetMetadataFromJson(string pluginDirectory) {
string configPath = Path.Combine(pluginDirectory, PluginConfigName);
PluginMetadata metadata;
if (!File.Exists(configPath))
{
return null;
}
if (!File.Exists(configPath)) {
return null;
}
try
{
metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath));
metadata.PluginType = PluginType.ThirdParty;
metadata.PluginDirecotry = pluginDirectory;
}
catch (Exception)
{
string error = string.Format("Parse plugin config {0} failed: json format is not valid", configPath);
return null;
}
try {
metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath));
metadata.PluginType = PluginType.ThirdParty;
metadata.PluginDirecotry = pluginDirectory;
}
catch (Exception) {
string error = string.Format("Parse plugin config {0} failed: json format is not valid", configPath);
return null;
}
if (!AllowedLanguage.IsAllowed(metadata.Language))
{
string error = string.Format("Parse plugin config {0} failed: invalid language {1}", configPath,
metadata.Language);
return null;
}
if (!File.Exists(metadata.ExecuteFilePath))
{
string error = string.Format("Parse plugin config {0} failed: ExecuteFile {1} didn't exist", configPath,
metadata.ExecuteFilePath);
return null;
}
if (!AllowedLanguage.IsAllowed(metadata.Language)) {
string error = string.Format("Parse plugin config {0} failed: invalid language {1}", configPath,
metadata.Language);
return null;
}
if (!File.Exists(metadata.ExecuteFilePath)) {
string error = string.Format("Parse plugin config {0} failed: ExecuteFile {1} didn't exist", configPath,
metadata.ExecuteFilePath);
return null;
}
return metadata;
}
return metadata;
}
public void Init(PluginInitContext context)
{
this.context = context;
}
}
public void Init(PluginInitContext context) {
this.context = context;
}
}
}

View File

@ -88,7 +88,8 @@ namespace Python.Runtime {
PyTrue = Runtime.PyObject_GetAttrString(op, "True");
PyFalse = Runtime.PyObject_GetAttrString(op, "False");
PyBoolType = Runtime.PyObject_Type(PyTrue);
PyBoolType = Runtime.PyObject_Type(PyTrue);> Python.Runtime.Runtime.Initialize() C#
PyNoneType = Runtime.PyObject_Type(PyNone);
PyTypeType = Runtime.PyObject_Type(PyNoneType);

View File

@ -3,139 +3,82 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Wox.Infrastructure;
using Wox.Infrastructure.Storage.UserSettings;
namespace Wox.Plugin.SystemPlugins.FileSystem {
public class FileSystemPlugin : BaseSystemPlugin, ISettingProvider {
#region Properties
private PluginInitContext context;
private static List<string> driverNames = null;
private static Dictionary<string, DirectoryInfo[]> parentDirectories = new Dictionary<string, DirectoryInfo[]>();
public override string Description { get { return base.Description; } }
public override string Name { get { return "File System"; } }
public override string IcoPath { get { return @"Images\folder.png"; } }
#endregion Properties
#region Misc
protected override void InitInternal(PluginInitContext context) {
this.context = context;
if (UserSettingStorage.Instance.FolderLinks == null) {
UserSettingStorage.Instance.FolderLinks = new List<FolderLink>();
UserSettingStorage.Instance.Save();
}
}
public System.Windows.Controls.Control CreateSettingPanel() {
return new FileSystemSettings();
}
#endregion Misc
protected override List<Result> QueryInternal(Query query) {
#region 1
//TODO: Consider always clearing the cache
List<Result> results = new List<Result>();
if (string.IsNullOrEmpty(query.RawQuery)) {
// clear the cache
if (parentDirectories.Count > 0)
parentDirectories.Clear();
//if (string.IsNullOrEmpty(query.RawQuery)) {
// // clear the cache
// if (parentDirectories.Count > 0) parentDirectories.Clear();
// return results;
//}
return results;
}
InitialDriverList();
#endregion 1
var input = query.RawQuery.ToLower();
var inputName = input.Split(new string[] { @"\" }, StringSplitOptions.None).First().ToLower();
var link = UserSettingStorage.Instance.FolderLinks.FirstOrDefault(x => x.Nickname.Equals(inputName, StringComparison.OrdinalIgnoreCase));
var currentPath = link == null ? input : link.Path + input.Remove(0, inputName.Length);
var link = UserSettingStorage.Instance.FolderLinks.FirstOrDefault(x =>
x.Nickname.Equals(inputName, StringComparison.OrdinalIgnoreCase));
var currentPath = link != null ? link.Path : null;
InitialDriverList();
foreach (var item in UserSettingStorage.Instance.FolderLinks) {
var Name = item.Nickname;
if (Name.StartsWith(input, StringComparison.OrdinalIgnoreCase) && Name.Length != input.Length) {
Result result = new Result {
Title = Name,
IcoPath = "Images/folder.png",
Action = (c) => {
context.ChangeQuery(item.Nickname);
return false;
}
};
results.Add(result);
}
foreach (var item in UserSettingStorage.Instance.FolderLinks.Where(x => x.Nickname.StartsWith(input, StringComparison.OrdinalIgnoreCase))) {
//if (item.Nickname.StartsWith(input, StringComparison.OrdinalIgnoreCase)) { //&& item.Nickname.Length != input.Length) {
results.Add(new Result(item.Nickname, "Images/folder.png") {
Action = (c) => {
context.ChangeQuery(item.Nickname);
return false;
}
});
//}
}
if (currentPath == null) {
if (!driverNames.Any(input.StartsWith))
return results;
if (link == null && !driverNames.Any(input.StartsWith))
return results;
currentPath = input;
}
else
currentPath += input.Remove(0, inputName.Length);
QueryInternal_Directory_Exists(currentPath, input, results);
if (Directory.Exists(currentPath)) {
// show all child directory
if (input.EndsWith("\\") || input.EndsWith("/")) {
var dirInfo = new DirectoryInfo(currentPath);
var dirs = dirInfo.GetDirectories();
var parentDirKey = input.TrimEnd('\\', '/');
if (!parentDirectories.ContainsKey(parentDirKey))
parentDirectories.Add(parentDirKey, dirs);
foreach (var dir in dirs) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
continue;
var dirPath = dir.FullName;
Result result = new Result {
Title = dir.Name,
IcoPath = "Images/folder.png",
Action = (c) => {
context.ChangeQuery(dirPath);
return false;
}
};
results.Add(result);
}
if (results.Count == 0) {
Result result = new Result {
Title = "Open this directory",
SubTitle = "No files in this directory",
IcoPath = "Images/folder.png",
Action = (c) => {
Process.Start(currentPath);
return true;
}
};
results.Add(result);
}
foreach (var dir in dirInfo.GetFiles()) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
continue;
var dirPath = dir.FullName;
Result result = new Result {
Title = global::System.IO.Path.GetFileNameWithoutExtension(dirPath),
IcoPath = dirPath,
Action = (c) => {
try {
Process.Start(dirPath);
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Could not start " + dir.Name);
}
return true;
}
};
results.Add(result);
}
}
else {
Result result = new Result {
Title = "Open this directory",
SubTitle = string.Format("path: {0}", currentPath),
Score = 50,
IcoPath = "Images/folder.png",
Action = (c) => {
Process.Start(currentPath);
return true;
}
};
results.Add(result);
}
}
return results;
/*
// change to search in current directory
string parentDir = null;
try {
@ -143,38 +86,37 @@ namespace Wox.Plugin.SystemPlugins.FileSystem {
}
catch { }
return results;
if (!string.IsNullOrEmpty(parentDir) && results.Count == 0) {
parentDir = parentDir.TrimEnd('\\', '/');
if (parentDirectories.ContainsKey(parentDir)) {
//TODO: Why are we doing the following check
var dirs = parentDirectories[parentDir];
var queryFileName = Path.GetFileName(currentPath).ToLower();
var fuzzy = FuzzyMatcher.Create(queryFileName);
foreach (var dir in dirs) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
continue;
//FUCK THIS CODE o.O!!!!!!!
if (parentDirectories.ContainsKey(parentDir)) {
var fuzzy = FuzzyMatcher.Create(Path.GetFileName(currentPath).ToLower());
foreach (var dir in parentDirectories[parentDir]) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) continue;
var matchResult = fuzzy.Evaluate(dir.Name);
if (!matchResult.Success)
continue;
if (!matchResult.Success) continue;
var dirPath = dir.FullName;
Result result = new Result {
Title = dir.Name,
IcoPath = "Images/folder.png",
results.Add(new Result(dir.Name, "Images/folder.png") {
Score = matchResult.Score,
Action = (c) => {
context.ChangeQuery(dirPath);
context.ChangeQuery(dir.FullName);
return false;
}
};
results.Add(result);
});
}
}
}
return results;
*/
}
private void InitialDriverList() {
@ -187,30 +129,103 @@ namespace Wox.Plugin.SystemPlugins.FileSystem {
}
}
protected override void InitInternal(PluginInitContext context) {
this.context = context;
private void QueryInternal_Directory_Exists(string currentPath, string input, List<Result> results) {
string path = Directory.Exists(currentPath) ? new DirectoryInfo(currentPath).FullName : Path.GetDirectoryName(input);
if (UserSettingStorage.Instance.FolderLinks == null) {
UserSettingStorage.Instance.FolderLinks = new List<FolderLink>();
UserSettingStorage.Instance.Save();
if (path != null) {
var dirs = new DirectoryInfo(path).GetDirectories();
var parentDirKey = input.TrimEnd('\\', '/');
if (!parentDirectories.ContainsKey(parentDirKey)) parentDirectories.Add(parentDirKey, dirs);
var fuzzy = FuzzyMatcher.Create(Path.GetFileName(currentPath).ToLower());
foreach (var dir in dirs) { //.Where(x => (x.Attributes & FileAttributes.Hidden) != 0)) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) continue;
var result = new Result(dir.Name, "Images/folder.png") {
Action = (c) => {
context.ChangeQuery(dir.FullName);
return false;
}
};
if (Path.GetFileName(currentPath).ToLower() != "") {
var matchResult = fuzzy.Evaluate(dir.Name);
result.Score = matchResult.Score;
if (!matchResult.Success) continue;
}
results.Add(result);
}
//if (results.Count == 0) {
// results.Add(new Result("Open this directory", "Images/folder.png", "No files in this directory") {
// Action = (c) => {
// Process.Start(currentPath);
// return true;
// }
// });
//}
}
else {
//results.Add(new Result("Open this directory", "Images/folder.png", string.Format("path: {0}", currentPath)) {
// Score = 50,
// Action = (c) => {
// Process.Start(currentPath);
// return true;
// }
//});
}
}
public override string Name {
get { return "File System"; }
}
public override string IcoPath {
get { return @"Images\folder.png"; }
}
public System.Windows.Controls.Control CreateSettingPanel() {
return new FileSystemSettings();
}
/**************************************************************/
/**************************************************************/
public override string Description {
get { return base.Description; }
if (results.Count == 0) {
results.Add(new Result("Open this directory", "Images/folder.png", "No files in this directory") {
Action = (c) => {
Process.Start(currentPath);
return true;
}
});
}
/**************************************************************/
/**************************************************************/
var Folder = Path.GetDirectoryName(currentPath);
if (Folder != null) {
var dirInfo1 = new DirectoryInfo(Folder);
var fuzzy = FuzzyMatcher.Create(Path.GetFileName(currentPath).ToLower());
foreach (var dir in dirInfo1.GetFiles()) { //.Where(x => (x.Attributes & FileAttributes.Hidden) != 0)) {
if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) continue;
var dirPath = dir.FullName;
Result result = new Result(System.IO.Path.GetFileNameWithoutExtension(dirPath), dirPath) {
Action = (c) => {
try {
Process.Start(dirPath);
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Could not start " + dir.Name);
}
return true;
}
};
if (Path.GetFileName(currentPath).ToLower() != "") {
var matchResult = fuzzy.Evaluate(dir.Name);
result.Score = matchResult.Score;
if (!matchResult.Success) continue;
}
results.Add(result);
}
}
}
}
}

View File

@ -2,47 +2,56 @@
using System.Collections;
using System.Collections.Generic;
namespace Wox.Plugin
{
public class Result
{
public string Title { get; set; }
public string SubTitle { get; set; }
public string IcoPath { get; set; }
namespace Wox.Plugin {
public class Result {
public string Title { get; set; }
public string SubTitle { get; set; }
public string IcoPath { get; set; }
/// <summary>
/// return true to hide wox after select result
/// </summary>
public Func<ActionContext,bool> Action { get; set; }
public int Score { get; set; }
/// <summary>
/// return true to hide wox after select result
/// </summary>
public Func<ActionContext, bool> Action { get; set; }
public int Score { get; set; }
/// <summary>
/// Auto add scores for MRU items
/// </summary>
public bool AutoAjustScore { get; set; }
/// <summary>
/// Auto add scores for MRU items
/// </summary>
public bool AutoAjustScore { get; set; }
//todo: this should be controlled by system, not visible to users
/// <summary>
/// Only resulsts that originQuery match with curren query will be displayed in the panel
/// </summary>
public Query OriginQuery { get; set; }
//todo: this should be controlled by system, not visible to users
/// <summary>
/// Only resulsts that originQuery match with curren query will be displayed in the panel
/// </summary>
public Query OriginQuery { get; set; }
/// <summary>
/// Don't set this property if you are developing a plugin
/// </summary>
public string PluginDirectory { get; set; }
/// <summary>
/// Don't set this property if you are developing a plugin
/// </summary>
public string PluginDirectory { get; set; }
public new bool Equals(object obj)
{
if (obj == null || !(obj is Result)) return false;
public new bool Equals(object obj) {
if (obj == null || !(obj is Result)) return false;
Result r = (Result)obj;
return r.Title == Title && r.SubTitle == SubTitle;
}
Result r = (Result)obj;
return r.Title == Title && r.SubTitle == SubTitle;
}
public override string ToString()
{
return Title + SubTitle;
}
}
public override string ToString() {
return Title + SubTitle;
}
public Result() {
}
public Result(string Title = null, string IcoPath = null, string SubTitle = null) {
this.Title = Title;
this.IcoPath = IcoPath;
this.SubTitle = SubTitle;
}
}
}

View File

@ -18,114 +18,98 @@ using MessageBoxOptions = System.Windows.Forms.MessageBoxOptions;
using StartupEventArgs = System.Windows.StartupEventArgs;
using UnhandledExceptionEventArgs = System.UnhandledExceptionEventArgs;
namespace Wox
{
public static class EntryPoint
{
[STAThread]
public static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandle;
System.Windows.Forms.Application.ThreadException += ErrorReporting.ThreadException;
namespace Wox {
public static class EntryPoint {
[STAThread]
public static void Main(string[] args) {
AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandle;
System.Windows.Forms.Application.ThreadException += ErrorReporting.ThreadException;
// don't combine Main and Entry since Microsoft.VisualBasic may be unable to load
// seperating them into two methods can make error reporting have the chance to catch exception
Entry(args);
}
// don't combine Main and Entry since Microsoft.VisualBasic may be unable to load
// seperating them into two methods can make error reporting have the chance to catch exception
Entry(args);
}
private static void Entry(string[] args){
SingleInstanceManager manager = new SingleInstanceManager();
manager.Run(args);
}
}
private static void Entry(string[] args) {
SingleInstanceManager manager = new SingleInstanceManager();
manager.Run(args);
}
}
// Using VB bits to detect single instances and process accordingly:
// * OnStartup is fired when the first instance loads
// * OnStartupNextInstance is fired when the application is re-run again
// NOTE: it is redirected to this instance thanks to IsSingleInstance
public class SingleInstanceManager : WindowsFormsApplicationBase
{
App app;
// Using VB bits to detect single instances and process accordingly:
// * OnStartup is fired when the first instance loads
// * OnStartupNextInstance is fired when the application is re-run again
// NOTE: it is redirected to this instance thanks to IsSingleInstance
[System.Diagnostics.DebuggerStepThrough]
public class SingleInstanceManager : WindowsFormsApplicationBase {
App app;
public SingleInstanceManager()
{
this.IsSingleInstance = true;
}
public SingleInstanceManager() {
this.IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
{
// First time app is launched
app = new App();
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e) {
// First time app is launched
app = new App();
//app.InitializeComponent();
app.Run();
return true;
}
app.Run();
return true;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
// Subsequent launches
base.OnStartupNextInstance(eventArgs);
app.Activate(eventArgs.CommandLine.ToArray());
}
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) {
// Subsequent launches
base.OnStartupNextInstance(eventArgs);
app.Activate(eventArgs.CommandLine.ToArray());
}
}
public partial class App : Application
{
public partial class App : Application {
private static MainWindow window;
private static MainWindow window;
public static MainWindow Window
{
get
{
return window;
}
}
public static MainWindow Window {
get {
return window;
}
}
protected override void OnStartup(StartupEventArgs e)
{
this.DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException;
protected override void OnStartup(StartupEventArgs e) {
this.DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException;
base.OnStartup(e);
base.OnStartup(e);
//for install plugin command when wox didn't start up
//we shouldn't init MainWindow, just intall plugin and exit.
if (e.Args.Length > 0 && e.Args[0].ToLower() == "installplugin")
{
var path = e.Args[1];
if (!File.Exists(path))
{
MessageBox.Show("Plugin " + path + " didn't exist");
return;
}
PluginInstaller.Install(path);
Environment.Exit(0);
return;
}
//for install plugin command when wox didn't start up
//we shouldn't init MainWindow, just intall plugin and exit.
if (e.Args.Length > 0 && e.Args[0].ToLower() == "installplugin") {
var path = e.Args[1];
if (!File.Exists(path)) {
MessageBox.Show("Plugin " + path + " didn't exist");
return;
}
PluginInstaller.Install(path);
Environment.Exit(0);
return;
}
if (e.Args.Length > 0 && e.Args[0].ToLower() == "plugindebugger")
{
var path = e.Args[1];
PluginLoader.Plugins.ActivatePluginDebugger(path);
}
if (e.Args.Length > 0 && e.Args[0].ToLower() == "plugindebugger") {
var path = e.Args[1];
PluginLoader.Plugins.ActivatePluginDebugger(path);
}
window = new MainWindow();
if (e.Args.Length == 0 || e.Args[0].ToLower() != "hidestart")
{
window.ShowApp();
}
window = new MainWindow();
if (e.Args.Length == 0 || e.Args[0].ToLower() != "hidestart") {
window.ShowApp();
}
window.ParseArgs(e.Args);
}
window.ParseArgs(e.Args);
}
public void Activate(string[] args)
{
if (args.Length == 0 || args[0].ToLower() != "hidestart")
{
window.ShowApp();
}
window.ParseArgs(args);
}
}
public void Activate(string[] args) {
if (args.Length == 0 || args[0].ToLower() != "hidestart") {
window.ShowApp();
}
window.ParseArgs(args);
}
}
}

View File

@ -9,117 +9,101 @@ using Wox.Helper;
using Wox.Plugin;
using Wox.Plugin.SystemPlugins;
namespace Wox.PluginLoader
{
public abstract class BasePluginLoader
{
private static string PluginPath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Plugins");
private static string PluginConfigName = "plugin.json";
protected static List<PluginMetadata> pluginMetadatas = new List<PluginMetadata>();
public abstract List<PluginPair> LoadPlugin();
namespace Wox.PluginLoader {
public abstract class BasePluginLoader {
private static string PluginPath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Plugins");
private static string PluginConfigName = "plugin.json";
protected static List<PluginMetadata> pluginMetadatas = new List<PluginMetadata>();
public abstract List<PluginPair> LoadPlugin();
public static void ParsePluginsConfig()
{
pluginMetadatas.Clear();
ParseSystemPlugins();
ParseThirdPartyPlugins();
public static void ParsePluginsConfig() {
pluginMetadatas.Clear();
ParseSystemPlugins();
ParseThirdPartyPlugins();
if (Plugins.DebuggerMode != null)
{
PluginMetadata metadata = GetMetadataFromJson(Plugins.DebuggerMode);
if (metadata != null) pluginMetadatas.Add(metadata);
}
}
if (Plugins.DebuggerMode != null) {
PluginMetadata metadata = GetMetadataFromJson(Plugins.DebuggerMode);
if (metadata != null) pluginMetadatas.Add(metadata);
}
}
private static void ParseSystemPlugins()
{
PluginMetadata metadata = new PluginMetadata();
metadata.Name = "System Plugins";
metadata.Author = "System";
metadata.Description = "system plugins collection";
metadata.Language = AllowedLanguage.CSharp;
metadata.Version = "1.0";
metadata.PluginType = PluginType.System;
metadata.ActionKeyword = "*";
metadata.ExecuteFileName = "Wox.Plugin.SystemPlugins.dll";
metadata.PluginDirecotry = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
pluginMetadatas.Add(metadata);
}
private static void ParseSystemPlugins() {
pluginMetadatas.Add(new PluginMetadata() {
Name = "System Plugins",
Author = "System",
Description = "system plugins collection",
Language = AllowedLanguage.CSharp,
Version = "1.0",
PluginType = PluginType.System,
ActionKeyword = "*",
ExecuteFileName = "Wox.Plugin.SystemPlugins.dll",
PluginDirecotry = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath)
});
}
private static void ParseThirdPartyPlugins()
{
if (!Directory.Exists(PluginPath))
Directory.CreateDirectory(PluginPath);
private static void ParseThirdPartyPlugins() {
if (!Directory.Exists(PluginPath))
Directory.CreateDirectory(PluginPath);
string[] directories = Directory.GetDirectories(PluginPath);
foreach (string directory in directories)
{
if (File.Exists((Path.Combine(directory, "NeedDelete.txt"))))
{
Directory.Delete(directory,true);
continue;
}
PluginMetadata metadata = GetMetadataFromJson(directory);
if (metadata != null) pluginMetadatas.Add(metadata);
}
}
string[] directories = Directory.GetDirectories(PluginPath);
foreach (string directory in directories) {
if (File.Exists((Path.Combine(directory, "NeedDelete.txt")))) {
Directory.Delete(directory, true);
continue;
}
PluginMetadata metadata = GetMetadataFromJson(directory);
if (metadata != null) pluginMetadatas.Add(metadata);
}
}
private static PluginMetadata GetMetadataFromJson(string pluginDirectory)
{
string configPath = Path.Combine(pluginDirectory, PluginConfigName);
PluginMetadata metadata;
private static PluginMetadata GetMetadataFromJson(string pluginDirectory) {
string configPath = Path.Combine(pluginDirectory, PluginConfigName);
PluginMetadata metadata;
if (!File.Exists(configPath))
{
Log.Warn(string.Format("parse plugin {0} failed: didn't find config file.", configPath));
return null;
}
if (!File.Exists(configPath)) {
Log.Warn(string.Format("parse plugin {0} failed: didn't find config file.", configPath));
return null;
}
try
{
metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath));
metadata.PluginType = PluginType.ThirdParty;
metadata.PluginDirecotry = pluginDirectory;
}
catch (Exception)
{
string error = string.Format("Parse plugin config {0} failed: json format is not valid", configPath);
Log.Warn(error);
try {
metadata = JsonConvert.DeserializeObject<PluginMetadata>(File.ReadAllText(configPath));
metadata.PluginType = PluginType.ThirdParty;
metadata.PluginDirecotry = pluginDirectory;
}
catch (Exception) {
string error = string.Format("Parse plugin config {0} failed: json format is not valid", configPath);
Log.Warn(error);
#if (DEBUG)
{
throw new WoxException(error);
}
{
throw new WoxException(error);
}
#endif
return null;
}
return null;
}
if (!AllowedLanguage.IsAllowed(metadata.Language))
{
string error = string.Format("Parse plugin config {0} failed: invalid language {1}", configPath,
metadata.Language);
Log.Warn(error);
if (!AllowedLanguage.IsAllowed(metadata.Language)) {
string error = string.Format("Parse plugin config {0} failed: invalid language {1}", configPath, metadata.Language);
Log.Warn(error);
#if (DEBUG)
{
throw new WoxException(error);
}
{
throw new WoxException(error);
}
#endif
return null;
}
if (!File.Exists(metadata.ExecuteFilePath))
{
string error = string.Format("Parse plugin config {0} failed: ExecuteFile {1} didn't exist", configPath,
metadata.ExecuteFilePath);
Log.Warn(error);
return null;
}
if (!File.Exists(metadata.ExecuteFilePath)) {
string error = string.Format("Parse plugin config {0} failed: ExecuteFile {1} didn't exist", configPath, metadata.ExecuteFilePath);
Log.Warn(error);
#if (DEBUG)
{
throw new WoxException(error);
}
{
throw new WoxException(error);
}
#endif
return null;
}
return null;
}
return metadata;
}
}
return metadata;
}
}
}

View File

@ -1,65 +1,53 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Wox.Helper;
using Wox.Plugin;
using Wox.Plugin.SystemPlugins;
namespace Wox.PluginLoader
{
public class CSharpPluginLoader : BasePluginLoader
{
public override List<PluginPair> LoadPlugin()
{
List<PluginPair> plugins = new List<PluginPair>();
namespace Wox.PluginLoader {
List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.CSharp.ToUpper()).ToList();
foreach (PluginMetadata metadata in metadatas)
{
try
{
Assembly asm = Assembly.Load(AssemblyName.GetAssemblyName(metadata.ExecuteFilePath));
List<Type> types = asm.GetTypes().Where(o => o.IsClass && !o.IsAbstract && (o.BaseType == typeof(BaseSystemPlugin) || o.GetInterfaces().Contains(typeof(IPlugin)))).ToList();
if (types.Count == 0)
{
Log.Warn(string.Format("Cound't load plugin {0}: didn't find the class who implement IPlugin",
metadata.Name));
continue;
}
public class CSharpPluginLoader : BasePluginLoader {
foreach (Type type in types)
{
PluginPair pair = new PluginPair()
{
Plugin = Activator.CreateInstance(type) as IPlugin,
Metadata = metadata
};
public override List<PluginPair> LoadPlugin() {
List<PluginPair> plugins = new List<PluginPair>();
var sys = pair.Plugin as BaseSystemPlugin;
if (sys != null)
{
sys.PluginDirectory = metadata.PluginDirecotry;
}
List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.CSharp.ToUpper()).ToList();
foreach (PluginMetadata metadata in metadatas) {
try {
Assembly asm = Assembly.Load(AssemblyName.GetAssemblyName(metadata.ExecuteFilePath));
List<Type> types = asm.GetTypes().Where(o => o.IsClass && !o.IsAbstract && (o.BaseType == typeof(BaseSystemPlugin) || o.GetInterfaces().Contains(typeof(IPlugin)))).ToList();
if (types.Count == 0) {
Log.Warn(string.Format("Cound't load plugin {0}: didn't find the class who implement IPlugin", metadata.Name));
continue;
}
plugins.Add(pair);
}
}
catch (Exception e)
{
Log.Error(string.Format("Cound't load plugin {0}: {1}", metadata.Name, e.Message));
foreach (Type type in types) {
PluginPair pair = new PluginPair() {
Plugin = Activator.CreateInstance(type) as IPlugin,
Metadata = metadata
};
var sys = pair.Plugin as BaseSystemPlugin;
if (sys != null) {
sys.PluginDirectory = metadata.PluginDirecotry;
}
plugins.Add(pair);
}
}
catch (Exception e) {
Log.Error(string.Format("Cound't load plugin {0}: {1}", metadata.Name, e.Message));
#if (DEBUG)
{
throw;
}
{
throw;
}
#endif
}
}
}
}
return plugins;
}
}
return plugins;
}
}
}

View File

@ -33,7 +33,7 @@
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>