-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
732 lines (650 loc) · 22.8 KB
/
Program.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
using System;
using System.Diagnostics;
using System.IO;
using System.Speech.Synthesis;
using System.Text.RegularExpressions;
using NAudio.Wave;
public class LogSharpwin
{
private StreamWriter logWriter;
private bool isEnabled;
public LogSharpwin()
{
string executableName = Process.GetCurrentProcess().ProcessName + ".exe";
if (executableName.Equals("log-sharpwin.exe", StringComparison.OrdinalIgnoreCase))
{
isEnabled = true;
int processId = Process.GetCurrentProcess().Id;
string tempPath = Path.GetTempPath();
string logFileName = $"sharpwin_{processId}.log";
string fullPath = Path.Combine(tempPath, logFileName);
// Initialize StreamWriter for the log file with autoFlush set to true
logWriter = new StreamWriter(fullPath, append: true, encoding: System.Text.Encoding.UTF8)
{
AutoFlush = true
};
}
else
{
isEnabled = false;
}
}
public void Log(string message)
{
if (isEnabled)
{
logWriter.WriteLine($"{message}");
}
}
// Ensure resources are properly released
public void Close()
{
logWriter?.Close();
}
}
class Program
{
private static Logger _debugLogger = Logger.GetInstance();
private static string _version = "1.3.0";
private static string _name = "SharpWin";
private static StateStore _ss = new StateStore();
private static SpeechSynthesizer _speaker = new SpeechSynthesizer();
private static TonePlayer _tonePlayer = new TonePlayer();
private static AudioTargetQueue _audioQueue = new AudioTargetQueue();
static async Task Main(string[] args)
{
try
{
await _debugLogger.Log("Enter: main");
LogSharpwin logger = new LogSharpwin();
_audioQueue.SetTarget(_ss.AudioTarget);
if (_ss.AudioTarget == "right" || _ss.AudioTarget == "left")
{
await DoSpeak("Notifications Server Running");
}
else
{
await InstantVersion();
}
while (true)
{
try
{
string l = Console.ReadLine();
if (l == null)
{
return;
}
logger.Log(l);
await _debugLogger.Log($"got line {l}");
(string cmd, string parameters) = await IsolateCmdAndParams(l);
switch (cmd)
{
case "a":
await ProcessAndQueueAudioIcon(parameters);
break;
case "c":
await DoDiscard(cmd, parameters);
break;
case "d":
await DispatchPendingQueue();
break;
case "l":
await InstantLetter(parameters);
break;
case "p":
await DoPlaySound(parameters);
break;
case "q":
await QueueLine(cmd, parameters);
break;
case "s":
await QueueLine(cmd, parameters);
break;
case "sh":
await QueueLine(cmd, parameters);
break;
case "t":
await QueueLine(cmd, parameters);
break;
case "tts_allcaps_beep":
await QueueLine(cmd, parameters);
break;
case "tts_exit":
await InstantTtsExit();
break;
case "tts_pause":
await DoDiscard(cmd, parameters);
//await InstantTtsPause();
break;
case "tts_reset":
await InstantTtsReset();
break;
case "tts_resume":
await DoDiscard(cmd, parameters);
//await InstantTtsResume();
break;
case "tts_say":
await InstantTtsSay(parameters);
break;
case "tts_set_character_scale":
await QueueLine(cmd, parameters);
break;
case "tts_set_pitch_multiplier":
await QueueLine(cmd, parameters);
break;
case "tts_set_punctuations":
await QueueLine(cmd, parameters);
break;
case "tts_set_sound_volume":
await QueueLine(cmd, parameters);
break;
case "tts_set_speech_rate":
await InstantSetSpeechRate(parameters);
break;
case "tts_set_tone_volume":
await QueueLine(cmd, parameters);
break;
case "set_lang":
await TtsSetVoice(parameters);
break;
case "tts_set_voice_volume":
await QueueLine(cmd, parameters);
break;
case "tts_split_caps":
await QueueLine(cmd, parameters);
break;
case "tts_sync_state":
await DoDiscard(cmd, parameters);
//await ProcessAndQueueSync(l);
break;
case "version":
await InstantVersion();
break;
default:
await UnknownLine(l);
break;
}
}
catch (Exception e)
{
_debugLogger.Log($"Inner Error: {e.Message}");
Console.WriteLine($"Error: {e.Message}");
}
} // End of while loop
}
catch (Exception e)
{
_debugLogger.Log($"Outer Error: {e.Message}");
Console.WriteLine($"Error: {e.Message}");
}
}
private static async Task DispatchPendingQueue()
{
(string cmd, string parameters) item;
while ((item = _ss.PopFromPendingQueue()) != (null, null))
{
await _debugLogger.Log($"got queued {item.cmd} {item.parameters}");
switch (item.cmd)
{
case "p":
await DoPlaySound(item.parameters);
break;
case "s":
await DoStopSpeaking();
break;
case "sh":
await DoSilence(item.parameters);
break;
case "q":
await DoSpeak(item.parameters);
break;
case "t":
await DoTone(item.parameters);
break;
case "tts_allcaps_beep":
await TtsAllCapsBeep(item.parameters);
break;
case "tts_set_character_scale":
await TtsSetCharacterScale(item.parameters);
break;
case "tts_set_pitch_multiplier":
await TtsSetPitchMultiplier(item.parameters);
break;
case "tts_set_punctuations":
await TtsSetPunctuations(item.parameters);
break;
case "tts_set_sound_volume":
await TtsSetSoundVolume(item.parameters);
break;
break;
case "tts_set_tone_volume":
await TtsSetToneVolume(item.parameters);
break;
case "tts_set_voice":
await TtsSetVoice(item.parameters);
break;
case "tts_set_voice_volume":
await TtsSetVoiceVolume(item.parameters);
break;
case "tts_split_caps":
await TtsSplitCaps(item.parameters);
break;
default:
await ImpossibleQueue(item.cmd, item.parameters);
break;
}
}
}
private static async Task QueueLine(string cmd, string parameters)
{
await _debugLogger.Log("Enter: queueLine");
_ss.AppendToPendingQueue((cmd, parameters));
}
private static async Task<List<string>> SplitOnSquareStar(string input)
{
string separator = "[*]";
List<string> result = new List<string>();
string[] parts = input.Split(new[] { separator }, StringSplitOptions.None);
for (int index = 0; index < parts.Length; index++)
{
result.Add(parts[index]);
// Add the separator back except after the last part
if (index < parts.Length - 1)
{
result.Add(separator);
}
}
return result;
}
private static async Task ProcessAndQueueSpeech(string p)
{
}
private static async Task<string> InsertSpaceBeforeUppercase(string input)
{
await _debugLogger.Log("Enter: insertSpaceBeforeUppercase");
string pattern = "(?<=[a-z])(?=[A-Z])";
Regex regex = new Regex(pattern);
string modifiedString = regex.Replace(input, " ");
return modifiedString;
}
private static async Task InstantTtsReset()
{
await _debugLogger.Log("Enter: instantTtsReset");
await DoStopAll();
_ss = new StateStore();
}
private static async Task InstantVersion()
{
await _debugLogger.Log("Enter: instantVersion");
string sayVersion = _version.Replace(".", " dot ");
await DoStopAll();
await InstantTtsSay($"{_name} {sayVersion}");
}
private static async Task DoSilence(string p)
{
await _debugLogger.Log("Enter: doSilence");
TimeSpan oldPostDelay = _ss.PostDelay;
if (int.TryParse(p, out int durationInMillis))
{
_ss.SetPostDelay(TimeSpan.FromMilliseconds(durationInMillis));
}
await DoSpeak("");
_ss.SetPostDelay(oldPostDelay);
}
private static async Task InstantTtsResume()
{
await _debugLogger.Log("Enter: instantTtsResume");
_speaker.Resume();
}
private static async Task InstantLetter(string p)
{
await _debugLogger.Log("Enter: unknownLine");
float oldPitchMultiplier = _ss.PitchMultiplier;
TimeSpan oldPreDelay = _ss.PreDelay;
if (await IsFirstLetterCapital(p))
{
if (_ss.AllCapsBeep)
{
await DoTone("500 50");
}
else
{
_ss.SetPitchMultiplier(1.5f);
}
}
int oldSpeechRate = _ss.SpeechRate;
_ss.SetSpeechRate(_ss.GetCharacterRate());
await DoStopSpeaking();
await DoSpeak(p.ToLower());
_ss.SetPitchMultiplier(oldPitchMultiplier);
_ss.SetSpeechRate(oldSpeechRate);
_ss.SetPreDelay(oldPreDelay);
}
private static async Task DoDiscard(string c, string p)
{
await _debugLogger.Log($"Intentionally Discarded: {c} {p}");
}
private static async Task DoStopSpeaking()
{
await _debugLogger.Log("Enter: doStopSpeaking");
_speaker.SpeakAsyncCancelAll();
_audioQueue.Stop();
}
private static async Task<bool> IsFirstLetterCapital(string str)
{
await _debugLogger.Log("Enter: isFirstLetterCapital");
if (string.IsNullOrEmpty(str))
{
return false;
}
char firstChar = str[0];
return char.IsUpper(firstChar) && char.IsLetter(firstChar);
}
private static async Task InstantTtsPause()
{
await _debugLogger.Log("Enter: instantTtsPause");
_speaker.Pause();
}
private static async Task UnknownLine(string line)
{
await _debugLogger.Log("Enter: unknownLine");
await _debugLogger.Log($"Unknown command: {line}");
Console.WriteLine($"Unknown command: {line}");
}
private static async Task ImpossibleQueue(string cmd, string parameters)
{
await _debugLogger.Log("Enter: impossibleQueue");
await _debugLogger.Log($"Impossible queue item '{cmd}' '{parameters}'");
Console.WriteLine($"Impossible queue item '{cmd}' '{parameters}'");
}
private static async Task<string> ExtractVoice(string str)
{
await _debugLogger.Log("Enter: extractVoice");
string pattern = @"\[\{voice\s+([^\}]+)\}\]";
Match match = Regex.Match(str, pattern);
if (match.Success)
{
return match.Groups[1].Value;
}
return null;
}
private static async Task ProcessAndQueueAudioIcon(string p)
{
await _debugLogger.Log("Enter: processAndQueueAudioIcon");
_ss.AppendToPendingQueue(("p", p));
}
private static async Task ProcessAndQueueCodes(string p)
{
await _debugLogger.Log("Enter: processAndQueueCodes");
string voice = await ExtractVoice(p);
if (!string.IsNullOrEmpty(voice))
{
_ss.AppendToPendingQueue(("tts_set_voice", voice));
}
}
private static async Task<string> ReplacePunctuations(string s)
{
switch (_ss.Punctuations)
{
case "all":
return (await ReplaceAllPuncs(s));
case "some":
return (await ReplaceSomePuncs(s));
default:
return (await ReplaceBasePuncs(s));
}
}
private static async Task<string> ReplaceBasePuncs(string line)
{
await _debugLogger.Log("Enter: replaceBasePuncs");
return line
.Replace("%", " percent ")
.Replace("$", " dollar ");
}
private static async Task<string> ReplaceSomePuncs(string line)
{
await _debugLogger.Log("Enter: replaceSomePuncs");
return (await ReplaceBasePuncs(line))
.Replace("#", " pound ")
.Replace("-", " dash ")
.Replace("\"", " quote ")
.Replace("(", " leftParen ")
.Replace(")", " rightParen ")
.Replace("*", " star ")
.Replace(";", " semi ")
.Replace(":", " colon ")
.Replace("\n", "")
.Replace("\\", " backslash ")
.Replace("/", " slash ")
.Replace("+", " plus ")
.Replace("=", " equals ")
.Replace("~", " tilda ")
.Replace("`", " backquote ")
.Replace("!", " exclamation ")
.Replace("^", " caret ");
}
private static async Task<string> ReplaceAllPuncs(string line)
{
await _debugLogger.Log("Enter: replaceAllPuncs");
return (await ReplaceSomePuncs(line))
.Replace("<", " less than ")
.Replace(">", " greater than ")
.Replace("'", " apostrophe ")
.Replace("*", " star ")
.Replace("@", " at sign ")
.Replace("_", " underline ")
.Replace(".", " dot ")
.Replace(",", " comma ");
}
private static async Task<string> BuildSsml(string p)
{
await _debugLogger.Log("Enter: BuildSsml");
// <audio src='path/to/your/audio/file.wav'/>
string ssml = @"
<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>
<voice name='" + _ss.Voice + @"'>
" + p + @"
</voice>
</speak>";
return ssml;
}
private static async Task TtsSplitCaps(string p)
{
await _debugLogger.Log("Enter: TtsSplitCaps");
_ss.SetSplitCaps(p == "1");
}
private static async Task TtsSetVoice(string p)
{
await _debugLogger.Log("Enter: ttsSetVoice");
string[] ps = p.Split(' ');
if (ps.Length == 2)
{
_ss.SetVoice(ps[0]);
if (ps[1] == "t")
{
DoSpeak("Voice set to: " + _ss.Voice);
}
}
}
private static async Task TtsSetToneVolume(string p)
{
await _debugLogger.Log("Enter: ttsSetToneVolume");
if (float.TryParse(p, out float toneVolume))
{
_ss.SetToneVolume(toneVolume);
}
}
private static async Task TtsSetSoundVolume(string p)
{
await _debugLogger.Log("Enter: ttsSetSoundVolume");
if (float.TryParse(p, out float soundVolume))
{
_ss.SetSoundVolume(soundVolume);
}
}
private static async Task TtsSetVoiceVolume(string p)
{
await _debugLogger.Log("Enter: ttsSetVoiceVolume");
if (int.TryParse(p, out int voiceVolume))
{
_ss.SetVoiceVolume(voiceVolume);
}
}
private static async Task InstantSetSpeechRate(string p)
{
await _debugLogger.Log("Enter: InstantSetSpeechRate");
if (int.TryParse(p, out int speechRate))
{
_ss.SetSpeechRate(speechRate);
}
}
private static async Task TtsSetPitchMultiplier(string p)
{
await _debugLogger.Log("Enter: ttsSetPitchMultiplier");
if (float.TryParse(p, out float pitchMultiplier))
{
_ss.SetPitchMultiplier(pitchMultiplier);
}
}
private static async Task TtsSetPunctuations(string p)
{
await _debugLogger.Log("Enter: ttsSetPunctuations");
_ss.SetPunctuations(p);
}
private static async Task TtsSetCharacterScale(string p)
{
await _debugLogger.Log("Enter: ttsSetCharacterScale");
if (float.TryParse(p, out float characterScale))
{
_ss.SetCharacterScale(characterScale);
}
}
private static async Task TtsAllCapsBeep(string p)
{
await _debugLogger.Log("Enter: ttsAllCapsBeep");
_ss.SetAllCapsBeep(p == "1");
}
private static async Task ProcessAndQueueSync(string p)
{
await _debugLogger.Log("Enter: processAndQueueSync");
string[] ps = p.Split(' ');
if (ps.Length == 4)
{
string punct = ps[0];
_ss.AppendToPendingQueue(("tts_set_punctuations", punct));
string splitCaps = ps[1];
_ss.AppendToPendingQueue(("tts_split_caps", splitCaps));
string beepCaps = ps[2];
_ss.AppendToPendingQueue(("tts_allcaps_beep", beepCaps));
string rate = ps[3];
_ss.AppendToPendingQueue(("tts_set_speech_rate", rate));
}
}
private static async Task DoTone(string p)
{
await _debugLogger.Log("Enter: doTone");
string[] ps = p.Split(' ');
int frequency = int.TryParse(ps[0], out int f) ? f : 500;
int durationInMillis = int.TryParse(ps[1], out int d) ? d : 75;
await _tonePlayer.PlayPureToneAsync(frequency, durationInMillis, _ss.ToneVolume);
}
private static async Task DoPlaySound(string p)
{
await _debugLogger.Log("Enter: doPlaySound");
SoundManager.Instance.Volume = _ss.SoundVolume;
await SoundManager.Instance.PlaySoundAsync(p);
}
private static async Task InstantTtsSay(string p)
{
await _debugLogger.Log("Enter: instantTtsSay");
await _debugLogger.Log($"ttsSay: {p}");
await DoStopAll();
await DoSpeak(p);
}
private static async Task DoStopAll()
{
await _debugLogger.Log("Enter: doStopAll");
await DoStopSpeaking();
_tonePlayer.Stop();
SoundManager.Instance.StopCurrentSound();
}
private static async Task DoSpeak(string what)
{
string temp;
if (_ss.SplitCaps)
{
temp = await InsertSpaceBeforeUppercase(what);
}
else
{
temp = what;
}
List<string> parts = await SplitOnSquareStar(temp);
foreach (string part in parts)
{
if (part == "[*]")
{
await DoSilence("0");
}
else
{
string speakPart = await ReplacePunctuations(temp);
await _DoSpeak(speakPart);
}
}
}
private static async Task _DoSpeak(string what)
{
await _debugLogger.Log("Enter: doSpeak");
// Important: lots of the settings live in
// this builder
string ssml = await BuildSsml(what);
// Set the rate of speech (-19 to 10)
_speaker.Rate = Math.Clamp(_ss.SpeechRate, -10, 10);
// Set the volume (0 to 100)
_speaker.Volume = Math.Clamp(_ss.VoiceVolume, 0, 100);
// Start speaking
await _debugLogger.Log($"SSML: {ssml}");
if (_ss.AudioTarget == "right" || _ss.AudioTarget == "left")
{
await _debugLogger.Log($"EnqueueText");
_audioQueue.EnqueueText(ssml);
}
else
{
await _debugLogger.Log($"SpeakSsmlasync");
_speaker.SpeakSsmlAsync(ssml);
}
}
private static async Task InstantTtsExit()
{
await _debugLogger.Log("Enter: instantTtsExit");
Environment.Exit(0);
}
private static async Task<string> IsolateCommand(string line)
{
await _debugLogger.Log("Enter: isolateCommand");
string cmd = line.Trim();
int firstIndex = cmd.IndexOf(' ');
if (firstIndex >= 0)
{
cmd = cmd.Substring(0, firstIndex);
}
return cmd;
}
private static async Task<(string, string)> IsolateCmdAndParams(string line)
{
await _debugLogger.Log("Enter: isolateParams");
string justCmd = await IsolateCommand(line);
string cmd = justCmd + " ";
string parameters = Regex.Replace(line, "^" + Regex.Escape(cmd), "", RegexOptions.IgnoreCase);
parameters = parameters.Trim();
if (parameters.StartsWith("{") && parameters.EndsWith("}"))
{
parameters = parameters.Substring(1, parameters.Length - 2);
}
await _debugLogger.Log($"Exit: isolateParams: {parameters}");
return (justCmd, parameters);
}
}