forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsoleKeyChordConverter.cs
More file actions
259 lines (226 loc) · 9.45 KB
/
Copy pathConsoleKeyChordConverter.cs
File metadata and controls
259 lines (226 loc) · 9.45 KB
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
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
#if UNIX
using System.Reflection;
#endif
using System.Runtime.InteropServices;
using Microsoft.PowerShell.Internal;
namespace Microsoft.PowerShell
{
/// <summary>
/// A helper class for converting strings to ConsoleKey chords.
/// </summary>
public static class ConsoleKeyChordConverter
{
/// <summary>
/// Converts a string to a sequence of ConsoleKeyInfo.
/// Sequences are separated by ','. Modifiers
/// appear before the modified key and are separated by '+'.
/// Examples:
/// Ctrl+X
/// Ctrl+D,M
/// Escape,X
/// </summary>
public static ConsoleKeyInfo[] Convert(string chord)
{
if (string.IsNullOrEmpty(chord))
{
throw new ArgumentNullException("chord");
}
var tokens = chord.Split(new[] {','});
if (tokens.Length > 2)
{
throw new ArgumentException(PSReadLineResources.ChordWithTooManyKeys);
}
var result = new ConsoleKeyInfo[tokens.Length];
for (int i = 0; i < tokens.Length; i++)
{
result[i] = ConvertOneSequence(tokens[i]);
}
return result;
}
private static ConsoleKeyInfo ConvertOneSequence(string sequence)
{
Stack<string> tokens = null;
ConsoleModifiers modifiers = 0;
ConsoleKey key = 0;
bool valid = !String.IsNullOrEmpty(sequence);
if (valid)
{
tokens = new Stack<string>(
(sequence.Split(new[] {'+'})
.Select(
part => part.ToLowerInvariant().Trim())));
}
while (valid && tokens.Count > 0)
{
string token = tokens.Pop();
// sequence was something silly like "shift++"
if (token == String.Empty)
{
valid = false;
break;
}
// key should be first token to be popped
if (key == 0)
{
// Enum.TryParse accepts arbitrary integers. We shouldn't,
// but single digits need to map to the correct key, e.g.
// ConsoleKey.D1
long tokenAsLong;
if (long.TryParse(token, out tokenAsLong))
{
if (tokenAsLong >= 0 && tokenAsLong <= 9)
{
token = "D" + token;
}
else
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, PSReadLineResources.UnrecognizedKey, token));
}
}
// try simple parse for ConsoleKey enum name
valid = Enum.TryParse(token, ignoreCase: true, result: out key);
// doesn't map to ConsoleKey so convert to virtual key from char
if (!valid && token.Length == 1)
{
string failReason;
valid = TryParseCharLiteral(token[0], ref modifiers, ref key, out failReason);
if (!valid)
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, PSReadLineResources.CantTranslateKey, token[0], failReason));
}
}
if (!valid)
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, PSReadLineResources.UnrecognizedKey, token));
}
}
else
{
// now, parse modifier(s)
ConsoleModifiers modifier;
// courtesy translation
if (token == "ctrl")
{
token = "control";
}
if (Enum.TryParse(token, ignoreCase: true, result: out modifier))
{
// modifier already set?
if ((modifiers & modifier) != 0)
{
// either found duplicate modifier token or shift state
// was already implied from char, e.g. char is "}", which is "shift+]"
throw new ArgumentException(
String.Format(CultureInfo.CurrentCulture, PSReadLineResources.InvalidModifier, modifier, key));
}
modifiers |= modifier;
}
else
{
throw new ArgumentException(
String.Format(CultureInfo.CurrentCulture, PSReadLineResources.InvalidModifier, token, key));
}
}
}
if (!valid)
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, PSReadLineResources.InvalidSequence, sequence));
}
char keyChar = GetCharFromConsoleKey(key, modifiers);
return new ConsoleKeyInfo(keyChar, key,
shift: ((modifiers & ConsoleModifiers.Shift) != 0),
alt: ((modifiers & ConsoleModifiers.Alt) != 0),
control: ((modifiers & ConsoleModifiers.Control) != 0));
}
private static bool TryParseCharLiteral(char literal, ref ConsoleModifiers modifiers, ref ConsoleKey key, out string failReason)
{
bool valid = false;
// shift state will be in MSB
short virtualKey = NativeMethods.VkKeyScan(literal);
int hresult = Marshal.GetLastWin32Error();
if (virtualKey != 0)
{
// e.g. "}" = 0x01dd but "]" is 0x00dd, ergo } = shift+].
// shift = 1, control = 2, alt = 4, hankaku = 8 (ignored)
int state = virtualKey >> 8;
if ((state & 1) == 1)
{
modifiers |= ConsoleModifiers.Shift;
}
if ((state & 2) == 2)
{
modifiers |= ConsoleModifiers.Control;
}
if ((state & 4) == 4)
{
modifiers |= ConsoleModifiers.Alt;
}
virtualKey &= 0xff;
if (Enum.IsDefined(typeof (ConsoleKey), (int) virtualKey))
{
failReason = null;
key = (ConsoleKey) virtualKey;
valid = true;
}
else
{
// haven't seen this happen yet, but possible
failReason = String.Format(CultureInfo.CurrentCulture, PSReadLineResources.UnrecognizedKey, virtualKey);
}
}
else
{
Exception e = Marshal.GetExceptionForHR(hresult);
failReason = e.Message;
}
return valid;
}
internal static char GetCharFromConsoleKey(ConsoleKey key, ConsoleModifiers modifiers)
{
// default for unprintables and unhandled
char keyChar = '\u0000';
#if UNIX
Type keyType = typeof (Keys);
FieldInfo[] keyFields = keyType.GetFields();
foreach (FieldInfo field in keyFields)
{
if (field.FieldType == typeof(ConsoleKeyInfo))
{
ConsoleKeyInfo info = (ConsoleKeyInfo)field.GetValue(null);
if (info.Key == key && info.Modifiers == modifiers)
{
return info.KeyChar;
}
}
}
#else
// emulate GetKeyboardState bitmap - set high order bit for relevant modifier virtual keys
var state = new byte[256];
state[NativeMethods.VK_SHIFT] = (byte)(((modifiers & ConsoleModifiers.Shift) != 0) ? 0x80 : 0);
state[NativeMethods.VK_CONTROL] = (byte)(((modifiers & ConsoleModifiers.Control) != 0) ? 0x80 : 0);
state[NativeMethods.VK_ALT] = (byte)(((modifiers & ConsoleModifiers.Alt) != 0) ? 0x80 : 0);
// a ConsoleKey enum's value is a virtual key code
uint virtualKey = (uint)key;
// get corresponding scan code
uint scanCode = NativeMethods.MapVirtualKey(virtualKey, NativeMethods.MAPVK_VK_TO_VSC);
// get corresponding character - maybe be 0, 1 or 2 in length (diacriticals)
var chars = new char[2];
int charCount = NativeMethods.ToUnicode(
virtualKey, scanCode, state, chars, chars.Length, NativeMethods.MENU_IS_INACTIVE);
// TODO: support diacriticals (charCount == 2)
if (charCount == 1)
{
keyChar = chars[0];
}
#endif
return keyChar;
}
}
}