forked from microsoft/Cognitive-Samples-IntelligentKiosk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInkMirror.xaml.cs
877 lines (724 loc) · 33.1 KB
/
InkMirror.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
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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services:
// http://www.microsoft.com/cognitive
//
// Microsoft Cognitive Services Github:
// https://github.com/Microsoft/Cognitive
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using IntelligentKioskSample.Models.InkRecognizerExplorer;
using Microsoft.Graphics.Canvas.Geometry;
using Microsoft.Graphics.Canvas.Text;
using Microsoft.Graphics.Canvas.UI.Xaml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Numerics;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.Display;
using Windows.Storage;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Input.Inking;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace IntelligentKioskSample.Views.InkRecognizerExplorer
{
public sealed partial class InkMirror : Page
{
private bool previouslyLoaded = false;
private string subscriptionKey = SettingsHelper.Instance.InkRecognizerApiKey;
private ServiceHelpers.InkRecognizer inkRecognizer;
private InkResponse inkResponse;
private Dictionary<int, InkRecognitionUnit> recoTreeNodes;
private List<InkRecognitionUnit> recoTreeParentNodes;
private Dictionary<int, Tuple<string, Color>> recoText;
private Stack<InkStroke> redoStrokes;
private List<InkStroke> clearedStrokes;
private InkToolbarToolButton activeTool;
private bool inkCleared = false;
private float dipsPerMm;
private Symbol TouchWriting = (Symbol)0xED5F;
private Symbol Undo = (Symbol)0xE7A7;
private Symbol Redo = (Symbol)0xE7A6;
private Symbol ClearAll = (Symbol)0xE74D;
private Symbol LanguageSelect = (Symbol)0xF2B7;
private Symbol Recognize = (Symbol)0xF0AF;
public InkMirror()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Enabled;
inkRecognizer = new ServiceHelpers.InkRecognizer(subscriptionKey);
recoTreeNodes = new Dictionary<int, InkRecognitionUnit>();
recoTreeParentNodes = new List<InkRecognitionUnit>();
recoText = new Dictionary<int, Tuple<string, Color>>();
redoStrokes = new Stack<InkStroke>();
clearedStrokes = new List<InkStroke>();
activeTool = ballpointPen;
inkCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Mouse;
inkCanvas.InkPresenter.StrokeInput.StrokeStarted += InkPresenter_StrokeInputStarted;
inkCanvas.InkPresenter.StrokesErased += InkPresenter_StrokesErased;
resultNav.SelectedItem = resultNav.MenuItems[0];
// Set default ink color to blue
ballpointPen.SelectedBrushIndex = 16;
pencil.SelectedBrushIndex = 16;
}
#region Event Handlers - Page
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
if (!previouslyLoaded)
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/InkRecognizerSampleInstructions.gif"));
if (file != null)
{
using (var stream = await file.OpenSequentialReadAsync())
{
await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(stream);
}
}
previouslyLoaded = true;
}
// When the page is Unloaded, the Win2D CanvasControl is disposed. To preserve the state of the page we need to re-instantiate this object.
// In the case of the Win2D CanvasControl, a new UI Element needs to be created/appended to the page as well
var resultCanvas = new CanvasControl();
resultCanvas.Name = "resultCanvas";
resultCanvas.Draw += ResultCanvas_Draw;
resultCanvas.SetValue(Grid.RowProperty, 0);
resultCanvasGrid.Children.Add(resultCanvas);
RecognizeButton_Click(null, null);
base.OnNavigatedTo(e);
}
void Page_Unloaded(object sender, RoutedEventArgs e)
{
// Dispose Win2D resources to avoid memory leak
// Reference: https://microsoft.github.io/Win2D/html/RefCycles.htm
var resultCanvas = this.FindName("resultCanvas") as CanvasControl;
resultCanvas.RemoveFromVisualTree();
resultCanvas = null;
}
#endregion
#region Event Handlers - Ink Toolbar
private void UndoButton_Click(object sender, RoutedEventArgs e)
{
var button = sender as InkToolbarCustomToolButton;
button.IsChecked = false;
if (inkCleared)
{
foreach (var stroke in clearedStrokes)
{
inkCanvas.InkPresenter.StrokeContainer.AddStroke(stroke.Clone());
}
clearedStrokes.Clear();
inkCleared = false;
}
else if (activeTool is InkToolbarEraserButton)
{
RedoButton_Click(sender, null);
}
else
{
var strokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
if (strokes.Count > 0)
{
var stroke = strokes[strokes.Count - 1];
redoStrokes.Push(stroke);
stroke.Selected = true;
inkCanvas.InkPresenter.StrokeContainer.DeleteSelected();
}
}
}
private void RedoButton_Click(object sender, RoutedEventArgs e)
{
var button = sender as InkToolbarCustomToolButton;
button.IsChecked = false;
if (redoStrokes.Count > 0)
{
var stroke = redoStrokes.Pop();
inkCanvas.InkPresenter.StrokeContainer.AddStroke(stroke.Clone());
}
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
var button = sender as InkToolbarCustomToolButton;
button.IsChecked = false;
var strokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
foreach (var stroke in strokes)
{
clearedStrokes.Add(stroke);
}
inkCleared = true;
inkCanvas.InkPresenter.StrokeContainer.Clear();
ClearJson();
}
private void LanguageSelectButton_Click(object sender, RoutedEventArgs e)
{
var button = sender as InkToolbarCustomToolButton;
button.IsChecked = false;
FlyoutBase.ShowAttachedFlyout(button);
}
private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
{
foreach (var item in languageDropdown.Items)
{
item.Background = null;
}
var selectedItem = sender as MenuFlyoutItem;
var color = GetColorFromHex("#0078D7");
selectedItem.Background = new SolidColorBrush(color);
inkRecognizer.SetLanguage(selectedItem.Tag.ToString());
}
private void TouchButton_Click(object sender, RoutedEventArgs e)
{
if (touchButton.IsChecked == true)
{
inkCanvas.InkPresenter.InputDeviceTypes |= CoreInputDeviceTypes.Touch;
}
else
{
inkCanvas.InkPresenter.InputDeviceTypes &= ~CoreInputDeviceTypes.Touch;
}
}
#endregion
#region Event Handlers - Ink Canvas
private void InkPresenter_StrokeInputStarted(InkStrokeInput sender, PointerEventArgs args)
{
//ViewCanvasButton_Click(null, null);
clearedStrokes.Clear();
inkCleared = false;
activeTool = inkToolbar.ActiveTool;
}
private void InkPresenter_StrokesErased(InkPresenter sender, InkStrokesErasedEventArgs args)
{
// When strokes are erased they are treated the same as an undo and are pushed onto a stack of strokes for the redo button
foreach (var stroke in args.Strokes)
{
redoStrokes.Push(stroke);
}
activeTool = inkToolbar.ActiveTool;
}
private async void RecognizeButton_Click(object sender, RoutedEventArgs e)
{
var strokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
if (strokes.Count > 0)
{
// Disable use of toolbar during recognition and rendering and
// Clear result canvas and viewable JSON before recognition and rendering of results
ToggleInkToolbar();
ToggleProgressRing();
ClearJson();
// Convert ink stroke data to JSON to be sent with request
inkRecognizer.ClearStrokes();
inkRecognizer.AddStrokes(strokes);
JObject json = inkRecognizer.ConvertInkToJson();
requestJsonText.Text = FormatJson(json.ToString());
// Recognize Ink from JSON and display response
var response = await inkRecognizer.RecognizeAsync(json);
string responseString = await response.Content.ReadAsStringAsync();
inkResponse = JsonConvert.DeserializeObject<InkResponse>(responseString);
if (response.StatusCode == HttpStatusCode.OK)
{
// Generate JSON tree view and draw result on right side canvas
CreateJsonTree();
responseJsonText.Text = FormatJson(responseString);
try
{
var resultCanvas = this.FindName("resultCanvas") as CanvasControl;
resultCanvas.Invalidate();
}
catch (NullReferenceException)
{
// This occurs when the page is changed before recognition finishes.
// Since the result canvas gets disposed when navigating away it becomes null.
}
}
else
{
if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.NotFound)
{
await new MessageDialog("Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct API endpoint in the Settings page.", $"Response Code: {inkResponse.Error.code}").ShowAsync();
}
else
{
await new MessageDialog(inkResponse.Error.message, $"Response Code: {inkResponse.Error.code}").ShowAsync();
}
}
// Re-enable use of toolbar after recognition and rendering
ToggleInkToolbar();
ToggleProgressRing();
}
else
{
// Clear viewable JSON if there is no strokes on canvas
ClearJson();
}
}
#endregion
#region Event Handlers - Result Canvas
private void ResultCanvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
if (!string.IsNullOrEmpty(responseJsonText.Text))
{
// For demo purposes and keeping the initially loaded ink consistent a value of 96 for DPI was used
// For production, it is most likely better to use the device's DPI when generating the request JSON and an example of that is below
//float dpi = args.DrawingSession.Dpi;
//dipsPerMm = inkRecognizer.GetDipsPerMm(dpi);
dipsPerMm = inkRecognizer.GetDipsPerMm(96);
var backgroundColor = GetColorFromHex("#2B2B2B");
args.DrawingSession.Clear(backgroundColor);
foreach (var recoUnit in inkResponse.RecognitionUnits)
{
string category = recoUnit.category;
switch (category)
{
case "inkBullet":
case "inkWord":
AddText(recoUnit);
break;
case "line":
DrawText(recoUnit, sender, args);
break;
case "inkDrawing":
DrawShape(recoUnit, args);
break;
}
}
recoText.Clear();
}
else
{
var backgroundColor = GetColorFromHex("#2B2B2B");
args.DrawingSession.Clear(backgroundColor);
}
}
private void ResultNav_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
{
var item = sender.SelectedItem as NavigationViewItem;
NavItemToggle(item.Name);
}
private void TreeView_ItemInvoked(TreeView sender, TreeViewItemInvokedEventArgs args)
{
var node = args.InvokedItem as TreeViewNode;
if (node.IsExpanded == false)
{
node.IsExpanded = true;
}
else
{
node.IsExpanded = false;
}
}
#endregion
#region Draw Results On Canvas
private void AddText(InkRecognitionUnit recoUnit)
{
string recognizedText = recoUnit.recognizedText;
if (recognizedText != null)
{
int id = recoUnit.id;
// Color of ink word or ink bullet
var color = GetStrokeColor(recoUnit);
var text = new Tuple<string, Color>(recognizedText, color);
recoText.Add(id, text);
}
}
private void DrawText(InkRecognitionUnit recoUnit, CanvasControl sender, CanvasDrawEventArgs args)
{
var childIds = recoUnit.childIds;
var initialTransformation = args.DrawingSession.Transform;
// Points of bounding rectangle to align drawn text
float floatX = (float)recoUnit.boundingRectangle.topX;
float floatY = (float)recoUnit.boundingRectangle.topY;
// Rotated bounding rectangle points to get correct angle of text being drawn
float topLeftX = (float)recoUnit.rotatedBoundingRectangle[0].x;
float topLeftY = (float)recoUnit.rotatedBoundingRectangle[0].y;
float topRightX = (float)recoUnit.rotatedBoundingRectangle[1].x;
float topRightY = (float)recoUnit.rotatedBoundingRectangle[1].y;
float bottomRightX = (float)recoUnit.rotatedBoundingRectangle[2].x;
float bottomRightY = (float)recoUnit.rotatedBoundingRectangle[2].y;
float bottomLeftX = (float)recoUnit.rotatedBoundingRectangle[3].x;
float bottomLeftY = (float)recoUnit.rotatedBoundingRectangle[3].y;
// Height and width of bounding rectangle to get font size and width for text layout
float height = GetDistanceBetweenPoints(topRightX, bottomRightX, topRightY, bottomRightY) * dipsPerMm;
float width = GetDistanceBetweenPoints(bottomLeftX, bottomRightX, bottomLeftY, bottomRightY) * dipsPerMm;
if (height < 45)
{
height = 45;
}
// Transform to get correct angle of text
float centerPointX = ((topLeftX + topRightX) / 2) * dipsPerMm;
float centerPointY = ((topLeftY + bottomLeftY) / 2) * dipsPerMm;
var centerPoint = new Vector2(centerPointX, centerPointY);
Matrix3x2 angle = GetRotationAngle(bottomLeftX, bottomRightX, bottomLeftY, bottomRightY, centerPoint);
args.DrawingSession.Transform = angle;
var textFormat = new CanvasTextFormat()
{
FontSize = height - 5,
WordWrapping = CanvasWordWrapping.NoWrap,
FontFamily = "Ink Free"
};
// Build string to be drawn to canvas
string textLine = string.Empty;
foreach (var item in childIds)
{
int id = int.Parse(item.ToString());
// Deconstruct the tuple to get the recognized text from it
(string text, _) = recoText[id];
textLine += text + " ";
}
var textLayout = new CanvasTextLayout(sender.Device, textLine, textFormat, width, height);
// Associate correct color with each word in string
int index = 0;
foreach (var item in childIds)
{
int id = int.Parse(item.ToString());
// Deconstruct the tuple to get the recognized text and color from it
(string text, Color color) = recoText[id];
textLayout.SetColor(index, text.Length, color);
index += text.Length + 1;
}
args.DrawingSession.DrawTextLayout(textLayout, floatX * dipsPerMm, floatY * dipsPerMm, Colors.Black);
args.DrawingSession.Transform = initialTransformation;
}
private void DrawShape(InkRecognitionUnit recoUnit, CanvasDrawEventArgs args)
{
string recognizedObject = recoUnit.recognizedObject;
switch (recognizedObject)
{
case "circle":
DrawCircle(recoUnit, args);
break;
case "ellipse":
DrawEllipse(recoUnit, args);
break;
case "drawing":
DrawHorizontalLine(recoUnit, args);
break;
default:
DrawPolygon(recoUnit, args);
break;
}
}
private void DrawCircle(InkRecognitionUnit recoUnit, CanvasDrawEventArgs args)
{
// Center point and diameter of circle
float floatX = (float)recoUnit.center.x;
float floatY = (float)recoUnit.center.y;
var centerPoint = new Vector2(floatX * dipsPerMm, floatY * dipsPerMm);
float diameter = (float)recoUnit.boundingRectangle.width;
// Color of circle
var color = GetStrokeColor(recoUnit);
// Stroke thickness
var strokeWidth = GetStrokeWidth(recoUnit);
args.DrawingSession.DrawCircle(centerPoint, (diameter * dipsPerMm) / 2, color, strokeWidth);
}
private void DrawEllipse(InkRecognitionUnit recoUnit, CanvasDrawEventArgs args)
{
var initialTransformation = args.DrawingSession.Transform;
// Rotated bounding rectangle points to get correct angle of ellipse being drawn
float floatX = (float)recoUnit.boundingRectangle.topX;
float floatY = (float)recoUnit.boundingRectangle.topY;
float topLeftX = (float)recoUnit.rotatedBoundingRectangle[0].x;
float topLeftY = (float)recoUnit.rotatedBoundingRectangle[0].y;
float topRightX = (float)recoUnit.rotatedBoundingRectangle[1].x;
float topRightY = (float)recoUnit.rotatedBoundingRectangle[1].y;
float bottomRightX = (float)recoUnit.rotatedBoundingRectangle[2].x;
float bottomRightY = (float)recoUnit.rotatedBoundingRectangle[2].y;
float bottomLeftX = (float)recoUnit.rotatedBoundingRectangle[3].x;
float bottomLeftY = (float)recoUnit.rotatedBoundingRectangle[3].y;
// Center point of ellipse
float centerPointX = (float)recoUnit.center.x;
float centerPointY = (float)recoUnit.center.y;
var centerPoint = new Vector2(centerPointX * dipsPerMm, centerPointY * dipsPerMm);
// X and Y diameter of ellipse
float diameterX = GetDistanceBetweenPoints(bottomLeftX, bottomRightX, bottomLeftY, bottomRightY) * dipsPerMm;
float diameterY = GetDistanceBetweenPoints(topRightX, bottomRightX, topRightY, bottomRightY) * dipsPerMm;
// Transform to get correct angle of ellipse
float transformCenterPointX = ((topLeftX + topRightX) / 2) * dipsPerMm;
float transformCenterPointY = ((topLeftY + bottomLeftY) / 2) * dipsPerMm;
var transformCenterPoint = new Vector2(transformCenterPointX, transformCenterPointY);
Matrix3x2 angle = GetRotationAngle(bottomLeftX, bottomRightX, bottomLeftY, bottomRightY, transformCenterPoint);
args.DrawingSession.Transform = angle;
// Color of ellipse
var color = GetStrokeColor(recoUnit);
// Stroke thickness
float strokeWidth = GetStrokeWidth(recoUnit);
args.DrawingSession.DrawEllipse(centerPoint, diameterX / 2, diameterY / 2, color, strokeWidth);
args.DrawingSession.Transform = initialTransformation;
}
private void DrawHorizontalLine(InkRecognitionUnit recoUnit, CanvasDrawEventArgs args)
{
float height = (float)recoUnit.boundingRectangle.height;
float width = (float)recoUnit.boundingRectangle.width;
// The ink recognizer does not recognize horizontal lines, however this check is used as a heuristic to render horizontal lines on the result canvas
if (height <= 10 && width >= 20)
{
// Bottom left and right corner points of rotated bounding rectangle
float pointAX = (float)recoUnit.rotatedBoundingRectangle[0].x;
float pointAY = (float)recoUnit.rotatedBoundingRectangle[0].y;
float pointBX = (float)recoUnit.rotatedBoundingRectangle[1].x;
var pointA = new Vector2(pointAX * dipsPerMm, pointAY * dipsPerMm);
var pointB = new Vector2(pointBX * dipsPerMm, pointAY * dipsPerMm);
// Color of line
var color = GetStrokeColor(recoUnit);
// Stroke thickness
float strokeWidth = GetStrokeWidth(recoUnit);
args.DrawingSession.DrawLine(pointA, pointB, color, strokeWidth);
}
}
private void DrawPolygon(InkRecognitionUnit recoUnit, CanvasDrawEventArgs args)
{
if (recoUnit.points.Count > 0)
{
// Create new list of points for polygon to be drawn
var pointsList = new List<Vector2>();
foreach (var inkPoint in recoUnit.points)
{
float x = (float)inkPoint.x;
float y = (float)inkPoint.y;
var point = new Vector2(x * dipsPerMm, y * dipsPerMm);
pointsList.Add(point);
}
// Create shape from list of points
var points = pointsList.ToArray();
var shape = CanvasGeometry.CreatePolygon(args.DrawingSession, points);
// Color of polygon
var color = GetStrokeColor(recoUnit);
// Stroke thickness
float strokeWidth = GetStrokeWidth(recoUnit);
args.DrawingSession.DrawGeometry(shape, color, strokeWidth);
}
}
#endregion
#region JSON To Tree View
private void CreateJsonTree()
{
// Add all of the ink recognition units that will become nodes to a collection
foreach (var recoUnit in inkResponse.RecognitionUnits)
{
if (recoUnit.parentId == 0)
{
recoTreeParentNodes.Add(recoUnit);
}
else
{
recoTreeNodes.Add(recoUnit.id, recoUnit);
}
}
// Add the initial "root" node for all of the ink recognition units to be added under
string itemCount = $"{recoTreeParentNodes.Count} item{(recoTreeParentNodes.Count > 1 ? "s" : string.Empty)}";
var root = new TreeViewNode()
{
Content = new KeyValuePair<string, string>("Root", itemCount)
};
// Traverse the list of top level parent nodes and append children if they have any
foreach (var parent in recoTreeParentNodes)
{
string category = parent.category;
var node = new TreeViewNode();
if (category == "writingRegion")
{
string childCount = $"{parent.childIds.Count} item{(parent.childIds.Count > 1 ? "s" : string.Empty)}";
node.Content = new KeyValuePair<string, string>(category, childCount);
// Recursively append all children
var childNodes = GetChildNodes(parent);
foreach (var child in childNodes)
{
node.Children.Add(child);
}
}
else if (category == "inkDrawing")
{
node.Content = new KeyValuePair<string, string>(category, parent.recognizedObject);
}
root.Children.Add(node);
}
recoTreeNodes.Clear();
recoTreeParentNodes.Clear();
root.IsExpanded = true;
treeView.RootNodes.Add(root);
}
private List<TreeViewNode> GetChildNodes(InkRecognitionUnit recoUnit)
{
var nodes = new List<TreeViewNode>();
// Iterate over each of the ink recognition unit's children to append them to their parent node
foreach (int id in recoUnit.childIds)
{
InkRecognitionUnit unit = recoTreeNodes[id];
var node = new TreeViewNode();
string category = unit.category;
if (category == "inkWord" || category == "inkBullet")
{
node.Content = new KeyValuePair<string, string>(category, unit.recognizedText);
}
else
{
string childCount = $"{unit.childIds.Count} item{(unit.childIds.Count > 1 ? "s" : string.Empty)}";
node.Content = new KeyValuePair<string, string>(category, childCount);
}
// If the child of the current ink recognition unit also has children recurse to append them to the child node as well
if (unit.childIds != null)
{
var childNodes = GetChildNodes(unit);
foreach (var child in childNodes)
{
node.Children.Add(child);
}
}
nodes.Add(node);
}
return nodes;
}
#endregion
#region Helpers
private void ClearJson()
{
requestJsonText.Text = string.Empty;
responseJsonText.Text = string.Empty;
treeView.RootNodes.Clear();
var resultCanvas = this.FindName("resultCanvas") as CanvasControl;
resultCanvas.Invalidate();
}
private string FormatJson(string json)
{
dynamic parsedJson = JsonConvert.DeserializeObject(json);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
private void ToggleProgressRing()
{
if (progressRing.IsActive == false)
{
recognizeButton.Visibility = Visibility.Collapsed;
progressRing.Visibility = Visibility.Visible;
progressRing.IsActive = true;
}
else
{
progressRing.IsActive = false;
progressRing.Visibility = Visibility.Collapsed;
recognizeButton.Visibility = Visibility.Visible;
}
}
private void ToggleInkToolbar()
{
if (inkToolbar.IsEnabled)
{
inkToolbar.IsEnabled = false;
inkCanvas.InkPresenter.IsInputEnabled = false;
foreach (var child in customToolbar.Children)
{
var button = child as InkToolbarCustomToolButton;
button.IsEnabled = false;
}
}
else
{
inkToolbar.IsEnabled = true;
inkCanvas.InkPresenter.IsInputEnabled = true;
foreach (var child in customToolbar.Children)
{
var button = child as InkToolbarCustomToolButton;
button.IsEnabled = true;
}
}
}
private void NavItemToggle(string navItemName)
{
var resultCanvas = this.FindName("resultCanvas") as CanvasControl;
switch (navItemName)
{
case "resultCanvasNavItem":
jsonTree.Visibility = Visibility.Collapsed;
responseJson.Visibility = Visibility.Collapsed;
requestJson.Visibility = Visibility.Collapsed;
resultCanvas.Visibility = Visibility.Visible;
break;
case "jsonTreeNavItem":
resultCanvas.Visibility = Visibility.Collapsed;
responseJson.Visibility = Visibility.Collapsed;
requestJson.Visibility = Visibility.Collapsed;
jsonTree.Visibility = Visibility.Visible;
break;
case "responseJsonNavItem":
resultCanvas.Visibility = Visibility.Collapsed;
jsonTree.Visibility = Visibility.Collapsed;
requestJson.Visibility = Visibility.Collapsed;
responseJson.Visibility = Visibility.Visible;
break;
case "requestJsonNavItem":
resultCanvas.Visibility = Visibility.Collapsed;
jsonTree.Visibility = Visibility.Collapsed;
responseJson.Visibility = Visibility.Collapsed;
requestJson.Visibility = Visibility.Visible;
break;
}
}
private float GetDistanceBetweenPoints(float x1, float x2, float y1, float y2)
{
float x = (x2 - x1) * (x2 - x1);
float y = (y2 - y1) * (y2 - y1);
float distance = (float)Math.Sqrt(x + y);
return distance;
}
private Matrix3x2 GetRotationAngle(float x1, float x2, float y1, float y2, Vector2 centerPoint)
{
float slope = (y2 - y1) / (x2 - x1);
float radians = (float)Math.Atan(slope);
var angle = Matrix3x2.CreateRotation(radians, centerPoint);
return angle;
}
private Color GetStrokeColor(InkRecognitionUnit recoUnit)
{
uint strokeId = (uint)recoUnit.strokeIds[0];
var color = inkCanvas.InkPresenter.StrokeContainer.GetStrokeById(strokeId).DrawingAttributes.Color;
return color;
}
private float GetStrokeWidth(InkRecognitionUnit recoUnit)
{
uint strokeId = (uint)recoUnit.strokeIds[0];
Size size = inkCanvas.InkPresenter.StrokeContainer.GetStrokeById(strokeId).DrawingAttributes.Size;
float strokeWidth = (float)size.Width;
return strokeWidth;
}
private Color GetColorFromHex(string hexCode)
{
byte a = 255;
byte r = Convert.ToByte(hexCode.Substring(1, 2), 16);
byte g = Convert.ToByte(hexCode.Substring(3, 2), 16);
byte b = Convert.ToByte(hexCode.Substring(5, 2), 16);
return Color.FromArgb(a, r, g, b);
}
#endregion
}
}