forked from Wox-launcher/Wox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.cs
334 lines (308 loc) · 11.4 KB
/
Main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using WindowsInput;
using WindowsInput.Native;
using Wox.Infrastructure.Hotkey;
using Wox.Infrastructure.Logger;
using Wox.Infrastructure.Storage;
using Application = System.Windows.Application;
using Control = System.Windows.Controls.Control;
using Keys = System.Windows.Forms.Keys;
namespace Wox.Plugin.Shell
{
public class Main : IPlugin, ISettingProvider, IPluginI18n, IContextMenu, ISavable
{
private const string Image = "Images/shell.png";
private PluginInitContext _context;
private bool _winRStroked;
private readonly KeyboardSimulator _keyboardSimulator = new KeyboardSimulator(new InputSimulator());
private readonly Settings _settings;
private readonly PluginJsonStorage<Settings> _storage;
public Main()
{
_storage = new PluginJsonStorage<Settings>();
_settings = _storage.Load();
}
public void Save()
{
_storage.Save();
}
public List<Result> Query(Query query)
{
List<Result> results = new List<Result>();
string cmd = query.Search;
if (string.IsNullOrEmpty(cmd))
{
return ResultsFromlHistory();
}
else
{
var queryCmd = GetCurrentCmd(cmd);
results.Add(queryCmd);
var history = GetHistoryCmds(cmd, queryCmd);
results.AddRange(history);
try
{
string basedir = null;
string dir = null;
string excmd = Environment.ExpandEnvironmentVariables(cmd);
if (Directory.Exists(excmd) && (cmd.EndsWith("/") || cmd.EndsWith(@"\")))
{
basedir = excmd;
dir = cmd;
}
else if (Directory.Exists(Path.GetDirectoryName(excmd) ?? string.Empty))
{
basedir = Path.GetDirectoryName(excmd);
var dirn = Path.GetDirectoryName(cmd);
dir = (dirn.EndsWith("/") || dirn.EndsWith(@"\")) ? dirn : cmd.Substring(0, dirn.Length + 1);
}
if (basedir != null)
{
var autocomplete = Directory.GetFileSystemEntries(basedir).
Select(o => dir + Path.GetFileName(o)).
Where(o => o.StartsWith(cmd, StringComparison.OrdinalIgnoreCase) &&
!results.Any(p => o.Equals(p.Title, StringComparison.OrdinalIgnoreCase)) &&
!results.Any(p => o.Equals(p.Title, StringComparison.OrdinalIgnoreCase))).ToList();
autocomplete.Sort();
results.AddRange(autocomplete.ConvertAll(m => new Result
{
Title = m,
IcoPath = Image,
Action = c =>
{
Execute(m);
return true;
}
}));
}
}
catch (Exception e)
{
Log.Exception($"|Wox.Plugin.Shell.Main.Query|Exception when query for <{query}>", e);
}
return results;
}
}
private List<Result> GetHistoryCmds(string cmd, Result result)
{
IEnumerable<Result> history = _settings.Count.Where(o => o.Key.Contains(cmd))
.OrderByDescending(o => o.Value)
.Select(m =>
{
if (m.Key == cmd)
{
result.SubTitle = string.Format(_context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value);
return null;
}
var ret = new Result
{
Title = m.Key,
SubTitle = string.Format(_context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value),
IcoPath = Image,
Action = c =>
{
Execute(m.Key);
return true;
}
};
return ret;
}).Where(o => o != null).Take(4);
return history.ToList();
}
private Result GetCurrentCmd(string cmd)
{
Result result = new Result
{
Title = cmd,
Score = 5000,
SubTitle = _context.API.GetTranslation("wox_plugin_cmd_execute_through_shell"),
IcoPath = Image,
Action = c =>
{
Execute(cmd);
return true;
}
};
return result;
}
private List<Result> ResultsFromlHistory()
{
IEnumerable<Result> history = _settings.Count.OrderByDescending(o => o.Value)
.Select(m => new Result
{
Title = m.Key,
SubTitle = string.Format(_context.API.GetTranslation("wox_plugin_cmd_cmd_has_been_executed_times"), m.Value),
IcoPath = Image,
Action = c =>
{
Execute(m.Key);
return true;
}
}).Take(5);
return history.ToList();
}
private void Execute(string command, bool runAsAdministrator = false)
{
command = command.Trim();
command = Environment.ExpandEnvironmentVariables(command);
ProcessStartInfo info;
if (_settings.Shell == Shell.Cmd)
{
var arguments = _settings.LeaveShellOpen ? $"/k \"{command}\"" : $"/c \"{command}\" & pause";
info = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = arguments,
};
}
else if (_settings.Shell == Shell.Powershell)
{
string arguments;
if (_settings.LeaveShellOpen)
{
arguments = $"-NoExit \"{command}\"";
}
else
{
arguments = $"\"{command} ; Read-Host -Prompt \\\"Press Enter to continue\\\"\"";
}
info = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = arguments
};
}
else if (_settings.Shell == Shell.RunCommand)
{
var parts = command.Split(new[] { ' ' }, 2);
if (parts.Length == 2)
{
var filename = parts[0];
if (ExistInPath(filename))
{
var arguemtns = parts[1];
info = new ProcessStartInfo
{
FileName = filename,
Arguments = arguemtns
};
}
else
{
info = new ProcessStartInfo(command);
}
}
else
{
info = new ProcessStartInfo(command);
}
}
else
{
return;
}
info.UseShellExecute = true;
info.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
info.Verb = runAsAdministrator ? "runas" : "";
try
{
Process.Start(info);
_settings.AddCmdHistory(command);
}
catch (FileNotFoundException e)
{
MessageBox.Show($"Command not found: {e.Message}");
}
}
private bool ExistInPath(string filename)
{
if (File.Exists(filename))
{
return true;
}
else
{
var values = Environment.GetEnvironmentVariable("PATH");
if (values != null)
{
foreach (var path in values.Split(';'))
{
var path1 = Path.Combine(path, filename);
var path2 = Path.Combine(path, filename + ".exe");
if (File.Exists(path1) || File.Exists(path2))
{
return true;
}
}
return false;
}
else
{
return false;
}
}
}
public void Init(PluginInitContext context)
{
this._context = context;
context.API.GlobalKeyboardEvent += API_GlobalKeyboardEvent;
}
bool API_GlobalKeyboardEvent(int keyevent, int vkcode, SpecialKeyState state)
{
if (_settings.ReplaceWinR)
{
if (keyevent == (int)KeyEvent.WM_KEYDOWN && vkcode == (int)Keys.R && state.WinPressed)
{
_winRStroked = true;
OnWinRPressed();
return false;
}
if (keyevent == (int)KeyEvent.WM_KEYUP && _winRStroked && vkcode == (int)Keys.LWin)
{
_winRStroked = false;
_keyboardSimulator.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.CONTROL);
return false;
}
}
return true;
}
private void OnWinRPressed()
{
_context.API.ChangeQuery($"{_context.CurrentPluginMetadata.ActionKeywords[0]}{Plugin.Query.TermSeperater}");
Application.Current.MainWindow.Visibility = Visibility.Visible;
}
public Control CreateSettingPanel()
{
return new CMDSetting(_settings);
}
public string GetTranslatedPluginTitle()
{
return _context.API.GetTranslation("wox_plugin_cmd_plugin_name");
}
public string GetTranslatedPluginDescription()
{
return _context.API.GetTranslation("wox_plugin_cmd_plugin_description");
}
public List<Result> LoadContextMenus(Result selectedResult)
{
return new List<Result>
{
new Result
{
Title = _context.API.GetTranslation("wox_plugin_cmd_run_as_administrator"),
Action = c =>
{
Execute(selectedResult.Title, true);
return true;
},
IcoPath = Image
}
};
}
}
}