-
Notifications
You must be signed in to change notification settings - Fork 99
/
MainWindow.xaml.cs
831 lines (724 loc) · 35.6 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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace VoiceAssistantClient
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using AdaptiveCards;
using AdaptiveCards.Rendering;
using AdaptiveCards.Rendering.Wpf;
using Microsoft.Bot.Schema;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using Microsoft.CognitiveServices.Speech.Dialog;
using Microsoft.Win32;
using NAudio.Wave;
using Newtonsoft.Json;
using VoiceAssistantClient.Settings;
/// <summary>
/// Interaction logic for MainWindow.xaml.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:Types that own disposable fields should be disposable", Justification = "Objects are disposed OnClosed()")]
public partial class MainWindow : Window, INotifyPropertyChanged
{
private AppSettings settings = new AppSettings();
private DialogServiceConnector connector = null;
private WaveOutEvent player = new WaveOutEvent();
private Queue<WavQueueEntry> playbackStreams = new Queue<WavQueueEntry>();
private WakeWordConfiguration activeWakeWordConfig = null;
private CustomSpeechConfiguration customSpeechConfig = null;
private ListenState listening = ListenState.NotListening;
private AdaptiveCardRenderer renderer;
public MainWindow()
{
this.InitializeComponent();
this.Dispatcher.UnhandledException += this.Dispatcher_UnhandledException;
CommandBinding cb = new CommandBinding(ApplicationCommands.Copy, this.CopyCmdExecuted, this.CopyCmdCanExecute);
this.ConversationView.ConversationHistory.CommandBindings.Add(cb);
this.ActivitiesPane.CommandBindings.Add(cb);
this.ActivityPayloadPane.CommandBindings.Add(cb);
this.DataContext = this;
this.player.PlaybackStopped += this.Player_PlaybackStopped;
Services.Tracker.Configure(this.settings).Apply();
this.renderer = new AdaptiveCardRenderer();
/*
Xceed Enhanced Input Package
This optional package enhances the Adaptive Card input controls beyond what WPF provides out of the box.
To enable it:
1. Add the NuGet package Extended.Wpf.Toolkit by Xceed to the project
2. Add the NuGet package AdaptiveCards.Rendering.Wpf.Xceed by Microsoft to the project
3. Uncomment the one line below
This option is not included here because of its license terms.
For more info: https://docs.microsoft.com/en-us/adaptive-cards/sdk/rendering-cards/net-wpf/getting-started
*/
// this.renderer.UseXceedElementRenderers();
var configFile = Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, "AdaptiveCardsHostConfig.json");
if (File.Exists(configFile))
{
this.renderer.HostConfig = AdaptiveHostConfig.FromJson(File.ReadAllText(configFile));
}
}
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets the window title string, which includes the assembly version number.
/// To update the assembly version number, edit this line in VoiceAssistantClient\Properties\AssemblyInfo.cs:
/// [assembly: AssemblyVersion("#.#.#.#")]
/// Or in VS, right click on the VoiceAssistantClient project -> properties -> Assembly Information.
/// Microsoft Version number is: [Major Version, Minor Version, Build Number, Revision]
/// (see https://docs.microsoft.com/en-us/dotnet/api/system.version).
/// Per GitHub guidance, we use Semantic Versioning with [Major, Minor, Patch], so we ignore
/// the last number and treat the Build Number as the Patch (see https://semver.org/).
/// </summary>
public static string WindowTitle
{
get
{
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
return $"Windows Voice Assistant Client v{version.Major}.{version.Minor}.{version.Build}";
}
}
public ObservableCollection<MessageDisplay> Messages { get; private set; } = new ObservableCollection<MessageDisplay>();
public ObservableCollection<ActivityDisplay> Activities { get; private set; } = new ObservableCollection<ActivityDisplay>();
public ListenState ListeningState
{
get
{
return this.listening;
}
private set
{
this.listening = value;
this.OnPropertyChanged(nameof(this.ListeningState));
}
}
protected override void OnClosed(EventArgs e)
{
if (this.connector != null)
{
this.connector.Dispose();
}
if (this.player != null)
{
this.player.Dispose();
}
base.OnClosed(e);
}
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
// Connecting and using the client requires providing a speech subscription key along
// with the region for that subscription or, for development against a specific custom
// URL, a URL override. If the client doesn't meet these requirements (e.g. on first
// run), pop up the settings dialog to prompt for it.
var hasSubscriptionKey = !string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.SubscriptionKey);
var hasSubscriptionRegion = !string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.SubscriptionKeyRegion);
var hasUrlOverride = !string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.UrlOverride);
if (!hasSubscriptionKey || (!hasSubscriptionRegion && !hasUrlOverride))
{
var settingsDialog = new SettingsDialog(this.settings.RuntimeSettings);
bool succeeded;
succeeded = settingsDialog.ShowDialog() ?? false;
if (!succeeded)
{
this.Close();
}
}
}
protected override void OnActivated(EventArgs e)
{
// Set this here as opposed to XAML since we do not do a full binding
this.CustomActivityCollectionCombo.ItemsSource = this.settings.DisplaySettings.CustomPayloadData;
this.CustomActivityCollectionCombo.DisplayMemberPath = "Name";
this.CustomActivityCollectionCombo.SelectedValuePath = "Name";
base.OnActivated(e);
}
protected virtual void OnPropertyChanged(string propertyName)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected override void OnDeactivated(EventArgs e)
{
base.OnDeactivated(e);
}
private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
this.ShowException(e.Exception);
e.Handled = true;
}
private void ShowException(Exception e)
{
this.RunOnUiThread(() =>
{
Debug.WriteLine(e);
this.Messages.Add(new MessageDisplay($"App Error (see log for details): {Environment.NewLine} {e.Source} : {e.Message}", Sender.Channel));
var trace = new Activity
{
Type = "Exception",
Value = e,
};
this.Activities.Add(new ActivityDisplay(JsonConvert.SerializeObject(trace), trace, Sender.Channel));
});
}
/// <summary>
/// The method reads user-entered settings and creates a new instance of the DialogServiceConnector object
/// when the "Reconnect" button is pressed (or the microphone button is pressed for the first time).
/// </summary>
private void InitSpeechConnector()
{
DialogServiceConfig config = null;
var hasSubscription = !string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.SubscriptionKey);
var hasRegion = !string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.SubscriptionKeyRegion);
var hasBotId = !string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.BotId);
var hasUrlOverride = !string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.UrlOverride);
if (hasSubscription && (hasRegion || hasUrlOverride))
{
if (!string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.CustomCommandsAppId))
{
// NOTE: Custom commands is a preview Azure Service.
// Set the custom commands configuration object based on three items:
// - The Custom commands application ID
// - Cognitive services speech subscription key.
// - The Azure region of the subscription key(e.g. "westus").
config = CustomCommandsConfig.FromSubscription(this.settings.RuntimeSettings.Profile.CustomCommandsAppId, this.settings.RuntimeSettings.Profile.SubscriptionKey, this.settings.RuntimeSettings.Profile.SubscriptionKeyRegion);
}
else if (hasBotId)
{
config = BotFrameworkConfig.FromSubscription(this.settings.RuntimeSettings.Profile.SubscriptionKey, this.settings.RuntimeSettings.Profile.SubscriptionKeyRegion, this.settings.RuntimeSettings.Profile.BotId);
}
else
{
// Set the bot framework configuration object based on two items:
// - Cognitive services speech subscription key. It is needed for billing and is tied to the bot registration.
// - The Azure region of the subscription key(e.g. "westus").
config = BotFrameworkConfig.FromSubscription(this.settings.RuntimeSettings.Profile.SubscriptionKey, this.settings.RuntimeSettings.Profile.SubscriptionKeyRegion);
}
}
if (!string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.ConnectionLanguage))
{
// Set the speech recognition language. If not set, the default is "en-us".
config.Language = this.settings.RuntimeSettings.Profile.ConnectionLanguage;
}
if (this.settings.RuntimeSettings.Profile.CustomSpeechEnabled)
{
// Set your custom speech end-point id here, as given to you by the speech portal https://speech.microsoft.com/portal.
// Otherwise the standard speech end-point will be used.
config.SetServiceProperty("cid", this.settings.RuntimeSettings.Profile.CustomSpeechEndpointId, ServicePropertyChannel.UriQueryParameter);
// Custom Speech does not support cloud Keyword Verification at the moment. If this is not done, there will be an error
// from the service and connection will close. Remove line below when supported.
config.SetProperty("KeywordConfig_EnableKeywordVerification", "false");
}
if (this.settings.RuntimeSettings.Profile.VoiceDeploymentEnabled)
{
// Set one or more IDs associated with the custom TTS voice your bot will use
// The format of the string is one or more GUIDs separated by comma (no spaces). You get these GUIDs from
// your custom TTS on the speech portal https://speech.microsoft.com/portal.
config.SetProperty(PropertyId.Conversation_Custom_Voice_Deployment_Ids, this.settings.RuntimeSettings.Profile.VoiceDeploymentIds);
}
if (!string.IsNullOrEmpty(this.settings.RuntimeSettings.Profile.FromId))
{
// Set the from.id in the Bot-Framework Activity sent by this tool.
// from.id field identifies who generated the activity, and may be required by some bots.
// See https://github.com/microsoft/botframework-sdk/blob/master/specs/botframework-activity/botframework-activity.md
// for Bot Framework Activity schema and from.id.
config.SetProperty(PropertyId.Conversation_From_Id, this.settings.RuntimeSettings.Profile.FromId);
}
if (!string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.LogFilePath))
{
// Speech SDK has verbose logging to local file, which may be useful when reporting issues.
// Supply the path to a text file on disk here. By default no logging happens.
config.SetProperty(PropertyId.Speech_LogFilename, this.settings.RuntimeSettings.Profile.LogFilePath);
}
if (hasUrlOverride)
{
// For prototyping new Direct Line Speech channel service feature, a custom service URL may be
// provided by Microsoft and entered in this tool.
config.SetProperty("SPEECH-Endpoint", this.settings.RuntimeSettings.Profile.UrlOverride);
}
if (!string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.ProxyHostName) &&
!string.IsNullOrWhiteSpace(this.settings.RuntimeSettings.Profile.ProxyPortNumber) &&
int.TryParse(this.settings.RuntimeSettings.Profile.ProxyPortNumber, out var proxyPortNumber))
{
// To funnel network traffic via a proxy, set the host name and port number here
config.SetProxy(this.settings.RuntimeSettings.Profile.ProxyHostName, proxyPortNumber, string.Empty, string.Empty);
}
// If a the DialogServiceConnector object already exists, destroy it first
if (this.connector != null)
{
// First, unregister all events
this.connector.ActivityReceived -= this.Connector_ActivityReceived;
this.connector.Recognizing -= this.Connector_Recognizing;
this.connector.Recognized -= this.Connector_Recognized;
this.connector.Canceled -= this.Connector_Canceled;
this.connector.SessionStarted -= this.Connector_SessionStarted;
this.connector.SessionStopped -= this.Connector_SessionStopped;
// Then dispose the object
this.connector.Dispose();
this.connector = null;
}
// Create a new Dialog Service Connector for the above configuration and register to receive events
this.connector = new DialogServiceConnector(config, AudioConfig.FromDefaultMicrophoneInput());
this.connector.ActivityReceived += this.Connector_ActivityReceived;
this.connector.Recognizing += this.Connector_Recognizing;
this.connector.Recognized += this.Connector_Recognized;
this.connector.Canceled += this.Connector_Canceled;
this.connector.SessionStarted += this.Connector_SessionStarted;
this.connector.SessionStopped += this.Connector_SessionStopped;
// Open a connection to Direct Line Speech channel
this.connector.ConnectAsync();
if (this.settings.RuntimeSettings.Profile.CustomSpeechEnabled)
{
this.customSpeechConfig = new CustomSpeechConfiguration(this.settings.RuntimeSettings.Profile.CustomSpeechEndpointId);
}
if (this.settings.RuntimeSettings.Profile.WakeWordEnabled)
{
// Configure wake word (also known as "keyword")
this.activeWakeWordConfig = new WakeWordConfiguration(this.settings.RuntimeSettings.Profile.WakeWordPath);
this.connector.StartKeywordRecognitionAsync(this.activeWakeWordConfig.WakeWordModel);
}
}
private void Connector_SessionStopped(object sender, SessionEventArgs e)
{
var message = "Stopped listening";
Debug.WriteLine($"SessionStopped event, id = {e.SessionId}");
if (this.settings.RuntimeSettings.Profile.WakeWordEnabled)
{
message = "Stopped actively listening - waiting for wake word";
}
this.UpdateStatus(message);
this.RunOnUiThread(() => this.ListeningState = ListenState.NotListening);
}
private void Connector_SessionStarted(object sender, SessionEventArgs e)
{
Debug.WriteLine($"SessionStarted event, id = {e.SessionId}");
this.UpdateStatus("Listening ...");
this.player.Stop();
this.RunOnUiThread(() => this.ListeningState = ListenState.Listening);
}
private void Connector_Canceled(object sender, SpeechRecognitionCanceledEventArgs e)
{
if (e.Reason == CancellationReason.Error
&& e.ErrorCode == CancellationErrorCode.ConnectionFailure
&& e.ErrorDetails.Contains("1000"))
{
// Connection was closed by the remote host.
// Error code: 1000.
// Error details: Exceeded maximum websocket connection idle duration (>300000ms = 5 minutes).
// A graceful timeout after a connection is idle manifests as an error but isn't an
// exceptional condition -- we don't want it show up as a big red bubble!
this.UpdateStatus("Active connection timed out but ready to reconnect on demand.");
}
else
{
var statusMessage = $"Error ({e.ErrorCode}) : {e.ErrorDetails}";
this.UpdateStatus(statusMessage);
this.RunOnUiThread(() =>
{
this.ListeningState = ListenState.NotListening;
this.Messages.Add(new MessageDisplay(statusMessage, Sender.Channel));
});
}
}
private void Connector_Recognized(object sender, SpeechRecognitionEventArgs e)
{
System.Diagnostics.Debug.WriteLine($"Connector_Recognized ({e.Result.Reason}): {e.Result.Text}");
this.RunOnUiThread(() =>
{
this.UpdateStatus(string.Empty);
if (!string.IsNullOrWhiteSpace(e.Result.Text) && e.Result.Reason == ResultReason.RecognizedSpeech)
{
this.Messages.Add(new MessageDisplay(e.Result.Text, Sender.User));
this.ConversationView.ConversationHistory.ScrollIntoView(this.ConversationView.ConversationHistory.Items[this.ConversationView.ConversationHistory.Items.Count - 1]);
}
});
}
private void Connector_Recognizing(object sender, SpeechRecognitionEventArgs e)
{
this.UpdateStatus(e.Result.Text, tentative: true);
}
private void Connector_ActivityReceived(object sender, ActivityReceivedEventArgs e)
{
var json = e.Activity;
var activity = JsonConvert.DeserializeObject<Activity>(json);
if (e.HasAudio && activity.Speak != null)
{
var audio = e.Audio;
var stream = new ProducerConsumerStream();
Task.Run(() =>
{
var buffer = new byte[800];
uint bytesRead = 0;
while ((bytesRead = audio.Read(buffer)) > 0)
{
stream.Write(buffer, 0, (int)bytesRead);
}
}).Wait();
var channelData = activity.GetChannelData<SpeechChannelData>();
var id = channelData?.ConversationalAiData?.RequestInfo?.InteractionId;
if (!string.IsNullOrEmpty(id))
{
System.Diagnostics.Debug.WriteLine($"Expecting TTS stream {id}");
}
var wavStream = new RawSourceWaveStream(stream, new WaveFormat(16000, 16, 1));
this.playbackStreams.Enqueue(new WavQueueEntry(id, false, stream, wavStream));
if (this.player.PlaybackState != PlaybackState.Playing)
{
Task.Run(() => this.PlayFromAudioQueue());
}
}
List<AdaptiveCard> cardsToBeRendered = new List<AdaptiveCard>();
if (activity.Attachments?.Any() is true)
{
cardsToBeRendered = activity.Attachments
.Where(x => x.ContentType == AdaptiveCard.ContentType)
.Select(x =>
{
try
{
var parseResult = AdaptiveCard.FromJson(x.Content.ToString());
return parseResult.Card;
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
{
this.ShowException(ex);
return null;
}
#pragma warning restore CA1031 // Do not catch general exception types
})
.Where(x => x != null)
.ToList();
}
this.RunOnUiThread(() =>
{
this.Activities.Add(new ActivityDisplay(json, activity, Sender.Bot));
if (activity.Type == ActivityTypes.Message || cardsToBeRendered?.Any() == true)
{
var renderedCards = cardsToBeRendered.Select(x =>
{
var rendered = this.renderer.RenderCard(x);
rendered.OnAction += this.RenderedCard_OnAction;
rendered.OnMediaClicked += this.RenderedCard_OnMediaClicked;
return rendered?.FrameworkElement;
});
this.Messages.Add(new MessageDisplay(activity.Text, Sender.Bot, renderedCards));
this.ConversationView.ConversationHistory.ScrollIntoView(this.ConversationView.ConversationHistory.Items[this.ConversationView.ConversationHistory.Items.Count - 1]);
}
});
}
private void RenderedCard_OnMediaClicked(RenderedAdaptiveCard sender, AdaptiveMediaEventArgs e)
{
MessageBox.Show(this, JsonConvert.SerializeObject(e.Media), "Host received Media");
}
private void RenderedCard_OnAction(RenderedAdaptiveCard sender, AdaptiveActionEventArgs e)
{
if (e.Action is AdaptiveOpenUrlAction openUrlAction)
{
Process.Start(openUrlAction.Url.AbsoluteUri);
}
else if (e.Action is AdaptiveSubmitAction submitAction)
{
var inputs = sender.UserInputs.AsJson();
// Merge the Action.Submit Data property with the inputs
inputs.Merge(submitAction.Data);
MessageBox.Show(this, JsonConvert.SerializeObject(inputs, Formatting.Indented), "SubmitAction");
}
}
private void SwitchToNewBotEndpoint()
{
this.Reset();
this.Messages.Add(new MessageDisplay("Switched to updated Bot Endpoint", Sender.Channel));
}
private void Reset()
{
this.Messages.Clear();
this.Activities.Clear();
this.ListeningState = ListenState.NotListening;
this.UpdateStatus("New conversation started");
this.StopAnyTTSPlayback();
this.InitSpeechConnector();
var message = "New conversation started - type or press the microphone button";
if (this.settings.RuntimeSettings.Profile.WakeWordEnabled)
{
message = $"New conversation started - type, press the microphone button, or say the wake word";
}
this.UpdateStatus(message);
}
private void Reconnect_Click(object sender, RoutedEventArgs e)
{
this.Reset();
this.UpdateConnectionProfileInfoBlock();
}
private void StartListening()
{
if (this.ListeningState == ListenState.NotListening)
{
if (this.connector == null)
{
this.InitSpeechConnector();
}
try
{
this.ListeningState = ListenState.Initiated;
this.connector.ListenOnceAsync();
System.Diagnostics.Debug.WriteLine("Started ListenOnceAsync");
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
{
this.ShowException(ex);
}
#pragma warning restore CA1031 // Do not catch general exception types
}
}
private void Mic_Click(object sender, RoutedEventArgs e)
{
this.StopAnyTTSPlayback();
if (this.ListeningState == ListenState.NotListening)
{
this.StartListening();
}
else
{
// Todo: canceling listening not supported
}
}
private void Player_PlaybackStopped(object sender, StoppedEventArgs e)
{
lock (this.playbackStreams)
{
if (this.playbackStreams.Count == 0)
{
return;
}
var entry = this.playbackStreams.Dequeue();
entry.Stream.Close();
}
if (!this.PlayFromAudioQueue())
{
if (this.Activities.LastOrDefault(x => x.Activity.Type == ActivityTypes.Message)
?.Activity?.AsMessageActivity()?.InputHint == InputHints.ExpectingInput)
{
this.StartListening();
}
}
}
private void StopAnyTTSPlayback()
{
lock (this.playbackStreams)
{
this.playbackStreams.Clear();
}
if (this.player.PlaybackState == PlaybackState.Playing)
{
this.player.Stop();
}
}
private void StatusBox_KeyUp(object sender, KeyEventArgs e)
{
this.StopAnyTTSPlayback();
if (e.Key != Key.Enter)
{
return;
}
e.Handled = true;
if (this.connector == null)
{
this.InitSpeechConnector();
}
var bfActivity = Activity.CreateMessageActivity();
bfActivity.Text = this.statusBox.Text;
if (!string.IsNullOrEmpty(this.settings.RuntimeSettings.Profile.FromId))
{
bfActivity.From = new ChannelAccount(this.settings.RuntimeSettings.Profile.FromId);
}
this.statusBox.Clear();
var jsonConnectorActivity = JsonConvert.SerializeObject(bfActivity);
this.Messages.Add(new MessageDisplay(bfActivity.Text, Sender.User));
this.Activities.Add(new ActivityDisplay(jsonConnectorActivity, bfActivity, Sender.User));
string id = this.connector.SendActivityAsync(jsonConnectorActivity).Result;
Debug.WriteLine($"SendActivityAsync called, id = {id}");
this.ConversationView.ConversationHistory.ScrollIntoView(this.ConversationView.ConversationHistory.Items[this.ConversationView.ConversationHistory.Items.Count - 1]);
}
private void ExportActivityLog_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog()
{
Filter = "Text Files(*.txt)|*.txt|All(*.*)|*",
};
if (dialog.ShowDialog() == true)
{
File.WriteAllLines(
dialog.FileName,
this.Messages.Select(x => x.ToString()).Concat(
this.Activities.Select(x => x.ToString()).ToList()).ToArray());
}
}
private void CopyCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
string copyContent = string.Empty;
if (e.OriginalSource is ListBox lb)
{
foreach (var item in lb.SelectedItems)
{
copyContent += item.ToString();
copyContent += Environment.NewLine;
}
}
else if (e.OriginalSource is JsonViewerControl.JsonViewer jv)
{
copyContent = jv.SelectedItem?.ToString();
}
if (copyContent != null)
{
Clipboard.SetText(copyContent);
}
}
private void CopyCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.OriginalSource is ListBox lb)
{
if (lb.SelectedItems.Count > 0)
{
e.CanExecute = true;
}
else
{
e.CanExecute = false;
}
}
else if (e.OriginalSource is JsonViewerControl.JsonViewer)
{
e.CanExecute = true;
}
}
private void RunOnUiThread(Action action)
{
this.statusBox.Dispatcher.InvokeAsync(action);
}
private void UpdateStatus(string msg, bool tentative = true)
{
if (Thread.CurrentThread != this.statusOverlay.Dispatcher.Thread)
{
this.RunOnUiThread(() =>
{
this.UpdateStatus(msg, tentative);
this.ConversationView.ConversationHistory.ScrollIntoView(this.ConversationView.ConversationHistory.Items[this.ConversationView.ConversationHistory.Items.Count - 1]);
});
return;
}
const string pad = " ";
if (tentative)
{
this.statusOverlay.Text = pad + msg;
}
else
{
this.statusBox.Clear();
this.statusBox.Text = pad + msg;
}
}
private bool PlayFromAudioQueue()
{
WavQueueEntry entry = null;
lock (this.playbackStreams)
{
if (this.playbackStreams.Count > 0)
{
entry = this.playbackStreams.Peek();
}
}
if (entry != null)
{
System.Diagnostics.Debug.WriteLine($"START playing {entry.Id}");
this.player.Init(entry.Reader);
this.player.Play();
return true;
}
return false;
}
private void SendActivity_Click(object sender, RoutedEventArgs e)
{
var selectedIndex = this.CustomActivityCollectionCombo.SelectedIndex;
if (selectedIndex != -1)
{
var selectedCustomActivity = this.settings.DisplaySettings.CustomPayloadData[selectedIndex];
var connectorActivity = selectedCustomActivity.JsonData;
var bfActivity = JsonConvert.DeserializeObject<Activity>(connectorActivity);
this.Activities.Add(new ActivityDisplay(connectorActivity, bfActivity, Sender.User));
if (this.connector == null)
{
this.InitSpeechConnector();
}
string id = this.connector.SendActivityAsync(connectorActivity).Result;
Debug.WriteLine($"SendActivityAsync called, id = {id}");
}
}
private void ActivitiesPane_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = (sender as ListView).SelectedItem;
if (item != null && item is ActivityDisplay entry)
{
this.ActivityPayloadPane.Load(entry.Json);
this.ActivityPayloadPane.ExpandAll();
}
}
private void BotEndpoint_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.Reset();
}
}
private void NewCustomActivityButton_Click(object sender, RoutedEventArgs e)
{
var window = new CustomActivityWindow(this.settings.DisplaySettings.CustomPayloadData, -1);
bool? succeeded = window.ShowDialog();
this.SelectOrDefault(succeeded, window);
}
private void EditCustomActivityButton_Click(object sender, RoutedEventArgs e)
{
var window = new CustomActivityWindow(this.settings.DisplaySettings.CustomPayloadData, this.CustomActivityCollectionCombo.SelectedIndex);
bool? succeeded = window.ShowDialog();
this.SelectOrDefault(succeeded, window);
}
private void SelectOrDefault(bool? dialogResult, CustomActivityWindow dialog)
{
if (dialogResult.Value)
{
var activityTag = dialog.CustomActivityTag;
if (!string.IsNullOrWhiteSpace(activityTag))
{
var activityInfoEntry = this.settings.DisplaySettings.CustomPayloadData.FirstOrDefault(
(item) => item.Name.Equals(activityTag, StringComparison.OrdinalIgnoreCase));
this.CustomActivityCollectionCombo.SelectedItem = activityInfoEntry;
}
}
}
private void Settings_Click(object sender, RoutedEventArgs e)
{
var settingsDialog = new SettingsDialog(this.settings.RuntimeSettings);
var succeeded = settingsDialog.ShowDialog();
// BUGBUG: Do not call reset, leave it for later as this is usually the first action.
}
private void UpdateConnectionProfileInfoBlock()
{
var settingsDialog = new SettingsDialog(this.settings.RuntimeSettings);
var connectionProfileName = !string.IsNullOrWhiteSpace(settingsDialog.ConnectionProfileName);
if (connectionProfileName)
{
this.ConnectionProfileInfoBlock.Text = $"Connection Profile: {settingsDialog.ConnectionProfileName}";
}
}
}
}