-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Copy pathChromiumWebBrowser.cs
2312 lines (2050 loc) · 91.4 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 © 2010-2017 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 CefSharp.Internals;
using CefSharp.Wpf.Internals;
using CefSharp.Wpf.Rendering;
using Microsoft.Win32.SafeHandles;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using CefSharp.ModelBinding;
using System.Runtime.CompilerServices;
namespace CefSharp.Wpf
{
/// <summary>
/// ChromiumWebBrowser is the WPF web browser control
/// </summary>
/// <seealso cref="System.Windows.Controls.ContentControl" />
/// <seealso cref="CefSharp.Internals.IRenderWebBrowser" />
/// <seealso cref="CefSharp.Wpf.IWpfWebBrowser" />
public class ChromiumWebBrowser : ContentControl, IRenderWebBrowser, IWpfWebBrowser
{
/// <summary>
/// The source
/// </summary>
private HwndSource source;
/// <summary>
/// The source hook
/// </summary>
private HwndSourceHook sourceHook;
/// <summary>
/// The tooltip timer
/// </summary>
private DispatcherTimer tooltipTimer;
/// <summary>
/// The tool tip
/// </summary>
private ToolTip toolTip;
/// <summary>
/// The managed cef browser adapter
/// </summary>
private ManagedCefBrowserAdapter managedCefBrowserAdapter;
/// <summary>
/// The ignore URI change
/// </summary>
private bool ignoreUriChange;
/// <summary>
/// The browser created
/// </summary>
private bool browserCreated;
/// <summary>
/// The browser initialized - boolean represented as 0 (false) and 1(true) as we use Interlocker to increment/reset
/// </summary>
private int browserInitialized;
/// <summary>
/// The image that represents this browser instances
/// </summary>
private Image image;
/// <summary>
/// The popup image
/// </summary>
private Image popupImage;
/// <summary>
/// The popup
/// </summary>
private Popup popup;
/// <summary>
/// The browser
/// </summary>
private IBrowser browser;
/// <summary>
/// The dispose count
/// </summary>
private int disposeCount;
/// <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>
/// A flag that indicates whether or not the designer is active
/// NOTE: Needs to be static for OnApplicationExit
/// </summary>
private static bool designMode;
/// <summary>
/// Gets or sets the browser settings.
/// </summary>
/// <value>The browser settings.</value>
public BrowserSettings BrowserSettings { get; set; }
/// <summary>
/// Gets or sets the request context.
/// </summary>
/// <value>The request context.</value>
public RequestContext RequestContext { get; set; }
/// <summary>
/// Implement <see cref="IDialogHandler" /> and assign to handle dialog events.
/// </summary>
/// <value>The dialog handler.</value>
public IDialogHandler DialogHandler { get; set; }
/// <summary>
/// Implement <see cref="IJsDialogHandler" /> and assign to handle events related to JavaScript Dialogs.
/// </summary>
/// <value>The js dialog handler.</value>
public IJsDialogHandler JsDialogHandler { get; set; }
/// <summary>
/// Implement <see cref="IKeyboardHandler" /> and assign to handle events related to key press.
/// </summary>
/// <value>The keyboard handler.</value>
public IKeyboardHandler KeyboardHandler { get; set; }
/// <summary>
/// Implement <see cref="IRequestHandler" /> and assign to handle events related to browser requests.
/// </summary>
/// <value>The request handler.</value>
public IRequestHandler RequestHandler { get; set; }
/// <summary>
/// Implement <see cref="IDownloadHandler" /> and assign to handle events related to downloading files.
/// </summary>
/// <value>The download handler.</value>
public IDownloadHandler DownloadHandler { get; set; }
/// <summary>
/// Implement <see cref="ILoadHandler" /> and assign to handle events related to browser load status.
/// </summary>
/// <value>The load handler.</value>
public ILoadHandler LoadHandler { get; set; }
/// <summary>
/// Implement <see cref="ILifeSpanHandler" /> and assign to handle events related to popups.
/// </summary>
/// <value>The life span handler.</value>
public ILifeSpanHandler LifeSpanHandler { get; set; }
/// <summary>
/// Implement <see cref="IDisplayHandler" /> and assign to handle events related to browser display state.
/// </summary>
/// <value>The display handler.</value>
public IDisplayHandler DisplayHandler { get; set; }
/// <summary>
/// Implement <see cref="IContextMenuHandler" /> and assign to handle events related to the browser context menu
/// </summary>
/// <value>The menu handler.</value>
public IContextMenuHandler MenuHandler { get; set; }
/// <summary>
/// Implement <see cref="IFocusHandler" /> and assign to handle events related to the browser component's focus
/// </summary>
/// <value>The focus handler.</value>
public IFocusHandler FocusHandler { get; set; }
/// <summary>
/// Implement <see cref="IDragHandler" /> and assign to handle events related to dragging.
/// </summary>
/// <value>The drag handler.</value>
public IDragHandler DragHandler { get; set; }
/// <summary>
/// Implement <see cref="IResourceHandlerFactory" /> and control the loading of resources
/// </summary>
/// <value>The resource handler factory.</value>
public IResourceHandlerFactory ResourceHandlerFactory { get; set; }
/// <summary>
/// Implement <see cref="IGeolocationHandler" /> and assign to handle requests for permission to use geolocation.
/// </summary>
/// <value>The geolocation handler.</value>
public IGeolocationHandler GeolocationHandler { get; set; }
/// <summary>
/// Gets or sets the bitmap factory.
/// </summary>
/// <value>The bitmap factory.</value>
public IBitmapFactory BitmapFactory { get; set; }
/// <summary>
/// Implement <see cref="IRenderProcessMessageHandler" /> and assign to handle messages from the render process.
/// </summary>
/// <value>The render process message handler.</value>
public IRenderProcessMessageHandler RenderProcessMessageHandler { get; set; }
/// <summary>
/// Implement <see cref="IFindHandler" /> to handle events related to find results.
/// </summary>
/// <value>The find handler.</value>
public IFindHandler FindHandler { get; set; }
/// <summary>
/// Event handler for receiving Javascript console messages being sent from web pages.
/// 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. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang..
/// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread.
/// (The exception to this is when your running with settings.MultiThreadedMessageLoop = false, then they'll be the same thread).
/// </summary>
public event EventHandler<ConsoleMessageEventArgs> ConsoleMessage;
/// <summary>
/// Event handler for changes to the status message.
/// 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. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang.
/// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread.
/// (The exception to this is when your running with settings.MultiThreadedMessageLoop = false, then they'll be the same thread).
/// </summary>
public event EventHandler<StatusMessageEventArgs> StatusMessage;
/// <summary>
/// Event handler that will get called when the browser begins loading a frame. Multiple frames may be loading at the same
/// time. Sub-frames may start or continue loading after the main frame load has ended. This method may not be called for a
/// particular frame if the load request for that frame fails. For notification of overall browser load status use
/// OnLoadingStateChange instead.
/// 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. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang..
/// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread.
/// </summary>
/// <remarks>Whilst this may seem like a logical place to execute js, it's called before the DOM has been loaded, implement
/// <see cref="IRenderProcessMessageHandler.OnContextCreated" /> as it's called when the underlying V8Context is created
/// (Only called for the main frame at this stage)</remarks>
public event EventHandler<FrameLoadStartEventArgs> FrameLoadStart;
/// <summary>
/// Event handler that will get called when the browser is done loading a frame. Multiple frames may be loading at the same
/// time. Sub-frames may start or continue loading after the main frame load has ended. This method will always be called
/// for all frames irrespective of whether the request completes successfully.
/// 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. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang..
/// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread.
/// </summary>
public event EventHandler<FrameLoadEndEventArgs> FrameLoadEnd;
/// <summary>
/// Event handler that will get called when the resource load for a navigation fails or is canceled.
/// 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. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang..
/// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread.
/// </summary>
public event EventHandler<LoadErrorEventArgs> LoadError;
/// <summary>
/// Event handler that will get called when the Loading state has changed.
/// This event will be fired twice. Once when loading is initiated either programmatically or
/// by user action, and once when loading is terminated due to completion, cancellation of failure.
/// 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. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang..
/// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread.
/// </summary>
public event EventHandler<LoadingStateChangedEventArgs> LoadingStateChanged;
/// <summary>
/// Raised before each render cycle, and allows you to adjust the bitmap before it's rendered/applied
/// </summary>
public event EventHandler<RenderingEventArgs> Rendering;
/// <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; }
/// <summary>
/// A flag that indicates if you can execute javascript in the main frame.
/// Flag is set to true in IRenderProcessMessageHandler.OnContextCreated.
/// and false in IRenderProcessMessageHandler.OnContextReleased
/// </summary>
public bool CanExecuteJavascriptInMainFrame { 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 double DpiScaleFactor { get; set; }
/// <summary>
/// Initializes static members of the <see cref="ChromiumWebBrowser"/> class.
/// </summary>
static ChromiumWebBrowser()
{
if (CefSharpSettings.ShutdownOnExit)
{
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>
/// 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 subsiquently throw an exception.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private void NoInliningConstructor()
{
//Initialize CEF if it hasn't already been initialized
if (!Cef.IsInitialized && !Cef.Initialize())
{
throw new InvalidOperationException("Cef::Initialize() failed");
}
BitmapFactory = new BitmapFactory();
//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);
managedCefBrowserAdapter = new ManagedCefBrowserAdapter(this, true);
ResourceHandlerFactory = new DefaultResourceHandlerFactory();
BrowserSettings = new BrowserSettings();
PresentationSource.AddSourceChangedHandler(this, PresentationSourceChangedHandler);
RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.HighQuality);
}
/// <summary>
/// Finalizes an instance of the <see cref="ChromiumWebBrowser"/> class.
/// </summary>
~ChromiumWebBrowser()
{
if (!designMode)
{
Dispose(false);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (!designMode)
{
Dispose(true);
}
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="isDisposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
// This method cannot be inlined as the designer will attempt to load libcef.dll and will subsiquently throw an exception.
[MethodImpl(MethodImplOptions.NoInlining)]
protected virtual void Dispose(bool isDisposing)
{
//If disposeCount is 0 then we'll update it to 1 and begin disposing
if (Interlocked.CompareExchange(ref disposeCount, 1, 0) == 0)
{
// No longer reference event listeners:
ConsoleMessage = null;
FrameLoadStart = null;
FrameLoadEnd = null;
LoadError = null;
LoadingStateChanged = null;
Rendering = null;
if (isDisposing)
{
browser = null;
if (BrowserSettings != null)
{
BrowserSettings.Dispose();
BrowserSettings = null;
}
PresentationSource.RemoveSourceChangedHandler(this, PresentationSourceChangedHandler);
// 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(popup != null)
{
popup.Opened -= PopupOpened;
popup.Closed -= PopupClosed;
popup = null;
}
if (tooltipTimer != null)
{
tooltipTimer.Tick -= OnTooltipTimerTick;
tooltipTimer.Stop();
tooltipTimer = null;
}
if (CleanupElement != null)
{
CleanupElement.Unloaded -= OnCleanupElementUnloaded;
}
if(managedCefBrowserAdapter != null)
{
managedCefBrowserAdapter.Dispose();
managedCefBrowserAdapter = null;
}
Interlocked.Exchange(ref browserInitialized, 0);
UiThreadRunAsync(() =>
{
SetCurrentValue(IsBrowserInitializedProperty, false);
WebBrowser = null;
});
}
// Release reference to handlers, make sure this is done after we dispose managedCefBrowserAdapter
// otherwise the ILifeSpanHandler.DoClose will not be invoked. (More important in the WinForms version,
// we do it here for consistency)
this.SetHandlersToNull();
Cef.RemoveDisposable(this);
RemoveSourceHook();
}
}
/// <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()
{
var screenInfo = new ScreenInfo(scaleFactor: (float)DpiScaleFactor);
return screenInfo;
}
/// <summary>
/// Gets the view rect (width, height)
/// </summary>
/// <returns>ViewRect.</returns>
ViewRect IRenderWebBrowser.GetViewRect()
{
return GetViewRect();
}
/// <summary>
/// Gets the view rect (width, height)
/// </summary>
/// <returns>ViewRect.</returns>
protected virtual ViewRect GetViewRect()
{
var viewRect = new ViewRect((int)Math.Ceiling(ActualWidth), (int)Math.Ceiling(ActualHeight));
return viewRect;
}
bool IRenderWebBrowser.GetScreenPoint(int viewX, int viewY, out int screenX, out int screenY)
{
screenX = 0;
screenY = 0;
//We manually claculate 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;
}
/// <summary>
/// Creates the BitmapInfo instance used for rendering. Two instances
/// will be created, one will be used for the popup
/// </summary>
/// <param name="isPopup">if set to <c>true</c> [is popup].</param>
/// <returns>BitmapInfo.</returns>
/// <exception cref="System.Exception">BitmapFactory cannot be null</exception>
BitmapInfo IRenderWebBrowser.CreateBitmapInfo(bool isPopup)
{
return CreateBitmapInfo(isPopup);
}
/// <summary>
/// Creates the BitmapInfo instance used for rendering. Two instances
/// will be created, one will be used for the popup
/// </summary>
/// <param name="isPopup">if set to <c>true</c> [is popup].</param>
/// <returns>BitmapInfo.</returns>
/// <exception cref="System.Exception">BitmapFactory cannot be null</exception>
protected virtual BitmapInfo CreateBitmapInfo(bool isPopup)
{
if (BitmapFactory == null)
{
throw new Exception("BitmapFactory cannot be null");
}
return BitmapFactory.CreateBitmap(isPopup, DpiScaleFactor);
}
/// <summary>
/// Starts the dragging.
/// </summary>
/// <param name="dragData">The drag data.</param>
/// <param name="mask">The mask.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
bool IRenderWebBrowser.StartDragging(IDragData dragData, DragOperationsMask mask, 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);
// 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)
{
var results = DragDrop.DoDragDrop(this, dataObject, GetDragEffects(mask));
browser.GetHost().DragSourceEndedAt(0, 0, GetDragOperationsMask(results));
browser.GetHost().DragSourceSystemDragEnded();
}
});
return true;
}
void IRenderWebBrowser.UpdateDragCursor(DragOperationsMask operation)
{
//TODO: Someone should implement this
}
/// <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
/// ScreenInfo.DeviceScaleFactor returned from GetScreenInfo. bitmapInfo.IsPopup indicates whether the element is the view
/// or the popup widget. BitmapInfo.DirtyRect contains the set of rectangles in pixel coordinates that need to be
/// repainted. The bitmap will be will be width * height *4 bytes in size and represents a BGRA image with an upper-left origin.
/// The underlying buffer is copied into the back buffer and is accessible via BackBufferHandle
/// </summary>
/// <param name="bitmapInfo">information about the bitmap to be rendered</param>
void IRenderWebBrowser.OnPaint(BitmapInfo bitmapInfo)
{
OnPaint(bitmapInfo);
}
/// <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
/// ScreenInfo.DeviceScaleFactor returned from GetScreenInfo. bitmapInfo.IsPopup indicates whether the element is the view
/// or the popup widget. BitmapInfo.DirtyRect contains the set of rectangles in pixel coordinates that need to be
/// repainted. The bitmap will be will be width * height *4 bytes in size and represents a BGRA image with an upper-left origin.
/// The underlying buffer is copied into the back buffer and is accessible via BackBufferHandle
/// </summary>
/// <param name="bitmapInfo">information about the bitmap to be rendered</param>
protected virtual void OnPaint(BitmapInfo bitmapInfo)
{
UiThreadRunAsync(delegate
{
lock (bitmapInfo.BitmapLock)
{
var wpfBitmapInfo = (WpfBitmapInfo)bitmapInfo;
// Inform parents that the browser rendering is updating
OnRendering(this, wpfBitmapInfo);
// Now update the WPF image
if (wpfBitmapInfo.CreateNewBitmap)
{
var img = bitmapInfo.IsPopup ? popupImage : image;
img.Source = null;
GC.Collect(1);
img.Source = wpfBitmapInfo.CreateBitmap();
}
wpfBitmapInfo.Invalidate();
}
},
DispatcherPriority.Render);
}
/// <summary>
/// Sets the popup size and position.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
void IRenderWebBrowser.SetPopupSizeAndPosition(int width, int height, int x, int y)
{
UiThreadRunAsync(() => SetPopupSizeAndPositionImpl(width, height, x, y));
}
/// <summary>
/// Sets the popup is open.
/// </summary>
/// <param name="isOpen">if set to <c>true</c> [is open].</param>
void IRenderWebBrowser.SetPopupIsOpen(bool isOpen)
{
UiThreadRunAsync(() => { popup.IsOpen = isOpen; });
}
/// <summary>
/// Sets the cursor.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="type">The type.</param>
void IRenderWebBrowser.SetCursor(IntPtr handle, CursorType type)
{
//Custom cursors are handled differently, for now keep standard ones executing
//in an async fashion
if (type == CursorType.Custom)
{
//When using a custom it appears we need to update the cursor in a sync fashion
//Likely the underlying handle/buffer is being released before the cursor
// is created when executed in an async fashion. Doesn't seem to be a problem
//for build in cursor types
UiThreadRunSync(() =>
{
Cursor = CursorInteropHelper.Create(new SafeFileHandle(handle, ownsHandle: false));
});
}
else
{
UiThreadRunAsync(() =>
{
Cursor = CursorInteropHelper.Create(new SafeFileHandle(handle, ownsHandle: false));
});
}
}
void IRenderWebBrowser.OnImeCompositionRangeChanged(Range selectedRange, Rect[] characterBounds)
{
//TODO: Implement this
}
/// <summary>
/// Sets the address.
/// </summary>
/// <param name="args">The <see cref="AddressChangedEventArgs"/> instance containing the event data.</param>
void IWebBrowserInternal.SetAddress(AddressChangedEventArgs args)
{
UiThreadRunAsync(() =>
{
ignoreUriChange = true;
SetCurrentValue(AddressProperty, args.Address);
ignoreUriChange = false;
// The tooltip should obviously also be reset (and hidden) when the address changes.
SetCurrentValue(TooltipTextProperty, null);
});
}
/// <summary>
/// Sets the loading state change.
/// </summary>
/// <param name="args">The <see cref="LoadingStateChangedEventArgs"/> instance containing the event data.</param>
void IWebBrowserInternal.SetLoadingStateChange(LoadingStateChangedEventArgs args)
{
UiThreadRunAsync(() =>
{
SetCurrentValue(CanGoBackProperty, args.CanGoBack);
SetCurrentValue(CanGoForwardProperty, args.CanGoForward);
SetCurrentValue(IsLoadingProperty, args.IsLoading);
((DelegateCommand)BackCommand).RaiseCanExecuteChanged();
((DelegateCommand)ForwardCommand).RaiseCanExecuteChanged();
((DelegateCommand)ReloadCommand).RaiseCanExecuteChanged();
});
var handler = LoadingStateChanged;
if (handler != null)
{
handler(this, args);
}
}
/// <summary>
/// Sets the title.
/// </summary>
/// <param name="args">The <see cref="TitleChangedEventArgs"/> instance containing the event data.</param>
void IWebBrowserInternal.SetTitle(TitleChangedEventArgs args)
{
UiThreadRunAsync(() => SetCurrentValue(TitleProperty, args.Title));
}
/// <summary>
/// Sets the tooltip text.
/// </summary>
/// <param name="tooltipText">The tooltip text.</param>
void IWebBrowserInternal.SetTooltipText(string tooltipText)
{
UiThreadRunAsync(() => SetCurrentValue(TooltipTextProperty, tooltipText));
}
/// <summary>
/// Handles the <see cref="E:FrameLoadStart" /> event.
/// </summary>
/// <param name="args">The <see cref="FrameLoadStartEventArgs"/> instance containing the event data.</param>
void IWebBrowserInternal.OnFrameLoadStart(FrameLoadStartEventArgs args)
{
var handler = FrameLoadStart;
if (handler != null)
{
handler(this, args);
}
}
/// <summary>
/// Handles the <see cref="E:FrameLoadEnd" /> event.
/// </summary>
/// <param name="args">The <see cref="FrameLoadEndEventArgs"/> instance containing the event data.</param>
void IWebBrowserInternal.OnFrameLoadEnd(FrameLoadEndEventArgs args)
{
var handler = FrameLoadEnd;
if (handler != null)
{
handler(this, args);
}
}
/// <summary>
/// Handles the <see cref="E:ConsoleMessage" /> event.
/// </summary>
/// <param name="args">The <see cref="ConsoleMessageEventArgs"/> instance containing the event data.</param>
void IWebBrowserInternal.OnConsoleMessage(ConsoleMessageEventArgs args)
{
var handler = ConsoleMessage;
if (handler != null)
{
handler(this, args);
}
}
/// <summary>
/// Handles the <see cref="E:StatusMessage" /> event.
/// </summary>
/// <param name="args">The <see cref="StatusMessageEventArgs"/> instance containing the event data.</param>
void IWebBrowserInternal.OnStatusMessage(StatusMessageEventArgs args)
{
var handler = StatusMessage;
if (handler != null)
{
handler(this, args);
}
}
/// <summary>
/// Handles the <see cref="E:LoadError" /> event.
/// </summary>
/// <param name="args">The <see cref="LoadErrorEventArgs"/> instance containing the event data.</param>
void IWebBrowserInternal.OnLoadError(LoadErrorEventArgs args)
{
var handler = LoadError;
if (handler != null)
{
handler(this, args);
}
}
void IWebBrowserInternal.SetCanExecuteJavascriptOnMainFrame(bool canExecute)
{
CanExecuteJavascriptInMainFrame = canExecute;
}
/// <summary>
/// Gets the browser adapter.
/// </summary>
/// <value>The browser adapter.</value>
IBrowserAdapter IWebBrowserInternal.BrowserAdapter
{
get { return managedCefBrowserAdapter; }
}
/// <summary>
/// Gets or sets a value indicating whether this instance has parent.
/// </summary>
/// <value><c>true</c> if this instance has parent; otherwise, <c>false</c>.</value>
bool IWebBrowserInternal.HasParent { get; set; }
/// <summary>
/// Called when [after browser created].
/// </summary>
/// <param name="browser">The browser.</param>
void IWebBrowserInternal.OnAfterBrowserCreated(IBrowser browser)
{
Interlocked.Exchange(ref browserInitialized, 1);
this.browser = browser;
UiThreadRunAsync(() =>
{
if (!IsDisposed)
{
SetCurrentValue(IsBrowserInitializedProperty, true);
// If Address was previously set, only now can we actually do the load
if (!string.IsNullOrEmpty(Address))
{
Load(Address);
}
}
});
}
#region CanGoBack dependency property
/// <summary>
/// A flag that indicates whether the state of the control current supports the GoBack action (true) or not (false).
/// </summary>
/// <value><c>true</c> if this instance can go back; otherwise, <c>false</c>.</value>
/// <remarks>In the WPF control, this property is implemented as a Dependency Property and fully supports data
/// binding.</remarks>
public bool CanGoBack
{
get { return (bool)GetValue(CanGoBackProperty); }
}
/// <summary>
/// The can go back property
/// </summary>
public static DependencyProperty CanGoBackProperty = DependencyProperty.Register("CanGoBack", typeof(bool), typeof(ChromiumWebBrowser));
#endregion
#region CanGoForward dependency property
/// <summary>
/// A flag that indicates whether the state of the control currently supports the GoForward action (true) or not (false).
/// </summary>
/// <value><c>true</c> if this instance can go forward; otherwise, <c>false</c>.</value>