-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
378 lines (328 loc) · 12.1 KB
/
MainWindow.xaml.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Controls;
using WindowsInput.Native;
using System.Reflection;
using System.ComponentModel;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using WindowsInput;
using System.Text.Json.Serialization;
using System.Windows.Media;
using MahApps.Metro.Controls;
using System.Text.RegularExpressions;
using System.Windows.Input;
using System.Windows.Data;
using System.Globalization;
using ControlzEx.Theming;
namespace virtual_cube
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
private static readonly int DEFAULT_KEYPRESS_TIME = 20;
private static readonly CubeBluetoothLEAdvertisementWatcher watcher = new CubeBluetoothLEAdvertisementWatcher();
public static Boolean mappingEnabled = false;
public List<VirtualKeyCode> VIRTUAL_KEY_CODES;
public static Boolean Active { get; set; }
public ScanMode ScanMode { get; set; }
private readonly static String path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private readonly static String configurationPath = path + "\\config.json";
private Boolean loading = true;
private BindingList<Cube> Cubes = new BindingList<Cube>();
private Timer batteryTimer;
private Configuration Configuration = new Configuration();
private static readonly InputSimulator InputSimulator = new InputSimulator();
private static readonly JsonSerializerOptions options = new JsonSerializerOptions
{
Converters ={
new JsonStringEnumConverter(),
}
};
public MainWindow()
{
InitializeComponent();
ToggleKeyMapping();
Active = true;
watcher.DeviceFoundEvent += DeviceFound;
cubeGrid.ItemsSource = Cubes;
StartScan();
VIRTUAL_KEY_CODES = ((VirtualKeyCode[])Enum.GetValues(typeof(VirtualKeyCode))).ToList();
F.ItemsSource = VIRTUAL_KEY_CODES;
FI.ItemsSource = VIRTUAL_KEY_CODES;
L.ItemsSource = VIRTUAL_KEY_CODES;
LI.ItemsSource = VIRTUAL_KEY_CODES;
R.ItemsSource = VIRTUAL_KEY_CODES;
RI.ItemsSource = VIRTUAL_KEY_CODES;
U.ItemsSource = VIRTUAL_KEY_CODES;
UI.ItemsSource = VIRTUAL_KEY_CODES;
B.ItemsSource = VIRTUAL_KEY_CODES;
BI.ItemsSource = VIRTUAL_KEY_CODES;
D.ItemsSource = VIRTUAL_KEY_CODES;
DI.ItemsSource = VIRTUAL_KEY_CODES;
Configuration = LoadConfiguration();
if (Configuration != null && Configuration.Mapping != null) {
foreach (UIElement uIElement in KeyMappingGrid.Children)
{
if (uIElement is System.Windows.Controls.ComboBox)
{
System.Windows.Controls.ComboBox comboBox = (System.Windows.Controls.ComboBox)uIElement;
VirtualKeyCode mapping;
Configuration.Mapping.TryGetValue(comboBox.Name, out mapping);
comboBox.SelectedValue = mapping;
}
}
keyMapping.IsChecked = Configuration.MappingEnabled;
PRESSTIME.Text = Configuration.TimePerKeyPress?.ToString();
}
loading = false;
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(1);
batteryTimer = new System.Threading.Timer((e) =>
{
foreach (Cube cube in Cubes.Where(x => x.ConnectionStatus == ConnectionStatus.CONNECTED))
{
cube.RequestBatteryLevelAsync();
}
var CubesToRemove = Cubes.Where(x =>
x.ConnectionStatus == ConnectionStatus.DISCONNECTED
&& x.LastAdvertisement < DateTime.Now.AddMinutes(-2)).ToList();
Application.Current.Dispatcher.Invoke(new Action(() => {
foreach (Cube cube in CubesToRemove)
{
Cubes.Remove(cube);
}
}));
}, null, startTimeSpan, periodTimeSpan);
}
private void StartScan()
{
watcher.Start();
ScanMode = ScanMode.SCANNING;
ScanButton.Content = "Stop Scanning";
}
private void StopScan()
{
watcher.Stop();
ScanMode = ScanMode.NONE;
ScanButton.Content = "Start Scanning";
}
protected override void OnActivated(EventArgs e)
{
Active = true;
}
protected override void OnDeactivated(EventArgs e)
{
Active = false;
}
private void HandleCheck(object sender, RoutedEventArgs e)
{
ToggleKeyMapping();
}
private void ToggleKeyMapping()
{
mappingEnabled = keyMapping != null && keyMapping.IsChecked != null && keyMapping.IsChecked == true;
if (mappingEnabled)
{
UpdateMapping(null, null);
}
if (KeyMappingGrid != null)
{
foreach (UIElement uIElement in KeyMappingGrid.Children)
{
uIElement.IsEnabled = mappingEnabled;
}
}
}
private void DisconnectButton_Click(object sender, RoutedEventArgs e)
{
FrameworkElement fe = sender as FrameworkElement;
Cube cube = ((Cube)fe.DataContext);
Disconnect(cube);
}
private void ConnectButton_Click(object sender, RoutedEventArgs e)
{
FrameworkElement fe = sender as FrameworkElement;
Cube cube = ((Cube)fe.DataContext);
Connect(cube);
}
private void ScanButton_Click(object sender, RoutedEventArgs e)
{
if (ScanMode.NONE == ScanMode)
{
StartScan();
} else
{
StopScan();
}
}
private async void Connect(Cube cube)
{
await cube.ConnectAsync();
if (cube.ConnectionStatus == ConnectionStatus.CONNECTED)
{
cube.Moves += OnMove;
StopScan();
await cube.RequestBatteryLevelAsync();
}
}
private async void Disconnect(Cube cube)
{
await cube.DisconnectAsync();
cube.Moves -= OnMove;
Application.Current.Dispatcher.Invoke(new Action(() => {
Cubes.Remove(cube);
}));
StartScan();
}
private void OnMove(object sender, Move move)
{
if (!Active)
{
if (mappingEnabled)
{
VirtualKeyCode map;
Configuration.Mapping.TryGetValue(move.ToString(), out map);
if (Configuration.Mapping != null)
{
Debug.WriteLine("Typing " + map);
InputSimulator.Keyboard.KeyDown(map);
SendUpWithDelay(map);
}
}
else
{
InputSimulator.Keyboard.TextEntry(move.ToString().Replace("I","'"));
}
}
else
{
HighLight(move);
}
}
async Task SendUpWithDelay(VirtualKeyCode a)
{
int delay = Configuration.TimePerKeyPress ?? DEFAULT_KEYPRESS_TIME;
await Task.Delay(delay);
InputSimulator.Keyboard.KeyUp(a);
}
async Task HighLight(Move move)
{
SetLabelStyle(move, Brushes.LightBlue, Brushes.White);
int delay = Configuration.TimePerKeyPress ?? DEFAULT_KEYPRESS_TIME;
await Task.Delay(delay);
SetLabelStyle(move, null, Brushes.Black);
}
private void SetLabelStyle(Move move, Brush background, Brush foreGround)
{
Application.Current.Dispatcher.Invoke(new Action(() => {
foreach (UIElement uIElement in KeyMappingGrid.Children)
{
if (uIElement is System.Windows.Controls.Label)
{
System.Windows.Controls.Label label = (System.Windows.Controls.Label)uIElement;
if (label.Name == "LABEL_" + move.ToString())
{
label.Background = background;
label.Foreground = foreGround;
}
}
}
}));
}
void DeviceFound(Cube cube)
{
Application.Current.Dispatcher.Invoke(new Action(() => {
if (!Cubes.Contains(cube))
{
Cubes.Add(cube);
cube.LastAdvertisement = DateTime.Now;
} else
{
var existingCube = Cubes.Where(x => x.BluetoothAddress == cube.BluetoothAddress).Single();
existingCube.LastAdvertisement = DateTime.Now;
}
}));
}
public void UpdateMapping(object sender, SelectionChangedEventArgs e)
{
UpdateConfiguration();
}
public void UpdateConfiguration()
{
if (!loading)
{
Configuration = new Configuration(mappingEnabled, GetMapping(), GetPressTime());
SaveConfiguration(Configuration);
}
}
private int GetPressTime()
{
int number;
bool success = Int32.TryParse(PRESSTIME.Text, out number);
if (!success)
{
number = DEFAULT_KEYPRESS_TIME;
}
return number;
}
public Dictionary<String, VirtualKeyCode> GetMapping()
{
Dictionary<String, VirtualKeyCode> mapping = new Dictionary<String, VirtualKeyCode>();
foreach (UIElement uIElement in KeyMappingGrid.Children) {
if (uIElement is System.Windows.Controls.ComboBox)
{
System.Windows.Controls.ComboBox comboBox = (System.Windows.Controls.ComboBox)uIElement;
if (comboBox.SelectedValue != null)
{
mapping.Add(comboBox.Name, (VirtualKeyCode)comboBox.SelectedValue);
}
}
}
return mapping;
}
private async void SaveConfiguration(Configuration configuration)
{
using (FileStream fs = File.Create(configurationPath))
{
await JsonSerializer.SerializeAsync(fs, configuration, options);
}
}
private void Refresh()
{
}
private Configuration LoadConfiguration()
{
if (File.Exists(configurationPath))
{
try
{
return JsonSerializer.Deserialize<Configuration>(File.ReadAllText(configurationPath), options);
} catch(Exception e) { }
}
return null;
}
private static readonly Regex _regex = new Regex("[^0-9]+"); //regex that matches disallowed text
private static bool IsTextAllowed(string text)
{
return !_regex.IsMatch(text);
}
private void PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}
private void PRESSTIME_TextChanged(object sender, TextChangedEventArgs e)
{
UpdateConfiguration();
}
}
}