aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.Common/RemoteDesktop/DefaultRemoteDesktopService.cs
blob: 5f8933fc690c563588e633a776d60f95b03f2306 (plain)
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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Tango.Core;
using Tango.Core.DI;
using Tango.Core.Threading;
using Tango.Integration.ExternalBridge;
using Tango.Logging;
using Tango.PPC.Common.Application;
using Tango.PPC.Common.Build;
using Tango.PPC.Common.ExternalBridge;
using Tango.PPC.Common.OS;
using Tango.PPC.Common.Printing;
using Tango.RemoteDesktop;
using Tango.RemoteDesktop.CaptureMethods;
using Tango.RemoteDesktop.Encoders;
using Tango.RemoteDesktop.Engines;
using Tango.RemoteDesktop.Frames;
using Tango.RemoteDesktop.Input;
using Tango.RemoteDesktop.Network;
using Tango.Settings;
using Tango.Transport;
using Tango.WebRTC;
using static Tango.RemoteDesktop.Input.MouseController;

namespace Tango.PPC.Common.RemoteDesktop
{
    [TangoCreateWhenRegistered]
    public class DefaultRemoteDesktopService : ExtendedObject, IRemoteDesktopService, IExternalBridgeRequestHandler
    {
        private RemoteDesktopPacket _initialPacket;
        private RasterScreenCaptureEngine _engine;
        private PPCSettings _settings;
        private List<RemoteDesktopClient> _clients;
        private JsonSerializerSettings _jsonSettings;
        private IOperationSystemManager _osManager;
        private IPPCApplicationManager _appManager;
        private IPrintingManager _printingManager;
        private bool _drawCursor;
        private bool _isMouseDown;
        private bool _ensureMouseDown;
        private ActionTimer _resetTimer;
        private IBuildProvider _buildProvider;

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="IPPCService" /> is enabled.
        /// </summary>
        public bool Enabled { get; set; } = true;

