-
-
Notifications
You must be signed in to change notification settings - Fork 505
/
OptiKeyApp.cs
1345 lines (1184 loc) · 62.4 KB
/
OptiKeyApp.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2022 OPTIKEY LTD (UK company number 11854839) - All Rights Reserved
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Diagnostics;
using Microsoft.Win32;
using JuliusSweetland.OptiKey.Enums;
using JuliusSweetland.OptiKey.Extensions;
using JuliusSweetland.OptiKey.Models;
using JuliusSweetland.OptiKey.Observables.PointSources;
using JuliusSweetland.OptiKey.Observables.TriggerSources;
using JuliusSweetland.OptiKey.Properties;
using JuliusSweetland.OptiKey.Services;
using JuliusSweetland.OptiKey.Static;
using JuliusSweetland.OptiKey.UI.ViewModels;
using JuliusSweetland.OptiKey.UI.Windows;
using log4net;
using log4net.Core;
using log4net.Repository.Hierarchy;
using log4net.Appender; //Do not remove even if marked as unused by Resharper - it is used by the Release build configuration
using Octokit;
using presage;
using Application = System.Windows.Application;
using JuliusSweetland.OptiKey.Services.PluginEngine;
using WindowsRecipes.TaskbarSingleInstance;
namespace JuliusSweetland.OptiKey
{
/// <summary>
/// Interaction logic for OptiKeyApp.xaml
/// </summary>
public partial class OptiKeyApp : Application
{
#region Constants
protected const string GazeTrackerUdpRegex = @"^STREAM_DATA\s(?<instanceTime>\d+)\s(?<x>-?\d+(\.[0-9]+)?)\s(?<y>-?\d+(\.[0-9]+)?)";
protected const string GitHubRepoName = "optikey";
protected const string GitHubRepoOwner = "optikey";
protected const string ExpectedMaryTTSLocationSuffix = @"\bin\marytts-server.bat";
#endregion
#region protected Member Vars
protected static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Action applyTheme;
private bool persistedState = true;
private WindowStates tempWindowState;
private DockEdges tempDockPosition;
private DockSizes tempDockSize;
private double tempFullDockThickness;
private double tempCollapsedDockThickness;
private Rect tempFloatingSizeAndPosition;
#endregion
#region Ctor
public OptiKeyApp()
{
}
// This will be assigned from within derived apps
protected static SingleInstanceManager _manager;
public static void RestartApp()
{
// Release single-instance mutex if we've got one
if (_manager != null)
{
_manager.Dispose();
}
System.Windows.Forms.Application.Restart();
}
// Previously in core OptiKey ctr, now called by derived classes after setting up Settings class
protected void Initialise()
{
//Setup unhandled exception handling
AttachUnhandledExceptionHandlers();
//Log startup diagnostic info
Log.Info("STARTING UP.");
LogDiagnosticInfo();
// Output the user settings for debugging
logUserSettings();
//Attach shutdown handler
Current.Exit += (o, args) =>
{
Log.Info("PERSISTING USER SETTINGS AND SHUTTING DOWN.");
Settings.Default.Save();
};
HandleCorruptSettings();
//Upgrade settings (if required) - this ensures that user settings migrate between version changes
if (Settings.Default.SettingsUpgradeRequired)
{
Settings.Default.Upgrade();
Settings.Default.SettingsUpgradeRequired = false;
Settings.Default.Save();
Settings.Default.Reload();
}
//Migrate the completion time setting to the new field
if (Settings.Default.KeySelectionTriggerFixationDefaultCompleteTimes == null)
{
Settings.Default.KeySelectionTriggerFixationDefaultCompleteTimes
= Settings.Default.KeySelectionTriggerFixationDefaultCompleteTime.TotalMilliseconds.ToString();
}
//Adjust log4net logging level if in debug mode
((Hierarchy)LogManager.GetRepository()).Root.Level = Settings.Default.Debug ? Level.Debug : Level.Info;
((Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(EventArgs.Empty);
//Apply resource language (and listen for changes)
Action<Languages> applyResourceLanguage = language =>
{
OptiKey.Properties.Resources.Culture = language.ToCultureInfo(); //Reloads resource file by culture code
Settings.Default.UiLanguageFlowDirection = language.ToCultureInfo().TextInfo.IsRightToLeft
? FlowDirection.RightToLeft
: FlowDirection.LeftToRight;
};
Settings.Default.OnPropertyChanges(s => s.UiLanguage).Subscribe(applyResourceLanguage);
applyResourceLanguage(Settings.Default.UiLanguage);
//Logic to initially apply the theme and change the theme on setting changes
applyTheme = () =>
{
var themeDictionary = new ThemeResourceDictionary
{
// TODO: this is a bit weird, makes assumptions about architecture of calling code...
Source = new Uri("pack://application:,,,/OptiKey;component" + Settings.Default.Theme)
};
var previousThemes = Resources.MergedDictionaries
.OfType<ThemeResourceDictionary>()
.ToList();
//N.B. Add replacement before removing the previous as having no applicable resource
//dictionary can result in the first element not being rendered (usually the first key).
Resources.MergedDictionaries.Add(themeDictionary);
previousThemes.ForEach(rd => Resources.MergedDictionaries.Remove(rd));
};
Settings.Default.OnPropertyChanges(settings => settings.Theme).Subscribe(_ => applyTheme());
}
#endregion
protected static bool PresageInstallationProblemsDetected()
{
if (Settings.Default.SuggestionMethod == SuggestionMethods.Presage)
{
//1.Check the install path to detect if the wrong bitness of Presage is installed
string presagePath = null;
string presageStartMenuFolder = null;
string osBitness = DiagnosticInfo.OperatingSystemBitness;
try
{
presagePath = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Presage", "", string.Empty).ToString();
presageStartMenuFolder = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Presage", "Start Menu Folder", string.Empty).ToString();
}
catch (Exception ex)
{
Log.ErrorFormat("Caught exception: {0}", ex);
}
Log.InfoFormat("Presage path: {0} | Presage start menu folder: {1} | OS bitness: {2}", presagePath, presageStartMenuFolder, osBitness);
if (string.IsNullOrEmpty(presagePath)
|| string.IsNullOrEmpty(presageStartMenuFolder))
{
Settings.Default.SuggestionMethod = SuggestionMethods.NGram;
Log.Error("Invalid Presage installation detected (path(s) missing). Must install 'presage-0.9.1-32bit' or 'presage-0.9.2~beta20150909-32bit'. Changed SuggesionMethod to NGram.");
return true;
}
if (presageStartMenuFolder != "presage-0.9.2~beta20150909"
&& presageStartMenuFolder != "presage-0.9.1")
{
Settings.Default.SuggestionMethod = SuggestionMethods.NGram;
Log.Error("Invalid Presage installation detected (valid version not detected). Must install 'presage-0.9.1-32bit' or 'presage-0.9.2~beta20150909-32bit'. Changed SuggesionMethod to NGram.");
return true;
}
if ((osBitness == "64-Bit" && presagePath != @"C:\Program Files (x86)\presage")
|| (osBitness == "32-Bit" && presagePath != @"C:\Program Files\presage"))
{
Settings.Default.SuggestionMethod = SuggestionMethods.NGram;
Log.Error("Invalid Presage installation detected (incorrect bitness? Install location is suspect). Must install 'presage-0.9.1-32bit' or 'presage-0.9.2~beta20150909-32bit'. Changed SuggesionMethod to NGram.");
return true;
}
if (!Directory.Exists(presagePath))
{
Settings.Default.SuggestionMethod = SuggestionMethods.NGram;
Log.Error("Invalid Presage installation detected (install directory does not exist). Must install 'presage-0.9.1-32bit' or 'presage-0.9.2~beta20150909-32bit'. Changed SuggesionMethod to NGram.");
return true;
}
//2.Attempt to construct a Presage object, which can fail for a few reasons, including BadImageFormatExceptions (64-bit version installed)
Presage presageTestInstance = null;
try
{
//Test Presage constructor call for DllNotFoundException or BadImageFormatException
presageTestInstance = new Presage(() => "", () => "");
}
catch (Exception ex)
{
//If the installed version of Presage is the wrong format (i.e. 64 bit) then a BadImageFormatException can occur.
//If Presage has been deleted, corrupted, or another problem, then a DllLoadException can occur.
//These causes an additional problem as the Presage object will probably be non-deterministically
//finalised, which will cause this exception again and crash OptiKey. The workaround is to suppress finalisation
//if an object is available (which it generally won't be!), or to warn the user and react.
//Set the suggestion method to NGram so that the IDictionaryService can be instantiated without crashing OptiKey
Settings.Default.SuggestionMethod = SuggestionMethods.NGram;
Settings.Default.Save(); //Save as OptiKey can crash as soon as the finaliser is called by the GC
Log.Error("Presage failed to bootstrap - attempting to suppress finalisation. The suggestion method has been changed to NGram", ex);
//Attempt to suppress finalisation on the presage instance, or just warn the user
if (presageTestInstance != null)
{
GC.SuppressFinalize(presageTestInstance);
}
else
{
MessageBox.Show(
OptiKey.Properties.Resources.PRESAGE_CONSTRUCTOR_EXCEPTION_MESSAGE,
OptiKey.Properties.Resources.PRESAGE_CONSTRUCTOR_EXCEPTION_TITLE,
MessageBoxButton.OK,
MessageBoxImage.Error);
}
return true;
}
// set the config
if (File.Exists(Settings.Default.PresageDatabaseLocation))
{
presageTestInstance.set_config("Presage.Predictors.DefaultSmoothedNgramPredictor.DBFILENAME", Path.GetFullPath(Settings.Default.PresageDatabaseLocation));
}
else
{
try
{
string ApplicationDataSubPath = @"OptiKey\OptiKey";
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ApplicationDataSubPath);
var database = Path.Combine(path, @"Presage\database.db");
if (!File.Exists(database))
{
try
{
using (ZipArchive archive = ZipFile.Open(@".\Resources\Presage\database.zip", ZipArchiveMode.Read, Encoding.UTF8))
{
archive.ExtractToDirectory(path);
}
}
catch (Exception e)
{
Log.ErrorFormat("Unpacking the Presage database failed with the following exception: \n{0}", e);
}
}
Settings.Default.PresageDatabaseLocation = database;
presageTestInstance.set_config("Presage.Predictors.DefaultSmoothedNgramPredictor.DBFILENAME", Path.GetFullPath(Settings.Default.PresageDatabaseLocation));
}
catch (Exception ex)
{
Log.Error("Presage failed to bootstrap. The database (database.db file) was not found, and the database.zip file could not be extracted!", ex);
return true;
}
}
presageTestInstance.set_config("Presage.Selector.REPEAT_SUGGESTIONS", "yes");
presageTestInstance.set_config("Presage.Selector.SUGGESTIONS", Settings.Default.PresageNumberOfSuggestions.ToString());
presageTestInstance.save_config();
Log.Info("Presage settings set successfully.");
}
return false;
}
private void logUserSettings()
{
// If debug switched on, dump entire XML into log so we can replicate issues.
if (Settings.Default.Debug)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
Log.Debug(config.FilePath);
// We read into a single string so we can print without log4net preamble on each line.
string configText = File.ReadAllText(config.FilePath);
Log.DebugFormat("\r\n{0}", configText);
}
// Otherwise just key: value pairs into log
else
{
Log.Info("Current user settings:");
foreach (SettingsProperty property in Settings.Default.Properties)
{
Log.InfoFormat(" {0}: {1}", property.Name, Settings.Default[property.Name]);
}
}
}
#region Create Main Window Manipulation Service
protected WindowManipulationService CreateMainWindowManipulationService(MainWindow mainWindow)
{
return new WindowManipulationService(
mainWindow,
() =>
{
if (Settings.Default.Debug)
{
Log.DebugFormat("Getting persistedState with value '{0}'", persistedState);
}
return persistedState;
},
() =>
{
if (Settings.Default.Debug)
{
Log.DebugFormat("Getting MainWindowOpacity from settings with value '{0}'", Settings.Default.MainWindowOpacity);
}
return Settings.Default.MainWindowOpacity;
},
() =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Getting MainWindowState from settings with value '{0}'", Settings.Default.MainWindowState);
else
Log.DebugFormat("Getting tempWindowState with value '{0}'", Settings.Default.MainWindowState);
}
if (persistedState)
return Settings.Default.MainWindowState;
else
return tempWindowState;
},
() =>
{
if (Settings.Default.Debug)
{
Log.DebugFormat("Getting MainWindowPreviousState from settings with value '{0}'", Settings.Default.MainWindowPreviousState);
}
return Settings.Default.MainWindowPreviousState;
},
() =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Getting MainWindowFloatingSizeAndPosition from settings with value '{0}'", Settings.Default.MainWindowFloatingSizeAndPosition);
else
Log.DebugFormat("Getting tempFloatingSizeAndPosition with value '{0}'", tempFloatingSizeAndPosition);
}
if (persistedState)
return Settings.Default.MainWindowFloatingSizeAndPosition;
else
return tempFloatingSizeAndPosition;
},
() =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Getting MainWindowDockPosition from settings with value '{0}'", Settings.Default.MainWindowDockPosition);
else
Log.DebugFormat("Getting tempDockPosition with value '{0}'", tempDockPosition);
}
if (persistedState)
return Settings.Default.MainWindowDockPosition;
else
return tempDockPosition;
},
() =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Getting MainWindowDockSize from settings with value '{0}'", Settings.Default.MainWindowDockSize);
else
Log.DebugFormat("Getting tempDockSize with value '{0}'", tempDockSize);
}
if (persistedState)
return Settings.Default.MainWindowDockSize;
else
return tempDockSize;
},
() =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Getting MainWindowFullDockThicknessAsPercentageOfScreen from settings with value '{0}'", Settings.Default.MainWindowFullDockThicknessAsPercentageOfScreen);
else
Log.DebugFormat("Getting tempFullDockThickness with value '{0}'", tempFullDockThickness);
}
if (persistedState)
return Settings.Default.MainWindowFullDockThicknessAsPercentageOfScreen;
else
return tempFullDockThickness;
},
() =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Getting MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness from settings with value '{0}'", Settings.Default.MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness);
else
Log.DebugFormat("Getting tempCollapsedDockThickness with value '{0}'", tempCollapsedDockThickness);
}
if (persistedState)
return Settings.Default.MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness;
else
return tempCollapsedDockThickness;
},
() =>
{
if (Settings.Default.Debug)
{
Log.DebugFormat("Getting MainWindowMinimisedPosition from settings with value '{0}'", Settings.Default.MainWindowMinimisedPosition);
}
return Settings.Default.MainWindowMinimisedPosition;
},
o =>
{
if (Settings.Default.Debug)
{
Log.DebugFormat("Storing persistedState with value '{0}'", o);
}
persistedState = o;
},
o =>
{
if (Settings.Default.Debug)
{
Log.DebugFormat("Storing MainWindowOpacity to settings with value '{0}'", o);
}
Settings.Default.MainWindowOpacity = o;
},
state =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Storing MainWindowState to settings with value '{0}'", state);
else
Log.DebugFormat("Storing tempWindowState with value '{0}'", state);
}
if (persistedState)
Settings.Default.MainWindowState = state;
else
tempWindowState = state;
},
state =>
{
if (Settings.Default.Debug)
{
Log.DebugFormat("Storing MainWindowPreviousState to settings with value '{0}'", state);
}
Settings.Default.MainWindowPreviousState = state;
},
rect =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Storing MainWindowFloatingSizeAndPosition to settings with value '{0}'", rect);
else
Log.DebugFormat("Storing tempFloatingSizeAndPosition with value '{0}'", rect);
}
if (persistedState)
Settings.Default.MainWindowFloatingSizeAndPosition = rect;
else
tempFloatingSizeAndPosition = rect;
},
pos =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Storing MainWindowDockPosition to settings with value '{0}'", pos);
else
Log.DebugFormat("Storing tempDockPosition with value '{0}'", pos);
}
if (persistedState)
Settings.Default.MainWindowDockPosition = pos;
else
tempDockPosition = pos;
},
size =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Storing MainWindowDockSize to settings with value '{0}'", size);
else
Log.DebugFormat("Storing tempDockSize with value '{0}'", size);
}
if (persistedState)
Settings.Default.MainWindowDockSize = size;
else
tempDockSize = size;
},
t =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Storing MainWindowFullDockThicknessAsPercentageOfScreen to settings with value '{0}'", t);
else
Log.DebugFormat("Storing tempFullDockThickness with value '{0}'", t);
}
if (persistedState)
Settings.Default.MainWindowFullDockThicknessAsPercentageOfScreen = t;
else
tempFullDockThickness = t;
},
t =>
{
if (Settings.Default.Debug)
{
if (persistedState)
Log.DebugFormat("Storing MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness to settings with value '{0}'", t);
else
Log.DebugFormat("Storing tempCollapsedDockThickness with value '{0}'", t);
}
if (persistedState)
Settings.Default.MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness = t;
else
tempCollapsedDockThickness = t;
});
}
#endregion
#region Attach Unhandled Exception Handlers
// Make sure exceptions get logged, and a crash message appears
protected static void AttachUnhandledExceptionHandlers()
{
Action CloseLogsAndShowCrashWindow = () =>
{
#if !DEBUG
LogManager.Flush(1000);
LogManager.Shutdown();
Application.Current.Dispatcher.Invoke((Action)delegate
{
CrashWindow crashWindow = CrashWindow.Instance;
if (!crashWindow.IsVisible)
crashWindow.ShowDialog();
});
#endif
};
Current.DispatcherUnhandledException += (sender, args) =>
{
Log.Error("A DispatcherUnhandledException has been encountered...", args.Exception);
CloseLogsAndShowCrashWindow();
};
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
Log.Error("An UnhandledException has been encountered...", args.ExceptionObject as Exception);
CloseLogsAndShowCrashWindow();
};
TaskScheduler.UnobservedTaskException += (sender, args) =>
{
Log.Error("An UnobservedTaskException has been encountered...", args.Exception);
CloseLogsAndShowCrashWindow();
};
}
#endregion
#region Handle Corrupt Settings
protected static void HandleCorruptSettings()
{
try
{
//Attempting to read a setting from a corrupt user config file throws an exception
var upgradeRequired = Settings.Default.SettingsUpgradeRequired;
}
catch (ConfigurationErrorsException cee)
{
Log.Warn("User settings file is corrupt and needs to be corrected. Alerting user and shutting down.");
string filename = ((ConfigurationErrorsException)cee.InnerException).Filename;
if (MessageBox.Show(
OptiKey.Properties.Resources.CORRUPTED_SETTINGS_MESSAGE,
OptiKey.Properties.Resources.CORRUPTED_SETTINGS_TITLE,
MessageBoxButton.YesNo,
MessageBoxImage.Error) == MessageBoxResult.Yes)
{
File.Delete(filename);
try
{
RestartApp();
}
catch {} //Swallow any exceptions (e.g. DispatcherExceptions) - we're shutting down so it doesn't matter.
}
Current.Shutdown(); //Avoid the inevitable crash by shutting down gracefully
}
}
#endregion
#region Create Service Methods
protected static ICalibrationService CreateCalibrationService()
{
switch (Settings.Default.PointsSource)
{
case PointsSources.TheEyeTribe:
return new TheEyeTribeCalibrationService();
case PointsSources.IrisbondDuo:
return new IrisbondDuoCalibrationService();
case PointsSources.IrisbondHiru:
return new IrisbondHiruCalibrationService();
case PointsSources.Alienware17:
case PointsSources.SteelseriesSentry:
case PointsSources.TobiiEyeX:
case PointsSources.TobiiEyeTracker4C:
case PointsSources.TobiiEyeTracker5:
case PointsSources.TobiiRex:
case PointsSources.TobiiPcEyeGo:
case PointsSources.TobiiPcEyeGoPlus:
case PointsSources.TobiiPcEye5:
case PointsSources.TobiiPcEyeMini:
case PointsSources.TobiiX2_30:
case PointsSources.TobiiX2_60:
return new TobiiEyeXCalibrationService();
case PointsSources.VisualInteractionMyGaze:
return new MyGazeCalibrationService();
}
return null;
}
protected static IInputService CreateInputService(
IKeyStateService keyStateService,
IDictionaryService dictionaryService,
IAudioService audioService,
ICalibrationService calibrationService,
ICapturingStateManager capturingStateManager,
List<INotifyErrors> errorNotifyingServices)
{
Log.Info("Creating InputService.");
//Instantiate point source
IPointSource pointSource;
switch (Settings.Default.PointsSource)
{
case PointsSources.GazeTracker:
pointSource = new GazeTrackerSource(
Settings.Default.PointTtl,
Settings.Default.GazeTrackerUdpPort,
new Regex(GazeTrackerUdpRegex));
break;
case PointsSources.IrisbondDuo:
var irisBondDuoPointService = new IrisbondDuoPointService();
errorNotifyingServices.Add(irisBondDuoPointService);
pointSource = new PointServiceSource(
Settings.Default.PointTtl,
irisBondDuoPointService);
break;
case PointsSources.IrisbondHiru:
var irisBondHiruPointService = new IrisbondHiruPointService();
errorNotifyingServices.Add(irisBondHiruPointService);
pointSource = new PointServiceSource(
Settings.Default.PointTtl,
irisBondHiruPointService);
break;
case PointsSources.MousePosition:
pointSource = new MousePositionSource(
Settings.Default.PointTtl);
break;
case PointsSources.TheEyeTribe:
var theEyeTribePointService = new TheEyeTribePointService();
errorNotifyingServices.Add(theEyeTribePointService);
pointSource = new PointServiceSource(
Settings.Default.PointTtl,
theEyeTribePointService);
break;
case PointsSources.Alienware17:
case PointsSources.SteelseriesSentry:
case PointsSources.TobiiEyeX:
case PointsSources.TobiiEyeTracker4C:
case PointsSources.TobiiEyeTracker5:
case PointsSources.TobiiRex:
case PointsSources.TobiiPcEyeGo:
case PointsSources.TobiiPcEyeGoPlus:
case PointsSources.TobiiPcEye5:
case PointsSources.TobiiPcEyeMini:
case PointsSources.TobiiX2_30:
case PointsSources.TobiiX2_60:
var tobiiEyeXPointService = new TobiiEyeXPointService();
var tobiiEyeXCalibrationService = calibrationService as TobiiEyeXCalibrationService;
if (tobiiEyeXCalibrationService != null)
{
tobiiEyeXCalibrationService.EyeXHost = tobiiEyeXPointService.EyeXHost;
}
errorNotifyingServices.Add(tobiiEyeXPointService);
pointSource = new PointServiceSource(
Settings.Default.PointTtl,
tobiiEyeXPointService);
break;
case PointsSources.VisualInteractionMyGaze:
var myGazePointService = new MyGazePointService();
errorNotifyingServices.Add(myGazePointService);
pointSource = new PointServiceSource(
Settings.Default.PointTtl,
myGazePointService);
break;
default:
throw new ArgumentException("'PointsSource' settings is missing or not recognised! Please correct and restart OptiKey.");
}
ITriggerSource eyeGestureTriggerSource = new EyeGestureSource(pointSource);
//Instantiate key trigger source
ITriggerSource keySelectionTriggerSource;
switch (Settings.Default.KeySelectionTriggerSource)
{
case TriggerSources.Fixations:
keySelectionTriggerSource = new KeyFixationSource(
Settings.Default.KeySelectionTriggerFixationLockOnTime,
Settings.Default.KeySelectionTriggerFixationResumeRequiresLockOn,
Settings.Default.KeySelectionTriggerFixationDefaultCompleteTimes,
Settings.Default.KeySelectionTriggerFixationCompleteTimesByIndividualKey
? Settings.Default.KeySelectionTriggerFixationCompleteTimesByKeyValues
: null,
Settings.Default.KeySelectionTriggerIncompleteFixationTtl,
pointSource);
break;
case TriggerSources.KeyboardKeyDownsUps:
keySelectionTriggerSource = new KeyboardKeyDownUpSource(
Settings.Default.KeySelectionTriggerKeyboardKeyDownUpKey,
pointSource);
break;
case TriggerSources.MouseButtonDownUps:
keySelectionTriggerSource = new MouseButtonDownUpSource(
Settings.Default.KeySelectionTriggerMouseDownUpButton,
pointSource);
break;
case TriggerSources.XInputButtonDownUps:
keySelectionTriggerSource = new XInputButtonDownUpSource(
Settings.Default.KeySelectionTriggerGamepadXInputController,
Settings.Default.KeySelectionTriggerGamepadXInputButtonDownUpButton,
pointSource);
break;
case TriggerSources.DirectInputButtonDownUps:
keySelectionTriggerSource = new DirectInputButtonDownUpSource(
Settings.Default.KeySelectionTriggerGamepadDirectInputController,
Settings.Default.KeySelectionTriggerGamepadDirectInputButtonDownUpButton,
pointSource);
break;
default:
throw new ArgumentException(
"'KeySelectionTriggerSource' setting is missing or not recognised! Please correct and restart OptiKey.");
}
//Instantiate point trigger source
ITriggerSource pointSelectionTriggerSource;
switch (Settings.Default.PointSelectionTriggerSource)
{
case TriggerSources.Fixations:
pointSelectionTriggerSource = new PointFixationSource(
Settings.Default.PointSelectionTriggerFixationLockOnTime,
Settings.Default.PointSelectionTriggerFixationCompleteTime,
Settings.Default.PointSelectionTriggerLockOnRadiusInPixels,
Settings.Default.PointSelectionTriggerLockOnRadiusInPixels,
pointSource);
break;
case TriggerSources.KeyboardKeyDownsUps:
pointSelectionTriggerSource = new KeyboardKeyDownUpSource(
Settings.Default.PointSelectionTriggerKeyboardKeyDownUpKey,
pointSource);
break;
case TriggerSources.MouseButtonDownUps:
pointSelectionTriggerSource = new MouseButtonDownUpSource(
Settings.Default.PointSelectionTriggerMouseDownUpButton,
pointSource);
break;
case TriggerSources.XInputButtonDownUps:
pointSelectionTriggerSource = new XInputButtonDownUpSource(
Settings.Default.PointSelectionTriggerGamepadXInputController,
Settings.Default.PointSelectionTriggerGamepadXInputButtonDownUpButton,
pointSource);
break;
case TriggerSources.DirectInputButtonDownUps:
pointSelectionTriggerSource = new DirectInputButtonDownUpSource(
Settings.Default.PointSelectionTriggerGamepadDirectInputController,
Settings.Default.PointSelectionTriggerGamepadDirectInputButtonDownUpButton,
pointSource);
break;
default:
throw new ArgumentException(
"'PointSelectionTriggerSource' setting is missing or not recognised! "
+ "Please correct and restart OptiKey.");
}
var inputService = new InputService(keyStateService, dictionaryService, audioService, capturingStateManager,
pointSource, eyeGestureTriggerSource, keySelectionTriggerSource, pointSelectionTriggerSource);
inputService.RequestSuspend(); //Pause it initially
return inputService;
}
#endregion
#region Log Diagnostic Info
protected static void LogDiagnosticInfo()
{
Log.InfoFormat("Assembly version: {0}", DiagnosticInfo.AssemblyVersion);
var assemblyFileVersion = DiagnosticInfo.AssemblyFileVersion;
if (!string.IsNullOrEmpty(assemblyFileVersion))
{
Log.InfoFormat("Assembly file version: {0}", assemblyFileVersion);
}
if (DiagnosticInfo.IsApplicationNetworkDeployed)
if (DiagnosticInfo.IsApplicationNetworkDeployed)
{
Log.InfoFormat("ClickOnce deployment version: {0}", DiagnosticInfo.DeploymentVersion);
}
Log.InfoFormat("Running as admin: {0}", DiagnosticInfo.RunningAsAdministrator);
Log.InfoFormat("Process elevated: {0}", DiagnosticInfo.IsProcessElevated);
Log.InfoFormat("Process bitness: {0}", DiagnosticInfo.ProcessBitness);
Log.InfoFormat("OS version: {0}", DiagnosticInfo.OperatingSystemVersion);
Log.InfoFormat("OS service pack: {0}", DiagnosticInfo.OperatingSystemServicePack);
Log.InfoFormat("OS bitness: {0}", DiagnosticInfo.OperatingSystemBitness);
}
#endregion
#region Show Splash Screen
protected static async Task<bool> ShowSplashScreen(IInputService inputService, IAudioService audioService, MainViewModel mainViewModel, string splashTitle)
{
var taskCompletionSource = new TaskCompletionSource<bool>(); //Used to make this method awaitable on the InteractionRequest callback
if (Settings.Default.ShowSplashScreen)
{
Log.Info("Showing splash screen.");
var message = new StringBuilder();
message.AppendLine(string.Format(OptiKey.Properties.Resources.VERSION_DESCRIPTION, DiagnosticInfo.AssemblyVersion));
message.AppendLine(string.Format(OptiKey.Properties.Resources.KEYBOARD_AND_DICTIONARY_LANGUAGE_DESCRIPTION, Settings.Default.KeyboardAndDictionaryLanguage.ToDescription()));
message.AppendLine(string.Format(OptiKey.Properties.Resources.UI_LANGUAGE_DESCRIPTION, Settings.Default.UiLanguage.ToDescription()));
message.AppendLine(string.Format(OptiKey.Properties.Resources.POINTING_SOURCE_DESCRIPTION, Settings.Default.PointsSource.ToDescription()));
var keySelectionSb = new StringBuilder();
keySelectionSb.Append(Settings.Default.KeySelectionTriggerSource.ToDescription());
switch (Settings.Default.KeySelectionTriggerSource)
{
case TriggerSources.Fixations:
keySelectionSb.Append(string.Format(OptiKey.Properties.Resources.DURATION_FORMAT, Settings.Default.KeySelectionTriggerFixationDefaultCompleteTime.TotalMilliseconds));
break;
case TriggerSources.KeyboardKeyDownsUps:
keySelectionSb.Append(string.Format(" ({0})", Settings.Default.KeySelectionTriggerKeyboardKeyDownUpKey));
break;
case TriggerSources.MouseButtonDownUps:
keySelectionSb.Append(string.Format(" ({0})", Settings.Default.KeySelectionTriggerMouseDownUpButton));
break;
case TriggerSources.XInputButtonDownUps:
keySelectionSb.Append(string.Format(" ({0})", Settings.Default.KeySelectionTriggerGamepadXInputButtonDownUpButton));
break;
case TriggerSources.DirectInputButtonDownUps:
keySelectionSb.Append(string.Format(" ({0})", Settings.Default.KeySelectionTriggerGamepadDirectInputButtonDownUpButton));
break;
}
message.AppendLine(string.Format(OptiKey.Properties.Resources.KEY_SELECTION_TRIGGER_DESCRIPTION, keySelectionSb));
var pointSelectionSb = new StringBuilder();
pointSelectionSb.Append(Settings.Default.PointSelectionTriggerSource.ToDescription());
switch (Settings.Default.PointSelectionTriggerSource)
{
case TriggerSources.Fixations:
pointSelectionSb.Append(string.Format(OptiKey.Properties.Resources.DURATION_FORMAT, Settings.Default.PointSelectionTriggerFixationCompleteTime.TotalMilliseconds));
break;
case TriggerSources.KeyboardKeyDownsUps:
pointSelectionSb.Append(string.Format(" ({0})", Settings.Default.PointSelectionTriggerKeyboardKeyDownUpKey));
break;
case TriggerSources.MouseButtonDownUps:
pointSelectionSb.Append(string.Format(" ({0})", Settings.Default.PointSelectionTriggerMouseDownUpButton));
break;
case TriggerSources.XInputButtonDownUps:
pointSelectionSb.Append(string.Format(" ({0})", Settings.Default.PointSelectionTriggerGamepadXInputButtonDownUpButton));
break;
case TriggerSources.DirectInputButtonDownUps:
pointSelectionSb.Append(string.Format(" ({0})", Settings.Default.PointSelectionTriggerGamepadDirectInputButtonDownUpButton));
break;
}
message.AppendLine(string.Format(OptiKey.Properties.Resources.POINT_SELECTION_DESCRIPTION, pointSelectionSb));
message.AppendLine(OptiKey.Properties.Resources.MANAGEMENT_CONSOLE_DESCRIPTION);
message.AppendLine(OptiKey.Properties.Resources.WEBSITE_DESCRIPTION);
message.AppendLine("By Julius Sweetland : @OptiKey_Julius");
inputService.RequestSuspend();
audioService.PlaySound(Settings.Default.InfoSoundFile, Settings.Default.InfoSoundVolume);
mainViewModel.RaiseToastNotification(
splashTitle,
message.ToString(),
NotificationTypes.Normal,
() =>
{
inputService.RequestResume();
taskCompletionSource.SetResult(true);
});
}
else
{
taskCompletionSource.SetResult(false);
}
return await taskCompletionSource.Task;
}
#endregion
#region Check For Updates
protected static async Task<bool> CheckForUpdates(IInputService inputService, IAudioService audioService, MainViewModel mainViewModel)
{
var taskCompletionSource = new TaskCompletionSource<bool>(); //Used to make this method awaitable on the InteractionRequest callback
try
{
if (Settings.Default.CheckForUpdates)
{
Log.InfoFormat("Checking GitHub for updates (repo owner:'{0}', repo name:'{1}').", GitHubRepoOwner, GitHubRepoName);
var github = new GitHubClient(new ProductHeaderValue("OptiKey"));
var releases = await github.Repository.Release.GetAll(GitHubRepoOwner, GitHubRepoName);
var latestRelease = releases.FirstOrDefault(release => !release.Prerelease);
if (latestRelease != null)
{
var currentVersion = new Version(DiagnosticInfo.AssemblyVersion); //Convert from string
//Discard revision (4th number) as my GitHub releases are tagged with "vMAJOR.MINOR.PATCH"
currentVersion = new Version(currentVersion.Major, currentVersion.Minor, currentVersion.Build);
if (!string.IsNullOrEmpty(latestRelease.TagName))
{
var tagNameWithoutLetters =
new string(latestRelease.TagName.ToCharArray().Where(c => !char.IsLetter(c)).ToArray());