-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Copy pathChromiumWebBrowser.cs
2862 lines (2515 loc) · 114 KB
/
ChromiumWebBrowser.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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2013 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using CefSharp.Enums;
using CefSharp.Internals;
using CefSharp.Structs;
using CefSharp.Wpf.Experimental;
using CefSharp.Wpf.Handler;
using CefSharp.Wpf.Internals;
using CefSharp.Wpf.Rendering;
using Microsoft.Win32.SafeHandles;
using CursorType = CefSharp.Enums.CursorType;
using Point = System.Windows.Point;
using Range = CefSharp.Structs.Range;
using Rect = CefSharp.Structs.Rect;
using Size = System.Windows.Size;
namespace CefSharp.Wpf
{
/// <summary>
/// ChromiumWebBrowser is the WPF web browser control
/// </summary>
/// <seealso cref="System.Windows.Controls.Control" />
/// <seealso cref="CefSharp.Wpf.IWpfWebBrowser" />
[TemplatePart(Name = PartImageName, Type = typeof(Image))]
[TemplatePart(Name = PartPopupImageName, Type = typeof(Image))]
public partial class ChromiumWebBrowser : Control, IRenderWebBrowser, IWpfWebBrowser
{
/// <summary>
/// TemplatePart Name constant for the Image used to represent the browser
/// </summary>
public const string PartImageName = "PART_image";
/// <summary>
/// TemplatePart Name constant for the Image used to represent the popup
/// overlayed on the browser
/// </summary>
public const string PartPopupImageName = "PART_popupImage";
/// <summary>
/// View Rectangle used by <see cref="GetViewRect"/>
/// </summary>
private Rect viewRect;
/// <summary>
/// Store the previous window state, used to determine if the
/// Windows was previous <see cref="WindowState.Minimized"/>
/// and resume rendering
/// </summary>
private WindowState previousWindowState;
/// <summary>
/// The source
/// </summary>
private HwndSource source;
/// <summary>
/// The HwndSource RootVisual (Window) - We store a reference
/// to unsubscribe event handlers
/// </summary>
private Window sourceWindow;
/// <summary>
/// The MonitorInfo based on the current hwnd
/// </summary>
private MonitorInfoEx monitorInfo;
/// <summary>
/// The tooltip timer
/// </summary>
private DispatcherTimer tooltipTimer;
/// <summary>
/// The tool tip
/// </summary>
private ToolTip toolTip;
/// <summary>
/// The managed cef browser adapter
/// </summary>
private IBrowserAdapter managedCefBrowserAdapter;
/// <summary>
/// The ignore URI change
/// </summary>
private bool ignoreUriChange;
/// <summary>
/// Initial address
/// </summary>
private string initialAddress;
/// <summary>
/// Used to stop multiple threads trying to load the initial Url multiple times.
/// If the Address property is bound after the browser is initialized
/// </summary>
private bool initialLoadCalled;
/// <summary>
/// Has the underlying Cef Browser been created (slightly different to initialized in that
/// the browser is initialized in an async fashion)
/// </summary>
private bool browserCreated;
/// <summary>
/// The image that represents this browser instances
/// </summary>
private Image image;
/// <summary>
/// The popup image
/// </summary>
private Image popupImage;
/// <summary>
/// Location of the control on the screen, relative to Top/Left
/// Used to calculate GetScreenPoint
/// We're unable to call PointToScreen directly due to treading restrictions
/// and calling in a sync fashion on the UI thread was problematic.
/// </summary>
private Point browserScreenLocation;
/// <summary>
/// Browser initialization settings
/// </summary>
private IBrowserSettings browserSettings;
/// <summary>
/// The request context (we deliberately use a private variable so we can throw an exception if
/// user attempts to set after browser created)
/// </summary>
private IRequestContext requestContext;
/// <summary>
/// Keep a short term copy of IDragData, so when calling DoDragDrop, DragEnter is called,
/// we can reuse the drag data provided from CEF
/// </summary>
private IDragData currentDragData;
/// <summary>
/// Keep the current drag&drop effects to return the appropriate effects on drag over.
/// </summary>
private DragDropEffects? currentDragDropEffects;
/// <summary>
/// A flag that indicates whether or not the designer is active
/// NOTE: Needs to be static for OnApplicationExit
/// </summary>
private static bool DesignMode;
// https://github.com/chromiumembedded/cef/issues/3427
private bool resizeHackIgnoreOnPaint;
private Structs.Size? resizeHackSize;
/// <summary>
/// This flag is set when the browser gets focus before the underlying CEF browser
/// has been initialized.
/// </summary>
private bool initialFocus;
/// <summary>
/// The class that coordinates the positioning of the dropdown if wanted.
/// </summary>
internal IMousePositionTransform MousePositionTransform { get; set; }
/// <summary>
/// When enabled the browser will resize by 1px when it becomes visible to workaround
/// the upstream issue
/// Hack to work around upstream issue https://github.com/chromiumembedded/cef/issues/3427
/// Disabled by default
/// </summary>
public bool ResizeHackEnabled { get; set; } = false;
/// <summary>
/// Number of milliseconds to wait after resizing the browser when it first
/// becomes visible. After the delay the browser will revert to it's
/// original size.
/// Hack to workaround upstream issue https://github.com/chromiumembedded/cef/issues/3427
/// </summary>
public int ResizeHackDelayInMs { get; set; } = 50;
/// <summary>
/// Gets a value indicating whether this instance is disposed.
/// </summary>
/// <value><see langword="true" /> if this instance is disposed; otherwise, <see langword="false" />.</value>
public bool IsDisposed
{
get
{
return Interlocked.CompareExchange(ref disposeSignaled, 1, 1) == 1;
}
}
/// <summary>
/// WPF Keyboard Handled forwards key events to the underlying browser
/// </summary>
public IWpfKeyboardHandler WpfKeyboardHandler { get; set; }
/// <summary>
/// Gets or sets the browser settings.
/// </summary>
/// <value>The browser settings.</value>
public IBrowserSettings BrowserSettings
{
get { return browserSettings; }
set
{
if (browserCreated)
{
throw new Exception("Browser has already been created. BrowserSettings must be " +
"set before the underlying CEF browser is created.");
}
//New instance is created in the constructor, if you use
//xaml to initialize browser settings then it will also create a new
//instance, so we dispose of the old one
if (browserSettings != null && browserSettings.AutoDispose)
{
browserSettings.Dispose();
}
browserSettings = value;
}
}
/// <summary>
/// Gets or sets the request context.
/// </summary>
/// <value>The request context.</value>
public IRequestContext RequestContext
{
get { return requestContext; }
set
{
if (browserCreated)
{
throw new Exception("Browser has already been created. RequestContext must be " +
"set before the underlying CEF browser is created.");
}
if (value != null && !Core.ObjectFactory.RequestContextType.IsAssignableFrom(value.UnWrap().GetType()))
{
throw new Exception(string.Format("RequestContext can only be of type {0} or null", Core.ObjectFactory.RequestContextType));
}
requestContext = value;
}
}
/// <summary>
/// Implement <see cref="IRenderHandler"/> and control how the control is rendered
/// </summary>
/// <value>The render Handler.</value>
public IRenderHandler RenderHandler { get; set; }
/// <summary>
/// Implement <see cref="IAccessibilityHandler" /> to handle events related to accessibility.
/// </summary>
/// <value>The accessibility handler.</value>
public IAccessibilityHandler AccessibilityHandler { get; set; }
/// <summary>
/// Raised every time <see cref="IRenderWebBrowser.OnPaint"/> is called. You can access the underlying buffer, though it's
/// preferable to either override <see cref="OnPaint"/> or implement your own <see cref="IRenderHandler"/> as there is no outwardly
/// accessible locking (locking is done within the default <see cref="IRenderHandler"/> implementations).
/// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI thread
/// </summary>
public event EventHandler<PaintEventArgs> Paint;
/// <summary>
/// Raised every time <see cref="IRenderWebBrowser.OnVirtualKeyboardRequested(IBrowser, TextInputMode)"/> is called.
/// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI thread
/// </summary>
public event EventHandler<VirtualKeyboardRequestedEventArgs> VirtualKeyboardRequested;
/// <summary>
/// Navigates to the previous page in the browser history. Will automatically be enabled/disabled depending on the
/// browser state.
/// </summary>
/// <value>The back command.</value>
public ICommand BackCommand { get; private set; }
/// <summary>
/// Navigates to the next page in the browser history. Will automatically be enabled/disabled depending on the
/// browser state.
/// </summary>
/// <value>The forward command.</value>
public ICommand ForwardCommand { get; private set; }
/// <summary>
/// Reloads the content of the current page. Will automatically be enabled/disabled depending on the browser state.
/// </summary>
/// <value>The reload command.</value>
public ICommand ReloadCommand { get; private set; }
/// <summary>
/// Prints the current browser contents.
/// </summary>
/// <value>The print command.</value>
public ICommand PrintCommand { get; private set; }
/// <summary>
/// Increases the zoom level.
/// </summary>
/// <value>The zoom in command.</value>
public ICommand ZoomInCommand { get; private set; }
/// <summary>
/// Decreases the zoom level.
/// </summary>
/// <value>The zoom out command.</value>
public ICommand ZoomOutCommand { get; private set; }
/// <summary>
/// Resets the zoom level to the default. (100%)
/// </summary>
/// <value>The zoom reset command.</value>
public ICommand ZoomResetCommand { get; private set; }
/// <summary>
/// Opens up a new program window (using the default text editor) where the source code of the currently displayed web
/// page is shown.
/// </summary>
/// <value>The view source command.</value>
public ICommand ViewSourceCommand { get; private set; }
/// <summary>
/// Command which cleans up the Resources used by the ChromiumWebBrowser
/// </summary>
/// <value>The cleanup command.</value>
public ICommand CleanupCommand { get; private set; }
/// <summary>
/// Stops loading the current page.
/// </summary>
/// <value>The stop command.</value>
public ICommand StopCommand { get; private set; }
/// <summary>
/// Cut selected text to the clipboard.
/// </summary>
/// <value>The cut command.</value>
public ICommand CutCommand { get; private set; }
/// <summary>
/// Copy selected text to the clipboard.
/// </summary>
/// <value>The copy command.</value>
public ICommand CopyCommand { get; private set; }
/// <summary>
/// Paste text from the clipboard.
/// </summary>
/// <value>The paste command.</value>
public ICommand PasteCommand { get; private set; }
/// <summary>
/// Select all text.
/// </summary>
/// <value>The select all command.</value>
public ICommand SelectAllCommand { get; private set; }
/// <summary>
/// Undo last action.
/// </summary>
/// <value>The undo command.</value>
public ICommand UndoCommand { get; private set; }
/// <summary>
/// Redo last action.
/// </summary>
/// <value>The redo command.</value>
public ICommand RedoCommand { get; private set; }
/// <inheritdoc/>
public ICommand ToggleAudioMuteCommand { get; private set; }
/// <summary>
/// The dpi scale factor, if the browser has already been initialized
/// you must manually call IBrowserHost.NotifyScreenInfoChanged for the
/// browser to be notified of the change.
/// </summary>
public float DpiScaleFactor { get; set; }
/// <summary>
/// Initializes static members of the <see cref="ChromiumWebBrowser"/> class.
/// </summary>
//TODO: Currently only a single Dispatcher is supported, all controls will
//be Shutdown on that dispatcher which may not actually be the correct Dispatcher.
//We could potentially use a ThreadStatic variable to implement this behaviour
//and support multiple dispatchers.
static ChromiumWebBrowser()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(ChromiumWebBrowser),
new FrameworkPropertyMetadata(typeof(ChromiumWebBrowser)));
if (CefSharpSettings.ShutdownOnExit)
{
//Use Dispatcher.FromThread as it returns null if no dispatcher
//is available for this thread.
var dispatcher = Dispatcher.FromThread(Thread.CurrentThread);
if (dispatcher == null)
{
//No dispatcher then we'll rely on Application.Exit
var app = Application.Current;
if (app != null)
{
app.Exit += OnApplicationExit;
}
}
else
{
dispatcher.ShutdownStarted += DispatcherShutdownStarted;
dispatcher.ShutdownFinished += DispatcherShutdownFinished;
}
}
}
/// <summary>
/// Handles Dispatcher Shutdown
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">eventargs</param>
private static void DispatcherShutdownStarted(object sender, EventArgs e)
{
var dispatcher = (Dispatcher)sender;
dispatcher.ShutdownStarted -= DispatcherShutdownStarted;
if (!DesignMode)
{
CefPreShutdown();
}
}
private static void DispatcherShutdownFinished(object sender, EventArgs e)
{
var dispatcher = (Dispatcher)sender;
dispatcher.ShutdownFinished -= DispatcherShutdownFinished;
if (!DesignMode)
{
CefShutdown();
}
}
/// <summary>
/// Handles the <see cref="E:ApplicationExit" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="ExitEventArgs"/> instance containing the event data.</param>
private static void OnApplicationExit(object sender, ExitEventArgs e)
{
if (!DesignMode)
{
CefShutdown();
}
}
/// <summary>
/// Required for designer support - this method cannot be inlined as the designer
/// will attempt to load libcef.dll and will subsequently throw an exception.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CefPreShutdown()
{
Cef.PreShutdown();
}
/// <summary>
/// Required for designer support - this method cannot be inlined as the designer
/// will attempt to load libcef.dll and will subsequently throw an exception.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CefShutdown()
{
Cef.Shutdown();
}
/// <summary>
/// To control how <see cref="Cef.Shutdown"/> is called, this method will
/// unsubscribe from <see cref="Application.Exit"/>,
/// <see cref="Dispatcher.ShutdownStarted"/> and <see cref="Dispatcher.ShutdownFinished"/>.
/// </summary>
public static void UnregisterShutdownHandler()
{
//Use Dispatcher.FromThread as it returns null if no dispatcher
//is available for this thread.
var dispatcher = Dispatcher.FromThread(Thread.CurrentThread);
if (dispatcher != null)
{
dispatcher.ShutdownStarted -= DispatcherShutdownStarted;
dispatcher.ShutdownFinished -= DispatcherShutdownFinished;
}
var app = Application.Current;
if (app != null)
{
app.Exit -= OnApplicationExit;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ChromiumWebBrowser"/> class.
/// </summary>
/// <exception cref="System.InvalidOperationException">Cef::Initialize() failed</exception>
public ChromiumWebBrowser()
{
DesignMode = System.ComponentModel.DesignerProperties.GetIsInDesignMode(this);
if (!DesignMode)
{
NoInliningConstructor();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ChromiumWebBrowser"/> class.
/// Use this constructor to load the browser before it's attached to the Visual Tree.
/// The underlying CefBrowser will be created with the specified <paramref name="size"/>.
/// CEF requires positive values for <see cref="Size.Width"/> and <see cref="Size.Height"/>,
/// if values less than 1 are specified then the default value of 1 will be used instead.
/// You can subscribe to the <see cref="LoadingStateChanged"/> event and attach the browser
/// to its parent control when Loading is complete (<see cref="LoadingStateChangedEventArgs.IsLoading"/> is false).
/// </summary>
/// <param name="parentWindowHwndSource">HwndSource for the Window that will host the browser.</param>
/// <param name="initialAddress">address to be loaded when the browser is created.</param>
/// <param name="size">size</param>
/// <example>
/// <code>
/// //Obtain Hwnd from parent window
/// var hwndSource = (HwndSource)PresentationSource.FromVisual(this);
/// var browser = new ChromiumWebBrowser(hwndSource, "github.com", 1024, 768);
/// browser.LoadingStateChanged += OnBrowserLoadingStateChanged;
///
/// private void OnBrowserLoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
/// {
/// if (e.IsLoading == false)
/// {
/// var b = (ChromiumWebBrowser)sender;
/// b.LoadingStateChanged -= OnBrowserLoadingStateChanged;
/// Dispatcher.InvokeAsync(() =>
/// {
/// //Attach to visual tree
/// ParentControl.Child = b;
/// });
/// }
/// }
/// </code>
/// </example>
public ChromiumWebBrowser(HwndSource parentWindowHwndSource, string initialAddress, Size size) : this(initialAddress)
{
CreateBrowser(parentWindowHwndSource, size);
}
/// <summary>
/// Initializes a new instance of the <see cref="ChromiumWebBrowser"/> class.
/// The specified <paramref name="initialAddress"/> will be loaded initially.
/// Use this constructor if you are loading a Chrome Extension.
/// </summary>
/// <param name="initialAddress">address to be loaded when the browser is created.</param>
public ChromiumWebBrowser(string initialAddress)
{
this.initialAddress = initialAddress;
NoInliningConstructor();
}
/// <summary>
/// Constructor logic has been moved into this method
/// Required for designer support - this method cannot be inlined as the designer
/// will attempt to load libcef.dll and will subsequently throw an exception.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private void NoInliningConstructor()
{
InitializeCefInternal();
//Add this ChromiumWebBrowser instance to a list of IDisposable objects
// that if still alive at the time Cef.Shutdown is called will be disposed of
// It's important all browser instances be freed before Cef.Shutdown is called.
Cef.AddDisposable(this);
Focusable = true;
FocusVisualStyle = null;
IsTabStop = true;
Dispatcher.BeginInvoke((Action)(() => WebBrowser = this));
Loaded += OnLoaded;
SizeChanged += OnActualSizeChanged;
GotKeyboardFocus += OnGotKeyboardFocus;
LostKeyboardFocus += OnLostKeyboardFocus;
// Drag Drop events
DragEnter += OnDragEnter;
DragOver += OnDragOver;
DragLeave += OnDragLeave;
Drop += OnDrop;
IsVisibleChanged += OnIsVisibleChanged;
ToolTip = toolTip = new ToolTip();
toolTip.StaysOpen = true;
toolTip.Visibility = Visibility.Collapsed;
toolTip.Closed += OnTooltipClosed;
BackCommand = new DelegateCommand(this.Back, () => CanGoBack);
ForwardCommand = new DelegateCommand(this.Forward, () => CanGoForward);
ReloadCommand = new DelegateCommand(this.Reload, () => !IsLoading);
PrintCommand = new DelegateCommand(this.Print);
ZoomInCommand = new DelegateCommand(ZoomIn);
ZoomOutCommand = new DelegateCommand(ZoomOut);
ZoomResetCommand = new DelegateCommand(ZoomReset);
ViewSourceCommand = new DelegateCommand(this.ViewSource);
CleanupCommand = new DelegateCommand(Dispose);
StopCommand = new DelegateCommand(this.Stop);
CutCommand = new DelegateCommand(this.Cut);
CopyCommand = new DelegateCommand(this.Copy);
PasteCommand = new DelegateCommand(this.Paste);
SelectAllCommand = new DelegateCommand(this.SelectAll);
UndoCommand = new DelegateCommand(this.Undo);
RedoCommand = new DelegateCommand(this.Redo);
ToggleAudioMuteCommand = new DelegateCommand(this.ToggleAudioMute);
managedCefBrowserAdapter = ManagedCefBrowserAdapter.Create(this, true);
browserSettings = Core.ObjectFactory.CreateBrowserSettings(autoDispose: true);
WpfKeyboardHandler = new WpfKeyboardHandler(this);
PresentationSource.AddSourceChangedHandler(this, PresentationSourceChangedHandler);
MenuHandler = new ContextMenuHandler();
MousePositionTransform = new NoOpMousePositionTransform();
UseLayoutRounding = true;
}
/// <summary>
/// Finalizes an instance of the <see cref="ChromiumWebBrowser"/> class.
/// </summary>
~ChromiumWebBrowser()
{
Dispose(false);
}
/// <summary>
/// Releases all resources used by the <see cref="ChromiumWebBrowser"/> object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// If not in design mode; Releases unmanaged and - optionally - managed resources for the <see cref="ChromiumWebBrowser"/>
/// </summary>
/// <param name="disposing"><see langword="true" /> to release both managed and unmanaged resources; <see langword="false" /> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
// Attempt to move the disposeSignaled state from 0 to 1. If successful, we can be assured that
// this thread is the first thread to do so, and can safely dispose of the object.
if (Interlocked.CompareExchange(ref disposeSignaled, 1, 0) != 0)
{
return;
}
if (DesignMode)
{
return;
}
InternalDispose(disposing);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources for the <see cref="ChromiumWebBrowser"/>
/// </summary>
/// <param name="disposing"><see langword="true" /> to release both managed and unmanaged resources; <see langword="false" /> to release only unmanaged resources.</param>
/// <remarks>
/// This method cannot be inlined as the designer will attempt to load libcef.dll and will subsequently throw an exception.
/// </remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
private void InternalDispose(bool disposing)
{
if (disposing)
{
CanExecuteJavascriptInMainFrame = false;
Interlocked.Exchange(ref browserInitialized, 0);
//Stop rendering immediately so later on when we dispose of the
//RenderHandler no further OnPaint calls take place
//Check browser not null as it's possible to call Dispose before it's created
if (browser?.IsDisposed == false)
{
browser?.GetHost().WasHidden(true);
}
UiThreadRunAsync(() =>
{
SetCurrentValue(IsBrowserInitializedProperty, false);
WebBrowser = null;
});
// No longer reference event listeners:
ConsoleMessage = null;
FrameLoadEnd = null;
FrameLoadStart = null;
AddressChanged = null;
IsBrowserInitializedChanged = null;
LoadError = null;
LoadingStateChanged = null;
Paint = null;
StatusMessage = null;
TitleChanged = null;
VirtualKeyboardRequested = null;
JavascriptMessageReceived = null;
// Release reference to handlers, except LifeSpanHandler which is done after Disposing
// ManagedCefBrowserAdapter otherwise the ILifeSpanHandler.DoClose will not be invoked.
// We also leave FocusHandler and override with a NoFocusHandler implementation as
// it so we can block taking Focus (we're dispoing afterall). Issue #3715
FreeHandlersExceptLifeSpanAndFocus();
FocusHandler = new NoFocusHandler();
browser = null;
BrowserCore = null;
// In case we accidentally have a reference to the CEF drag data
currentDragData?.Dispose();
currentDragData = null;
PresentationSource.RemoveSourceChangedHandler(this, PresentationSourceChangedHandler);
// Release window event listeners if PresentationSourceChangedHandler event wasn't
// fired before Dispose
if (sourceWindow != null)
{
sourceWindow.StateChanged -= OnWindowStateChanged;
sourceWindow.LocationChanged -= OnWindowLocationChanged;
sourceWindow = null;
}
// Release internal event listeners:
Loaded -= OnLoaded;
SizeChanged -= OnActualSizeChanged;
GotKeyboardFocus -= OnGotKeyboardFocus;
LostKeyboardFocus -= OnLostKeyboardFocus;
// Release internal event listeners for Drag Drop events:
DragEnter -= OnDragEnter;
DragOver -= OnDragOver;
DragLeave -= OnDragLeave;
Drop -= OnDrop;
IsVisibleChanged -= OnIsVisibleChanged;
if (tooltipTimer != null)
{
tooltipTimer.Tick -= OnTooltipTimerTick;
tooltipTimer.Stop();
tooltipTimer = null;
}
if (CleanupElement != null)
{
CleanupElement.Unloaded -= OnCleanupElementUnloaded;
}
managedCefBrowserAdapter?.Dispose();
managedCefBrowserAdapter = null;
// LifeSpanHandler is set to null after managedCefBrowserAdapter.Dispose so ILifeSpanHandler.DoClose
// is called.
LifeSpanHandler = null;
WpfKeyboardHandler?.Dispose();
WpfKeyboardHandler = null;
//Take a copy of the RenderHandler then set to property to null
//Before we dispose, reduces the changes of any OnPaint calls
//using the RenderHandler after Dispose
var renderHandler = RenderHandler;
RenderHandler = null;
renderHandler?.Dispose();
source = null;
}
Cef.RemoveDisposable(this);
}
/// <summary>
/// Gets the ScreenInfo - currently used to get the DPI scale factor.
/// </summary>
/// <returns>ScreenInfo containing the current DPI scale factor</returns>
ScreenInfo? IRenderWebBrowser.GetScreenInfo()
{
return GetScreenInfo();
}
/// <summary>
/// Gets the ScreenInfo - currently used to get the DPI scale factor.
/// </summary>
/// <returns>ScreenInfo containing the current DPI scale factor</returns>
protected virtual ScreenInfo? GetScreenInfo()
{
Rect rect = monitorInfo.Monitor;
Rect availableRect = monitorInfo.WorkArea;
if (DpiScaleFactor > 1.0)
{
rect = rect.ScaleByDpi(DpiScaleFactor);
availableRect = availableRect.ScaleByDpi(DpiScaleFactor);
}
var screenInfo = new ScreenInfo
{
DeviceScaleFactor = DpiScaleFactor,
Rect = rect,
AvailableRect = availableRect
};
return screenInfo;
}
/// <summary>
/// Called to retrieve the view rectangle which is relative to screen coordinates.
/// This method must always provide a non-empty rectangle.
/// </summary>
/// <returns>View Rectangle</returns>
Rect IRenderWebBrowser.GetViewRect()
{
return GetViewRect();
}
/// <summary>
/// Called to retrieve the view rectangle which is relative to screen coordinates.
/// This method must always provide a non-empty rectangle.
/// </summary>
/// <returns>View Rectangle</returns>
protected virtual Rect GetViewRect()
{
//Take a local copy as the value is set on a different thread,
//Its possible the struct is set to null after our initial check.
var resizeRect = resizeHackSize;
if (resizeRect == null)
{
return viewRect;
}
var size = resizeRect.Value;
return new Rect(0, 0, size.Width, size.Height);
}
/// <inheritdoc />
bool IRenderWebBrowser.GetScreenPoint(int viewX, int viewY, out int screenX, out int screenY)
{
return GetScreenPoint(viewX, viewY, out screenX, out screenY);
}
/// <summary>
/// Called to retrieve the translation from view coordinates to actual screen coordinates.
/// </summary>
/// <param name="viewX">x</param>
/// <param name="viewY">y</param>
/// <param name="screenX">screen x</param>
/// <param name="screenY">screen y</param>
/// <returns>Return true if the screen coordinates were provided.</returns>
protected virtual bool GetScreenPoint(int viewX, int viewY, out int screenX, out int screenY)
{
screenX = 0;
screenY = 0;
//We manually calculate the screen point as calling PointToScreen can only be called on the UI thread
// in a sync fashion and it's easy for users to get themselves into a deadlock.
if (DpiScaleFactor > 1)
{
screenX = (int)(browserScreenLocation.X + (viewX * DpiScaleFactor));
screenY = (int)(browserScreenLocation.Y + (viewY * DpiScaleFactor));
}
else
{
screenX = (int)(browserScreenLocation.X + viewX);
screenY = (int)(browserScreenLocation.Y + viewY);
}
return true;
}
/// <inheritdoc />
bool IRenderWebBrowser.StartDragging(IDragData dragData, DragOperationsMask allowedOps, int x, int y)
{
return StartDragging(dragData, allowedOps, x, y);
}
/// <summary>
/// Called when the user starts dragging content in the web view.
/// OS APIs that run a system message loop may be used within the StartDragging call.
/// Don't call any of IBrowserHost::DragSource*Ended* methods after returning false.
/// Call IBrowserHost.DragSourceEndedAt and DragSourceSystemDragEnded either synchronously or asynchronously to inform the web view that the drag operation has ended.
/// </summary>
/// <param name="dragData"> Contextual information about the dragged content</param>
/// <param name="allowedOps">allowed operations</param>
/// <param name="x">is the drag start location in screen coordinates</param>
/// <param name="y">is the drag start location in screen coordinates</param>
/// <returns>Return true to handle the drag operation.</returns>
protected virtual bool StartDragging(IDragData dragData, DragOperationsMask allowedOps, int x, int y)
{
var dataObject = new DataObject();
dataObject.SetText(dragData.FragmentText, TextDataFormat.Text);
dataObject.SetText(dragData.FragmentText, TextDataFormat.UnicodeText);
dataObject.SetText(dragData.FragmentHtml, TextDataFormat.Html);
//Clone dragData for use in OnDragEnter event handler
currentDragData = dragData.Clone();
currentDragData.ResetFileContents();
// TODO: The following code block *should* handle images, but GetFileContents is
// not yet implemented.
//if (dragData.IsFile)
//{
// var bmi = new BitmapImage();
// bmi.BeginInit();
// bmi.StreamSource = dragData.GetFileContents();
// bmi.EndInit();
// dataObject.SetImage(bmi);
//}
UiThreadRunAsync(delegate
{
if (browser != null)
{
// DoDragDrop will fire DragEnter event
var result = DragDrop.DoDragDrop(this, dataObject, allowedOps.GetDragEffects());
var dragOperationMask = GetDragOperationsMask(result, currentDragDropEffects);
// DragData was stored so when DoDragDrop fires DragEnter we reuse a clone of the IDragData provided here
currentDragData = null;
currentDragDropEffects = null;
// If result or the last recorded drag drop effect were DragDropEffects.None
// then we'll send DragOperationsMask.None, effectively cancelling the drag operation
browser.GetHost().DragSourceEndedAt(x, y, dragOperationMask);
browser.GetHost().DragSourceSystemDragEnded();
}
});
return true;
}
protected virtual DragOperationsMask GetDragOperationsMask(DragDropEffects result, DragDropEffects? dragEffects)
{
// Ensure the drag and drop operation wasn't cancelled
var finalEffectMask = (dragEffects ?? DragDropEffects.None).GetDragOperationsMask() & result.GetDragOperationsMask();
// We shouldn't have an instance where finalEffectMask signfies multiple effects, as the operation
// set by UpdateDragCursor should only ever be none, move, copy, or link. However, if it does, we'll
// just default to copy, as that reflects the defaulting behavior of GetDragEffects.
if (finalEffectMask.HasFlag(DragOperationsMask.Every))
{
return DragOperationsMask.Copy;
}
return finalEffectMask;
}
/// <inheritdoc />
void IRenderWebBrowser.UpdateDragCursor(DragOperationsMask operation)
{
UpdateDragCursor(operation);
}
/// <summary>
/// Called when the web view wants to update the mouse cursor during a drag & drop operation.
/// </summary>
/// <param name="operation">describes the allowed operation (none, move, copy, link). </param>
protected virtual void UpdateDragCursor(DragOperationsMask operation)
{
currentDragDropEffects = operation.GetDragEffects();
}
/// <inheritdoc />
void IRenderWebBrowser.OnAcceleratedPaint(PaintElementType type, Rect dirtyRect, AcceleratedPaintInfo acceleratedPaintInfo)
{
OnAcceleratedPaint(type == PaintElementType.Popup, dirtyRect, acceleratedPaintInfo);
}
/// <summary>
/// Called when an element has been rendered to the shared texture handle.
/// This method is only called when <see cref="IWindowInfo.SharedTextureEnabled"/> is set to true
///
/// The underlying implementation uses a pool to deliver frames. As a result,
/// the handle may differ every frame depending on how many frames are
/// in-progress. The handle's resource cannot be cached and cannot be accessed
/// outside of this callback. It should be reopened each time this callback is
/// executed and the contents should be copied to a texture owned by the
/// client application. The contents of <paramref name="acceleratedPaintInfo"/>acceleratedPaintInfo
/// will be released back to the pool after this callback returns.
/// </summary>
/// <param name="isPopup">indicates whether the element is the view or the popup widget.</param>
/// <param name="dirtyRect">contains the set of rectangles in pixel coordinates that need to be repainted</param>
/// <param name="acceleratedPaintInfo">contains the shared handle; on Windows it is a
/// HANDLE to a texture that can be opened with D3D11 OpenSharedResource.</param>
protected virtual void OnAcceleratedPaint(bool isPopup, Rect dirtyRect, AcceleratedPaintInfo acceleratedPaintInfo)
{
RenderHandler?.OnAcceleratedPaint(isPopup, dirtyRect, acceleratedPaintInfo);
}
/// <inheritdoc />
void IRenderWebBrowser.OnPaint(PaintElementType type, Rect dirtyRect, IntPtr buffer, int width, int height)
{
OnPaint(type == PaintElementType.Popup, dirtyRect, buffer, width, height);
}
/// <summary>
/// Called when an element should be painted. Pixel values passed to this method are scaled relative to view coordinates based on the
/// value of <see cref="ScreenInfo.DeviceScaleFactor"/> returned from <see cref="IRenderWebBrowser.GetScreenInfo"/>. To override the default behaviour