forked from shanselman/babysmash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Controller.cs
631 lines (555 loc) · 22.8 KB
/
Controller.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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Deployment.Application;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using BabySmash.Properties;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using WinForms = System.Windows.Forms;
namespace BabySmash
{
using System.Globalization;
using System.IO;
using System.Speech.Synthesis;
using System.Text;
using Newtonsoft.Json;
public class Controller
{
[DllImport("user32.dll")]
private static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private static Controller instance = new Controller();
public bool isOptionsDialogShown { get; set; }
private bool isDrawing = false;
private readonly SpeechSynthesizer objSpeech = new SpeechSynthesizer();
private readonly List<MainWindow> windows = new List<MainWindow>();
private DispatcherTimer timer = new DispatcherTimer();
private Queue<Shape> ellipsesQueue = new Queue<Shape>();
private Dictionary<string, List<UserControl>> figuresUserControlQueue = new Dictionary<string, List<UserControl>>();
//private ApplicationDeployment deployment = null;
private WordFinder wordFinder = new WordFinder("Words.txt");
/// <summary>Prevents a default instance of the Controller class from being created.</summary>
private Controller() { }
public static Controller Instance
{
get { return instance; }
}
//void deployment_CheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)
//{
// if (e.Error == null && e.UpdateAvailable)
// {
// try
// {
// MainWindow w = this.windows[0];
// w.updateProgress.Value = 0;
// w.UpdateAvailableLabel.Visibility = Visibility.Visible;
// deployment.UpdateAsync();
// }
// catch (InvalidOperationException ex)
// {
// Debug.WriteLine(ex.ToString());
// MainWindow w = this.windows[0];
// w.UpdateAvailableLabel.Visibility = Visibility.Hidden;
// }
// }
//}
//void deployment_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
//{
// MainWindow w = this.windows[0];
// w.updateProgress.Value = e.ProgressPercentage;
//}
void deployment_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
Debug.WriteLine(e.ToString());
return;
}
MainWindow w = this.windows[0];
w.UpdateAvailableLabel.Visibility = Visibility.Hidden;
}
public void Launch()
{
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = new TimeSpan(0, 0, 1);
int Number = 0;
//if (ApplicationDeployment.IsNetworkDeployed)
//{
// deployment = ApplicationDeployment.CurrentDeployment;
// deployment.UpdateCompleted += new System.ComponentModel.AsyncCompletedEventHandler(deployment_UpdateCompleted);
// deployment.UpdateProgressChanged += deployment_UpdateProgressChanged;
// deployment.CheckForUpdateCompleted += deployment_CheckForUpdateCompleted;
// try
// {
// deployment.CheckForUpdateAsync();
// }
// catch (InvalidOperationException e)
// {
// Debug.WriteLine(e.ToString());
// }
//}
foreach (WinForms.Screen s in WinForms.Screen.AllScreens)
{
MainWindow m = new MainWindow(this)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = s.WorkingArea.Left,
Top = s.WorkingArea.Top,
Width = s.WorkingArea.Width,
Height = s.WorkingArea.Height,
WindowStyle = WindowStyle.None,
ResizeMode = ResizeMode.NoResize,
Topmost = true,
AllowsTransparency = Settings.Default.TransparentBackground,
Background = (Settings.Default.TransparentBackground ? new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)) : Brushes.WhiteSmoke),
Name = "Window" + Number++.ToString()
};
figuresUserControlQueue[m.Name] = new List<UserControl>();
m.Show();
m.MouseLeftButtonDown += HandleMouseLeftButtonDown;
m.MouseWheel += HandleMouseWheel;
m.WindowState = WindowState.Maximized;
windows.Add(m);
}
//Only show the info label on the FIRST monitor.
windows[0].infoLabel.Visibility = Visibility.Visible;
//Startup sound
Win32Audio.PlayWavResourceYield("EditedJackPlaysBabySmash.wav");
string[] args = Environment.GetCommandLineArgs();
string ext = System.IO.Path.GetExtension(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
if (ApplicationDeployment.IsNetworkDeployed && (ApplicationDeployment.CurrentDeployment.IsFirstRun || ApplicationDeployment.CurrentDeployment.UpdatedVersion != ApplicationDeployment.CurrentDeployment.CurrentVersion))
{
//if someone made us a screensaver, then don't show the options dialog.
if ((args != null && args[0] != "/s") && String.CompareOrdinal(ext, ".SCR") != 0)
{
ShowOptionsDialog();
}
}
#if !false
timer.Start();
#endif
}
void timer_Tick(object sender, EventArgs e)
{
if (isOptionsDialogShown)
{
return;
}
try
{
IntPtr windowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
SetForegroundWindow(windowHandle);
SetFocus(windowHandle);
}
catch (Exception)
{
//Wish me luck!
}
}
public void ProcessKey(FrameworkElement uie, KeyEventArgs e)
{
if (uie.IsMouseCaptured)
{
uie.ReleaseMouseCapture();
}
char displayChar = GetDisplayChar(e.Key);
AddFigure(uie, displayChar);
}
private char GetDisplayChar(Key key)
{
// If a number on the normal number track is pressed, display the number.
if (key >= Key.D0 && key <= Key.D9)
{
return (char)('0' + key - Key.D0);
}
// If a number on the numpad is pressed, display the number.
if (key >= Key.NumPad0 && key <= Key.NumPad9)
{
return (char)('0' + key - Key.NumPad0);
}
try
{
return char.ToUpperInvariant(TryGetLetter(key));
}
catch (Exception ex)
{
Debug.Assert(false, ex.ToString());
return '*';
}
}
public enum MapType : uint
{
MAPVK_VK_TO_VSC = 0x0,
MAPVK_VSC_TO_VK = 0x1,
MAPVK_VK_TO_CHAR = 0x2,
MAPVK_VSC_TO_VK_EX = 0x3,
}
[DllImport("user32.dll")]
public static extern int ToUnicode(
uint wVirtKey,
uint wScanCode,
byte[] lpKeyState,
[Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 4)]
StringBuilder pwszBuff,
int cchBuff,
uint wFlags);
[DllImport("user32.dll")]
public static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
public static extern uint MapVirtualKey(uint uCode, MapType uMapType);
private static char TryGetLetter(Key key)
{
char ch = ' ';
int virtualKey = KeyInterop.VirtualKeyFromKey(key);
byte[] keyboardState = new byte[256];
GetKeyboardState(keyboardState);
uint scanCode = MapVirtualKey((uint)virtualKey, MapType.MAPVK_VK_TO_VSC);
StringBuilder stringBuilder = new StringBuilder(2);
int result = ToUnicode((uint)virtualKey, scanCode, keyboardState, stringBuilder, stringBuilder.Capacity, 0);
switch (result)
{
case -1:
break;
case 0:
break;
case 1:
{
ch = stringBuilder[0];
break;
}
default:
{
ch = stringBuilder[0];
break;
}
}
return ch;
}
private void AddFigure(FrameworkElement uie, char c)
{
FigureTemplate template = FigureGenerator.GenerateFigureTemplate(c);
foreach (MainWindow window in this.windows)
{
UserControl f = FigureGenerator.NewUserControlFrom(template);
window.AddFigure(f);
var queue = figuresUserControlQueue[window.Name];
queue.Add(f);
// Letters should already have accurate width and height, but others may them assigned.
if (double.IsNaN(f.Width) || double.IsNaN(f.Height))
{
f.Width = 300;
f.Height = 300;
}
Canvas.SetLeft(f, Utils.RandomBetweenTwoNumbers(0, Convert.ToInt32(window.ActualWidth - f.Width)));
Canvas.SetTop(f, Utils.RandomBetweenTwoNumbers(0, Convert.ToInt32(window.ActualHeight - f.Height)));
Storyboard storyboard = Animation.CreateDPAnimation(uie, f,
UIElement.OpacityProperty,
new Duration(TimeSpan.FromSeconds(Settings.Default.FadeAfter)), 1, 0);
if (Settings.Default.FadeAway) storyboard.Begin(uie);
IHasFace face = f as IHasFace;
if (face != null)
{
face.FaceVisible = Settings.Default.FacesOnShapes ? Visibility.Visible : Visibility.Hidden;
}
if (queue.Count > Settings.Default.ClearAfter)
{
window.RemoveFigure(queue[0]);
queue.RemoveAt(0);
}
}
// Find the last word typed, if applicable.
string lastWord = this.wordFinder.LastWord(figuresUserControlQueue.Values.First());
if (lastWord != null)
{
foreach (MainWindow window in this.windows)
{
this.wordFinder.AnimateLettersIntoWord(figuresUserControlQueue[window.Name], lastWord);
}
SpeakString(lastWord);
}
else
{
PlaySound(template);
}
}
//private static DoubleAnimationUsingKeyFrames ApplyZoomOut(UserControl u)
//{
// Tweener.TransitionType rt1 = Tweener.TransitionType.EaseOutExpo;
// var ani1 = Tweener.Tween.CreateAnimation(rt1, 1, 0, TimeSpan.FromSeconds(0.5));
// u.RenderTransformOrigin = new Point(0.5, 0.5);
// var group = new TransformGroup();
// u.RenderTransform = group;
// ani1.Completed += new EventHandler(ani1_Completed);
// group.Children.Add(new ScaleTransform());
// group.Children[0].BeginAnimation(ScaleTransform.ScaleXProperty, ani1);
// group.Children[0].BeginAnimation(ScaleTransform.ScaleYProperty, ani1);
// return ani1;
//}
//static void ani1_Completed(object sender, EventArgs e)
//{
// AnimationClock clock = sender as AnimationClock;
// Debug.Write(sender.ToString());
// UserControl foo = sender as UserControl;
// UserControl toBeRemoved = queue.Dequeue() as UserControl;
// Canvas container = toBeRemoved.Parent as Canvas;
// container.Children.Remove(toBeRemoved);
//}
void HandleMouseWheel(object sender, MouseWheelEventArgs e)
{
UserControl foo = sender as UserControl; //expected this on Sender!
if (foo != null)
{
if (e.Delta < 0)
{
Animation.ApplyZoom(foo, new Duration(TimeSpan.FromSeconds(0.5)), 2.5);
}
else
{
Animation.ApplyZoom(foo, new Duration(TimeSpan.FromSeconds(0.5)), 0.5);
}
}
}
void HandleMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
UserControl f = e.Source as UserControl;
if (f != null && f.Opacity > 0.1) //can it be seen?
{
isDrawing = true; //HACK: This is a cheat to stop the mouse draw action.
Animation.ApplyRandomAnimationEffect(f, Duration.Automatic);
PlayLaughter(); //Might be better to re-speak the name, color, etc.
}
}
public void PlaySound(FigureTemplate template)
{
if (Settings.Default.Sounds == "Laughter")
{
PlayLaughter();
}
if (objSpeech != null && Settings.Default.Sounds == "Speech")
{
if (template.Letter != null && template.Letter.Length == 1 && Char.IsLetterOrDigit(template.Letter[0]))
{
SpeakString(template.Letter);
}
else
{
SpeakString(GetLocalizedString(Utils.ColorToString(template.Color)) + " " + template.Name);
}
}
}
/// <summary>
/// Returns <param name="key"></param> if value or culture is not found.
/// </summary>
public static string GetLocalizedString(string key)
{
CultureInfo keyboardLanguage = System.Windows.Forms.InputLanguage.CurrentInputLanguage.Culture;
string culture = keyboardLanguage.Name;
string path = $@"Resources\Strings\{culture}.json";
string path2 = @"Resources\Strings\en-EN.json";
string jsonConfig = null;
if (File.Exists(path))
{
jsonConfig = File.ReadAllText(path);
}
else if (File.Exists(path2))
{
jsonConfig = File.ReadAllText(path2);
}
if (jsonConfig != null)
{
Dictionary<string, object> config = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonConfig);
if (config.ContainsKey(key))
{
return config[key].ToString();
}
}
else
{
System.Diagnostics.Debug.Assert(false, "No file");
}
return key;
}
private void PlayLaughter()
{
Win32Audio.PlayWavResource(Utils.GetRandomSoundFile());
}
private void SpeakString(string s)
{
ThreadedSpeak ts = new ThreadedSpeak(s);
ts.Speak();
}
private class ThreadedSpeak
{
private string Word = null;
SpeechSynthesizer SpeechSynth = new SpeechSynthesizer();
public ThreadedSpeak(string Word)
{
this.Word = Word;
CultureInfo keyboardLanguage = System.Windows.Forms.InputLanguage.CurrentInputLanguage.Culture;
InstalledVoice neededVoice = this.SpeechSynth.GetInstalledVoices(keyboardLanguage).FirstOrDefault();
if (neededVoice == null)
{
//http://superuser.com/questions/590779/how-to-install-more-voices-to-windows-speech
//https://msdn.microsoft.com/en-us/library/windows.media.speechsynthesis.speechsynthesizer.voice.aspx
//http://stackoverflow.com/questions/34776593/speechsynthesizer-selectvoice-fails-with-no-matching-voice-is-installed-or-th
this.Word = "Unsupported Language";
}
else if (!neededVoice.Enabled)
{
this.Word = "Voice Disabled";
}
else
{
try
{
this.SpeechSynth.SelectVoice(neededVoice.VoiceInfo.Name);
}
catch (Exception ex)
{
Debug.Assert(false, ex.ToString());
}
}
SpeechSynth.Rate = -1;
SpeechSynth.Volume = 100;
}
public void Speak()
{
Thread oThread = new Thread(new ThreadStart(this.Start));
oThread.Start();
}
private void Start()
{
try
{
SpeechSynth.Speak(Word);
}
catch (Exception e)
{
System.Diagnostics.Trace.WriteLine(e.ToString());
}
}
}
public void ShowOptionsDialog()
{
bool foo = Settings.Default.TransparentBackground;
isOptionsDialogShown = true;
var o = new Options();
Mouse.Capture(null);
foreach (MainWindow m in this.windows)
{
m.Topmost = false;
}
o.Topmost = true;
o.Focus();
o.ShowDialog();
Debug.Write("test");
foreach (MainWindow m in this.windows)
{
m.Topmost = true;
//m.ResetCanvas();
}
isOptionsDialogShown = false;
if (foo != Settings.Default.TransparentBackground)
{
MessageBoxResult result = MessageBox.Show(
"You've changed the Window Transparency Option. We'll need to restart BabySmash! for you to see the change. Pressing YES will restart BabySmash!. Is that OK?",
"Need to Restart", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
Application.Current.Shutdown();
System.Windows.Forms.Application.Restart();
}
}
}
public void MouseDown(MainWindow main, MouseButtonEventArgs e)
{
if (isDrawing || Settings.Default.MouseDraw) return;
// Create a new Ellipse object and add it to canvas.
Point ptCenter = e.GetPosition(main.mouseCursorCanvas);
MouseDraw(main, ptCenter);
isDrawing = true;
main.CaptureMouse();
Win32Audio.PlayWavResource("smallbumblebee.wav");
}
public void MouseWheel(MainWindow main, MouseWheelEventArgs e)
{
if (e.Delta > 0)
{
Win32Audio.PlayWavResourceYield("rising.wav");
}
else
{
Win32Audio.PlayWavResourceYield("falling.wav");
}
}
public void MouseUp(MainWindow main, MouseButtonEventArgs e)
{
isDrawing = false;
if (Settings.Default.MouseDraw) return;
main.ReleaseMouseCapture();
}
public void MouseMove(MainWindow main, MouseEventArgs e)
{
if (isOptionsDialogShown)
{
main.ReleaseMouseCapture();
return;
}
if (Settings.Default.MouseDraw && main.IsMouseCaptured == false)
main.CaptureMouse();
if (isDrawing || Settings.Default.MouseDraw)
{
MouseDraw(main, e.GetPosition(main));
}
// Cheesy, but hotkeys are ignored when the mouse is captured.
// However, if we don't capture and release, the shapes will draw forever.
if (Settings.Default.MouseDraw && main.IsMouseCaptured)
main.ReleaseMouseCapture();
}
private void MouseDraw(MainWindow main, Point p)
{
//randomize at some point?
Shape shape = new Ellipse
{
Stroke = SystemColors.WindowTextBrush,
StrokeThickness = 0,
Fill = Utils.GetGradientBrush(Utils.GetRandomColor()),
Width = 50,
Height = 50
};
ellipsesQueue.Enqueue(shape);
main.mouseDragCanvas.Children.Add(shape);
Canvas.SetLeft(shape, p.X - 25);
Canvas.SetTop(shape, p.Y - 25);
if (Settings.Default.MouseDraw)
Win32Audio.PlayWavResourceYield("smallbumblebee.wav");
if (ellipsesQueue.Count > 30) //this is arbitrary
{
Shape shapeToRemove = ellipsesQueue.Dequeue();
main.mouseDragCanvas.Children.Remove(shapeToRemove);
}
}
//private static void ResetCanvas(MainWindow main)
//{
// main.ResetCanvas();
//}
public void LostMouseCapture(MainWindow main, MouseEventArgs e)
{
if (Settings.Default.MouseDraw) return;
if (isDrawing) isDrawing = false;
}
}
}