        private bool _isStarted;
        /// <summary>
        /// Gets a value indicating whether the remote desktop service has started.
        /// </summary>
        public bool IsStarted
        {
            get { return _isStarted; }
            private set { _isStarted = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets a value indicating whether there is any active remote desktop session with a remote peer.
        /// </summary>
        public bool InSession
        {
            get
            {
                return _clients.Count > 0;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultRemoteDesktopService"/> class.
        /// </summary>
        /// <param name="applicationManager">The application manager.</param>
        /// <param name="externalBridge">The external bridge.</param>
        /// <param name="osManager">The os manager.</param>
        public DefaultRemoteDesktopService(IPPCApplicationManager applicationManager, IPPCExternalBridgeService externalBridge, IOperationSystemManager osManager, IPrintingManager printingManager, IBuildProvider buildProvider)
        {
            _osManager = osManager;
            _appManager = applicationManager;
            _printingManager = printingManager;
            _buildProvider = buildProvider;

            _jsonSettings = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All
            };

            _settings = SettingsManager.Default.GetOrCreate<PPCSettings>();
            Enabled = _settings.EnableRemoteDesktop;

            applicationManager.ApplicationReady += ApplicationManager_ApplicationReady;

            externalBridge.RegisterRequestHandler(this);

            _clients = new List<RemoteDesktopClient>();
            _engine = new RasterScreenCaptureEngine();

            _engine.CaptureCursor = false;

            _engine.FrameRate = Math.Min(Math.Max(_settings.RemoteDesktopFrameRate, 1), 20);
            _engine.FrameReceived += _engine_FrameReceived;

            _resetTimer = new ActionTimer(TimeSpan.FromSeconds(5));
        }

        private void ApplicationManager_ApplicationReady(object sender, EventArgs e)
        {
            var mainWindow = System.Windows.Application.Current.MainWindow;

            if (_buildProvider.MachineType.IsXMachine())
            {
                _engine.CaptureRegion = new CaptureRegion()
                {
                    Left = (int)mainWindow.Left,
                    Top = 0,
                    Width = 1920,
                    Height = 1080
                };
            }

            if (mainWindow.WindowStyle != System.Windows.WindowStyle.None)
            {
                mainWindow.LocationChanged += (_, __) =>
                {
                    _engine.CaptureRegion = new CaptureRegion()
                    {
                        Left = (int)mainWindow.Left + 10,
                        Top = (int)mainWindow.Top + 5,
                        Width = (int)mainWindow.Width - 20,
                        Height = (int)mainWindow.Height - 15
                    };
                };

                _engine.CaptureRegion = new CaptureRegion()
                {
                    Left = (int)mainWindow.Left + 10,
                    Top = (int)mainWindow.Top + 5,
                    Width = (int)mainWindow.Width - 20,
                    Height = (int)mainWindow.Height - 15
                };
            }
            else
            {
                //DirectX capturing is not working on PPC !! Maybe when we replace ?
                //try
                //{
                //    _engine.CaptureMethod = new DirectXScreenCapture();
                //}
                //catch (Exception ex)
                //{
                //    LogManager.Log(ex, "Could not initialize DirectX screen capture method on this device. Falling back to GDI.");
                //}
            }

            mainWindow.PreviewMouseDown += (_, __) =>
            {
                _isMouseDown = true;
                _ensureMouseDown = true;
            };

            mainWindow.PreviewMouseUp += (_, __) =>
            {
                _isMouseDown = false;
            };

            _engine.Comparer.MaxDifferencesThrow = _engine.CaptureRegion.Width * _engine.CaptureRegion.Height / 2;
        }

        [ExternalBridgeRequestHandlerMethod(typeof(StartRemoteDesktopSessionRequest), RequestHandlerLoggingMode.LogRequestName)]
        public async Task OnStartRemoteDesktopSessionRequestReceived(StartRemoteDesktopSessionRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            var client = _clients.SingleOrDefault(x => x.Receiver == receiver);

            if (client != null)
            {
                _clients.Remove(client);
            }

            RemoteDesktopClient newClient = new RemoteDesktopClient();
            newClient.Receiver = receiver;
            newClient.Token = token;
            newClient.WebRtcClient = new WebRtcClient();
            newClient.WebRtcClient.Tag = receiver;
            newClient.WebRtcClient.TextMessageReceived += WebRtcClient_TextMessageReceived;
            _clients.Add(newClient);

            await receiver.SendGenericResponse(new StartRemoteDesktopSessionResponse()
            {
                FrameRate = _engine.FrameRate
            }, token);


            if (!_engine.IsStarted)
            {
                _engine.Start();
            }

            RaisePropertyChanged(nameof(InSession));
        }

        [ExternalBridgeRequestHandlerMethod(typeof(WebRtcIceCandidateRequest), RequestHandlerLoggingMode.LogRequestName)]
        public async Task OnWebRtcIceCandidateRequestReceived(WebRtcIceCandidateRequest request, String token, ExternalBridgeReceiver receiver)
        {
            var client = _clients.SingleOrDefault(x => x.Receiver == receiver);

            if (client != null)
            {
                try
                {
                    await receiver.SendGenericResponse(new WebRtcIceCandidateResponse() { }, token);
                    client.WebRtcClient.AddIceCandidate(request.IceCandidate);
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error adding WebRTC ice candidate received from the remote connection.");
                }
            }
        }

        [ExternalBridgeRequestHandlerMethod(typeof(WebRtcOfferRequest), RequestHandlerLoggingMode.LogRequestName)]
        public async Task OnWebRtcOfferRequestReceived(WebRtcOfferRequest request, String token, ExternalBridgeReceiver receiver)
        {
            var client = _clients.SingleOrDefault(x => x.Receiver == receiver);

            if (client != null)
            {
                try
                {

                    try
                    {
                        client.WebRtcClient.NewIceCandidate += async (x, e) =>
                        {
                            try
                            {
                                await receiver.SendGenericRequest<WebRtcIceCandidateRequest, WebRtcIceCandidateResponse>(new WebRtcIceCandidateRequest() { IceCandidate = e.IceCandidate });
                            }
                            catch (Exception ex)
                            {
                                LogManager.Log(ex, "Error sending ice candidate to remote peer.");
                            }
                        };
                        client.WebRtcClient.Ready += (x, e) =>
                        {
                            client.IsWebRtcReady = true;
                        };
                        client.WebRtcClient.Disconnected += (x, e) =>
                        {
                            client.IsWebRtcReady = false;
                        };

                        client.WebRtcClient.FrameWidth = 800;
                        client.WebRtcClient.FrameHeight = 1280;
                        client.WebRtcClient.FrameRate = _engine.FrameRate;

                        await client.WebRtcClient.Init();

                        var answer = await client.WebRtcClient.CreateAnswer(request.Offer);
                        await receiver.SendGenericResponse(new WebRtcOfferResponse() { Answer = answer }, token);
                    }
                    catch (Exception ex)
                    {
                        throw LogManager.Log(ex, "Error initializing the WebRTC client.");
                    }
                }
                catch (Exception ex)
                {
                    throw LogManager.Log(ex, "Error responding to WebRTC offer request.");
                }
            }
        }

        [ExternalBridgeRequestHandlerMethod(typeof(StopRemoteDesktopSessionRequest), RequestHandlerLoggingMode.LogRequestName)]
        public async Task OnStopRemoteDesktopSessionRequestReceived(StopRemoteDesktopSessionRequest request, String token, ExternalBridgeReceiver receiver)
        {
            var client = _clients.SingleOrDefault(x => x.Receiver == receiver);

            if (client != null)
            {
                _clients.Remove(client);

                if (client.WebRtcClient != null)
                {
                    client.WebRtcClient.Dispose();
                }
            }

            if (_clients.Count == 0)
            {
                _engine.Stop();
            }

            await receiver.SendGenericResponse(new StopRemoteDesktopSessionResponse(), token);

            if (client != null)
            {
                await receiver.SendGenericResponse(new StartRemoteDesktopSessionResponse(), client.Token, new TransportResponseConfig() { Completed = true });
            }

            RaisePropertyChanged(nameof(InSession));
        }

        [ExternalBridgeRequestHandlerMethod(typeof(MouseStateRequest))]
        public async Task OnMouseStateRequestReceived(MouseStateRequest request, String token, ExternalBridgeReceiver receiver)
        {
            MouseController.SetCursorPosition((int)request.Location.X, (int)request.Location.Y);

            if (request.EventType == MouseEventType.Up || request.EventType == MouseEventType.Down)
            {
                MouseEventFlags flag = MouseEventFlags.LeftUp;

                switch (request.EventType)
                {
                    case MouseEventType.Down:
                        flag = request.Button == MouseButton.Right ? MouseEventFlags.RightDown : MouseEventFlags.LeftDown;
                        break;
                    case MouseEventType.Up:
                        flag = request.Button == MouseButton.Right ? MouseEventFlags.RightUp : MouseEventFlags.LeftUp;
                        break;
                }

                if (!receiver.AllowSafetyLevelOperations)
                {
                    Debug.WriteLine("PREVENT PRINT");
                    _printingManager.PreventPrintingByRemoteDesktop = true;
                }

                MouseController.MouseEvent(flag);

                _resetTimer.ResetReplace(() =>
                {
                    _printingManager.PreventPrintingByRemoteDesktop = false;
                    Debug.WriteLine("ALLOW PRINT");
                });
            }
            else if (request.EventType == MouseEventType.DoubleClick)
            {
                if (!receiver.AllowSafetyLevelOperations)
                {
                    _printingManager.PreventPrintingByRemoteDesktop = true;
                }

                MouseController.DoubleClick();

                _resetTimer.ResetReplace(() =>
                {
                    _printingManager.PreventPrintingByRemoteDesktop = false;
                });
            }
            else if (request.EventType == MouseEventType.Scroll)
            {
                MouseController.Scroll(request.ScrollDelta);
            }

            if (receiver != null)
            {
                await receiver.SendGenericResponse(new MouseStateResponse(), token);
            }
        }

        [ExternalBridgeRequestHandlerMethod(typeof(TouchStateRequest))]
        public async Task OnTouchStateRequestReceived(TouchStateRequest request, String token, ExternalBridgeReceiver receiver)
        {
            switch (request.EventType)
            {
                case TouchEventType.TouchDown:
                    TouchController.TouchDown((int)request.Location.X, (int)request.Location.Y);
                    break;
                case TouchEventType.TouchMove:
                    TouchController.TouchMove(request.MoveDeltaX, request.MoveDeltaY);
                    break;
                case TouchEventType.TouchUp:
                    TouchController.TouchUp();
                    break;
            }

            if (receiver != null)
            {
                await receiver.SendGenericResponse(new TouchStateResponse(), token);
            }
        }

        [ExternalBridgeRequestHandlerMethod(typeof(KeyboardStateRequest))]
        public async Task OnKeyboardStateRequestReceived(KeyboardStateRequest request, String token, ExternalBridgeReceiver receiver)
        {
            if (request.EventType == KeyboardEventType.Down)
            {
                KeyboardController.KeyDown(request.Key, request.IsCtrlDown, request.IsShiftDown, request.IsAltDown);
            }
            else
            {
                KeyboardController.KeyUp(request.Key, request.IsCtrlDown, request.IsShiftDown, request.IsAltDown);
            }

            if (receiver != null)
            {
                await receiver.SendGenericResponse(new KeyboardStateResponse(), token);
            }
        }

        [ExternalBridgeRequestHandlerMethod(typeof(RemoteDesktopCommandRequest), RequestHandlerLoggingMode.LogRequestName)]
        public async Task OnRemoteDesktopCommandRequest(RemoteDesktopCommandRequest request, String token, ExternalBridgeReceiver receiver)
        {
            switch (request.Command)
            {
                case RemoteDesktopCommand.HideAndOpenShell:
                    _osManager.OpenShell();
                    _appManager.SetWindowState(System.Windows.WindowState.Minimized);
                    break;
            }

            await receiver.SendGenericResponse(new RemoteDesktopCommandResponse(), token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(SetCursorVisibilityRequest), RequestHandlerLoggingMode.LogRequestName)]
        public async Task OnSetCursorVisibilityRequest(SetCursorVisibilityRequest request, String token, ExternalBridgeReceiver receiver)
        {
            _drawCursor = request.Visible;
            await receiver.SendGenericResponse(new SetCursorVisibilityResponse(), token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(GetScreenshotRequest), RequestHandlerLoggingMode.LogRequestName)]
        public async Task OnGetScreenshotRequest(GetScreenshotRequest request, String token, ExternalBridgeReceiver receiver)
        {
            GdiScreenCapture capture = new GdiScreenCapture();
            var bitmap = capture.GetDesktopBitmap(CaptureRegion.PrimaryScreenBounds());
            RasterFrame frame = new RasterFrame(bitmap);
            var data = frame.ToEncoder<JpegEncoder>().ToArray(80);
            frame.Dispose();

            await receiver.SendGenericResponse(new GetScreenshotResponse() { Bitmap = data }, token);
        }

        private async void _engine_FrameReceived(object sender, ScreenCaptureFrameReceivedEventArgs<RasterFrame> e)
        {
            try
            {
                if (_drawCursor)
                {
                    e.Frame.DrawImage((_isMouseDown || _ensureMouseDown) ? Properties.Resources.tap : Properties.Resources.finger3, new System.Drawing.Point(System.Windows.Forms.Cursor.Position.X - 5, System.Windows.Forms.Cursor.Position.Y - 4));
                    _ensureMouseDown = false;
                }

                _initialPacket = new RemoteDesktopPacket()
                {
                    Bitmap = e.Frame.ToEncoder<PngEncoder>().ToArray(),
                };

                if (_clients.Count > 0)
                {
                    bool useWebRTC = _clients.ToList().All(x => x.IsWebRtcReady);

                    if (useWebRTC)
                    {
                        _engine.EnableComparer = false;

                        foreach (var client in _clients.ToList())
                        {
                            try
                            {
                                client.WebRtcClient.PushFrame(e.Frame.ToBitmap());
                            }
                            catch (Exception ex)
                            {
                                LogManager.Log(ex, LogCategory.Debug, "Error pushing remote desktop frame via WebRTC channel.");
                            }
                        }

                        e.Frame.Dispose();
                    }
                    else
                    {
                        _engine.EnableComparer = !_buildProvider.MachineType.IsXMachine();

                        foreach (var client in _clients.ToList().Where(x => !x.InitialPacketSent))
                        {
                            try
                            {
                                await client.Receiver.SendGenericResponse(new StartRemoteDesktopSessionResponse()
                                {
                                    Packet = _initialPacket,
                                }, client.Token, new TransportResponseConfig()
                                {
                                    Immediate = false,
                                });

                                client.InitialPacketSent = true;
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex);
                            }
                        }

                        if (e.Frame.DifferenceCount > 0 || _buildProvider.MachineType.IsXMachine())
                        {
                            RemoteDesktopPacket packet = null;

                            Point mousePosition = new Point(System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y);

                            if (!e.Frame.DifferenceAvailable || _buildProvider.MachineType.IsXMachine())
                            {
                                packet = new RemoteDesktopPacket()
                                {
                                    Bitmap = e.Frame.ToEncoder<JpegEncoder>().ToArray(30),
                                    MousePosition = mousePosition,
                                    CursorVisible = _drawCursor
                                };
                            }
                            else
                            {
                                var diffFrame = e.Frame.ToDifference();
                                diffFrame = diffFrame.OptimizeBounds();

                                packet = new RemoteDesktopPacket()
                                {
                                    Bitmap = diffFrame.ToEncoder<PngEncoder>().ToArray(),
                                    IsPartial = true,
                                    PartialRegion = new CaptureRegion(diffFrame.Left, diffFrame.Top, diffFrame.Width, diffFrame.Height),
                                    MousePosition = mousePosition,
                                    CursorVisible = _drawCursor
                                };

                                diffFrame.Dispose();
                            }

                            Debug.WriteLine($"Remote Desktop Bitmap Size: {packet.Bitmap.Length / 1000} kb");

                            foreach (var client in _clients.ToList().Where(x => x.InitialPacketSent))
                            {
                                try
                                {
                                    await client.Receiver.SendGenericResponse(new StartRemoteDesktopSessionResponse()
                                    {
                                        Packet = packet
                                    }, client.Token, new TransportResponseConfig()
                                    {
                                        Immediate = false,
                                    });
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine(ex);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error occurred on remote desktop engine frame received event.");
            }
            finally
            {
                e.Frame.Dispose();
            }
        }

        private async void WebRtcClient_TextMessageReceived(object sender, DataMessageReceivedEventArgs<string> e)
        {
            try
            {
                var request = JsonConvert.DeserializeObject(e.Data, _jsonSettings);

                if (request.GetType() == typeof(MouseStateRequest))
                {
                    await OnMouseStateRequestReceived(request as MouseStateRequest, null, (sender as WebRtcClient).Tag as ExternalBridgeReceiver);
                }
                else if (request.GetType() == typeof(KeyboardStateRequest))
                {
                    await OnKeyboardStateRequestReceived(request as KeyboardStateRequest, null, null);
                }
                else if (request.GetType() == typeof(TouchStateRequest))
                {
                    await OnTouchStateRequestReceived(request as TouchStateRequest, null, null);
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error deserializing incoming message on the WebRTC data Channel.");
            }
        }

        public void OnReceiverDisconnected(ExternalBridgeReceiver receiver)
        {
            var client = _clients.SingleOrDefault(x => x.Receiver == receiver);

            if (client != null)
            {
                LogManager.Log("Remote desktop client disconnected. Disposing WebRTC channel...");

                _clients.Remove(client);

                try
                {
                    if (client.WebRtcClient != null)
                    {
                        client.WebRtcClient.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error disposing the WebRTC channel.");
                }
            }

            if (_clients.Count == 0)
            {
                _engine.Stop();
            }

            RaisePropertyChanged(nameof(InSession));
        }
    }
}