This repository was archived by the owner on May 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 240
Expand file tree
/
Copy pathWebKitBrowserCore.cs
More file actions
1158 lines (1002 loc) · 42.7 KB
/
WebKitBrowserCore.cs
File metadata and controls
1158 lines (1002 loc) · 42.7 KB
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;
using WebKit.Interop;
using WebKit.JSCore;
namespace WebKit
{
public class WebKitBrowserCore : IWebKitBrowser
{
// static variables
private static ActivationContext _activationContext;
private static int _actCtxRefCount;
// private member variables...
private IWebView _webView;
private IntPtr _webViewHwnd;
private IWebKitBrowserHost _webKitBrowserHost;
private WebNotificationObserver _webNotificationObserver;
private WebNotificationCenter _webNotificationCenter;
// Note: we do not provide overridden Equals or GetHashCode methods for the
// WebDownload interface used as a key here - the default implementations should suffice
private readonly Dictionary<WebDownload, WebKitDownload> _downloads = new Dictionary<WebDownload, WebKitDownload>();
private bool _disposed;
// initialisation and property stuff
private bool _loaded; // loaded == true -> webView != null
private string _initialText = "";
private Uri _initialUrl;
private bool _initialAllowNavigation = true;
private bool _initialAllowDownloads = true;
private bool _initialAllowNewWindows = true;
private bool _initialJavaScriptEnabled = true;
private bool _initialLocalStorageEnabled = true;
private bool _initialAllowAnimatedImages = true;
private bool _initialAllowFileAccessFromFileURLs;
private CookieAcceptPolicy _initialCookieAcceptPolicy = CookieAcceptPolicy.Always;
private string _initialLocalStorageDatabaseDirectory = "";
private bool _contextMenuEnabled = true;
private readonly Version _version = Assembly.GetExecutingAssembly().GetName().Version;
private object _scriptObject;
// delegates for WebKit events
private WebFrameLoadDelegate _frameLoadDelegate;
private WebDownloadDelegate _downloadDelegate;
private WebPolicyDelegate _policyDelegate;
private WebUIDelegate _uiDelegate;
private WebResourceLoadDelegate _resourceLoadDelegate;
#region WebKitBrowser events
// public events, roughly the same as in WebBrowser class
// using the null object pattern to avoid null tests
/// <summary>
/// Occurs when the DocumentTitle property value changes.
/// </summary>
public event EventHandler DocumentTitleChanged = delegate { };
/// <summary>
/// Occurs when the WebKitBrowser control finishes loading a document.
/// </summary>
public event WebBrowserDocumentCompletedEventHandler DocumentCompleted = delegate { };
/// <summary>
/// Occurs when the WebKitBrowser control has navigated to a new document and has begun loading it.
/// </summary>
public event WebBrowserNavigatedEventHandler Navigated = delegate { };
/// <summary>
/// Occurs before the WebKitBrowser control navigates to a new document.
/// </summary>
public event WebBrowserNavigatingEventHandler Navigating = delegate { };
/// <summary>
/// Occurs when an error occurs on the current document, or when navigating to a new document.
/// </summary>
public event WebKitBrowserErrorEventHandler Error = delegate { };
/// <summary>
/// Occurs when the WebKitBrowser control begins a file download, before any data has been transferred.
/// </summary>
public event FileDownloadBeginEventHandler DownloadBegin = delegate { };
/// <summary>
/// Occurs when the WebKitBrowser control attempts to open a link in a new window.
/// </summary>
public event NewWindowRequestEventHandler NewWindowRequest = delegate { };
/// <summary>
/// Occurs when the WebKitBrowser control creates a new window.
/// </summary>
public event NewWindowCreatedEventHandler NewWindowCreated = delegate { };
/// <summary>
/// Occures when WebKitBrowser control has begun to provide information on the download progress of a document it is navigating to.
/// </summary>
public event ProgressStartedEventHandler ProgressStarted = delegate { };
/// <summary>
/// Occures when WebKitBrowser control is no longer providing information on the download progress of a document it is navigating to.
/// </summary>
public event ProgressFinishedEventHandler ProgressFinished = delegate { };
/// <summary>
/// Occurs when the WebKitBrowser control has updated information on the download progress of a document it is navigating to.
/// </summary>
public event ProgressChangedEventHandler ProgressChanged = delegate { };
/// <summary>
/// Occurs when JavaScript requests an alert panel to be displayed via the alert() function.
/// </summary>
public event ShowJavaScriptAlertPanelEventHandler ShowJavaScriptAlertPanel = delegate { };
/// <summary>
/// Occurs when JavaScript requests a confirm panel to be displayed via the confirm() function.
/// </summary>
public event ShowJavaScriptConfirmPanelEventHandler ShowJavaScriptConfirmPanel = delegate { };
/// <summary>
/// Occurs when JavaScript requests a prompt panel to be displayed via the prompt() function.
/// </summary>
public event ShowJavaScriptPromptPanelEventHandler ShowJavaScriptPromptPanel = delegate { };
#endregion
private void SetIfLoaded<T>(T Value, ref T InitialValue, Action<T> Setter)
{
if (_loaded)
Setter(Value);
else
InitialValue = Value;
}
private T GetIfLoaded<T>(T InitialValue, Func<T> Getter)
{
if (_loaded)
return Getter();
return InitialValue;
}
#region Public properties
/// <summary>
/// The HTTP Basic Authentication UserName
/// </summary>
public string UserName { get; set; }
/// <summary>
/// The HTTP Basic Authentication Password
/// </summary>
public string Password { private get; set; }
/// <summary>
/// The current print page settings.
/// </summary>
public PageSettings PageSettings { get; set; }
/// <summary>
/// Gets the title of the current document.
/// </summary>
public string DocumentTitle { get; private set; }
/// <summary>
/// Gets or sets the current Url.
/// </summary>
public Uri Url
{
get
{
return GetIfLoaded(_initialUrl, () => {
Uri result;
return Uri.TryCreate(_webView.mainFrame().dataSource().request().url(),
UriKind.Absolute, out result) ? result : null;
});
}
set
{
SetIfLoaded(value, ref _initialUrl, Uri => {
if (Uri != null)
Navigate(Uri.AbsoluteUri);
});
}
}
/// <summary>
/// Gets a value indicating whether a web page is currently being loaded.
/// </summary>
public bool IsBusy
{
get
{
return GetIfLoaded(false, () => _webView.isLoading() > 0);
}
}
/// <summary>
/// Gets or sets the HTML content of the current document.
/// </summary>
public string DocumentText
{
get
{
return GetIfLoaded(_initialText, () => {
try
{
return _webView.mainFrame().dataSource().representation().documentSource();
}
catch (COMException)
{
return "";
}
});
}
set
{
SetIfLoaded(value, ref _initialText,
Text => _webView.mainFrame().loadHTMLString(Text, null));
}
}
/// <summary>
/// Gets the currently selected text.
/// </summary>
public string SelectedText
{
get
{
return GetIfLoaded("", () => _webView.selectedText());
}
}
/// <summary>
/// Gets or sets the application name for the user agent.
/// </summary>
public string ApplicationName
{
get
{
return _webView != null ? _webView.applicationNameForUserAgent() : "";
}
set
{
if (_webView != null)
_webView.setApplicationNameForUserAgent(value);
}
}
/// <summary>
/// Gets or sets the user agent string.
/// </summary>
public string UserAgent
{
get
{
return _webView != null ? _webView.userAgentForURL("") : "";
}
set
{
if (_webView != null)
_webView.setCustomUserAgent(value);
}
}
/// <summary>
/// Gets or sets the text size multiplier (1.0 is normal size).
/// </summary>
public float TextSize
{
get
{
return _webView != null ? _webView.textSizeMultiplier() : 1.0f;
}
set
{
if (_webView != null)
_webView.setTextSizeMultiplier(value);
}
}
/// <summary>
/// Gets or sets whether the control can navigate to another page
/// once it's initial page has loaded.
/// </summary>
public bool AllowNavigation
{
get
{
return GetIfLoaded(_initialAllowNavigation, () => _policyDelegate.AllowNavigation);
}
set
{
SetIfLoaded(value, ref _initialAllowNavigation,
B => _policyDelegate.AllowInitialNavigation = _policyDelegate.AllowNavigation = B);
}
}
/// <summary>
/// Gets or sets whether to allow file downloads.
/// </summary>
public bool AllowDownloads
{
get
{
return GetIfLoaded(_initialAllowDownloads, () => _policyDelegate.AllowDownloads);
}
set
{
SetIfLoaded(value, ref _initialAllowDownloads,
B => _policyDelegate.AllowDownloads = _policyDelegate.AllowDownloads = B);
}
}
/// <summary>
/// Gets or sets whether to allow links to be opened in a new window.
/// </summary>
public bool AllowNewWindows
{
get
{
return GetIfLoaded(_initialAllowNewWindows, () => _policyDelegate.AllowNewWindows);
}
set
{
SetIfLoaded(value, ref _initialAllowNewWindows,
B => _policyDelegate.AllowNewWindows = _policyDelegate.AllowNewWindows = B);
}
}
/// <summary>
/// Gets a value indicating whether a previous page in the navigation history is available.
/// </summary>
public bool CanGoBack
{
get
{
return GetIfLoaded(false, () => _webView.backForwardList().backListCount() > 0);
}
}
/// <summary>
/// Gets a value indicating whether a subsequent page in the navigation history is available.
/// </summary>
public bool CanGoForward
{
get
{
return GetIfLoaded(false, () => _webView.backForwardList().forwardListCount() > 0);
}
}
/// <summary>
/// Gets a Document representing the currently displayed page.
/// </summary>
public DOM.Document Document
{
get
{
return DOM.Document.Create(_webView.mainFrameDocument());
}
}
/// <summary>
/// Gets the current version.
/// </summary>
public Version Version
{
get
{
return _version;
}
}
/// <summary>
/// Gets or sets the scroll offset of the current page, in pixels from the origin.
/// </summary>
public Point ScrollOffset
{
get
{
if (_webView == null)
return Point.Empty;
var v = (IWebViewPrivate) _webView;
return new Point(v.scrollOffset().x, v.scrollOffset().y);
}
set
{
if (_webView == null)
return;
var v = (IWebViewPrivate) _webView;
var p = new tagPOINT();
p.x = value.X - ScrollOffset.X;
p.y = value.Y - ScrollOffset.Y;
v.scrollBy(ref p);
}
}
/// <summary>
/// Gets the visible content rectangle of the current view, in pixels.
/// </summary>
public Rectangle VisibleContent
{
get
{
if (_webView == null)
return Rectangle.Empty;
var v = (IWebViewPrivate)_webView;
var r = v.visibleContentRect();
return new Rectangle(r.left, r.top, (r.right - r.left), (r.bottom - r.top));
}
}
/// <summary>
/// Gets or sets a value indicating whether the context menu of the WebKitBrowser is enabled.
/// </summary>
public bool WebBrowserContextMenuEnabled
{
get { return _contextMenuEnabled; }
set { _contextMenuEnabled = value; }
}
/// <summary>
/// Gets or sets a value indicating whether JavaScript is enabled.
/// </summary>
public bool ScriptingEnabled {
get
{
return GetIfLoaded(_initialJavaScriptEnabled, () => _webView.preferences().isJavaScriptEnabled() != 0);
}
set
{
SetIfLoaded(value, ref _initialJavaScriptEnabled, B => {
var prefs = _webView.preferences();
prefs.setJavaScriptEnabled(B ? 1 : 0);
_webView.setPreferences(prefs);
});
}
}
/// <summary>
/// Gets or sets a value indicating whether LocalStorage is enabled.
/// </summary>
public bool LocalStorageEnabled
{
get
{
return GetIfLoaded(_initialLocalStorageEnabled,
() => ((IWebPreferencesPrivate) _webView.preferences()).localStorageEnabled() != 0);
}
set
{
SetIfLoaded(value, ref _initialLocalStorageEnabled,
B => ((IWebPreferencesPrivate) _webView.preferences()).setLocalStorageEnabled(B ? 1 : 0));
}
}
/// <summary>
/// Gets or sets the fully qualified path to the directory where
/// local storage database files will be stored.
/// </summary>
/// <remarks>Value must be a fully qualified directory path.</remarks>
public string LocalStorageDatabaseDirectory
{
get
{
return GetIfLoaded(_initialLocalStorageDatabaseDirectory,
() => ((IWebPreferencesPrivate) _webView.preferences()).localStorageDatabasePath());
}
set
{
SetIfLoaded(value, ref _initialLocalStorageDatabaseDirectory,
B => {
if (!string.IsNullOrEmpty(B))
((IWebPreferencesPrivate) _webView.preferences()).setLocalStorageDatabasePath(B);
});
}
}
/// <summary>
/// Gets or sets a value indicating whether cross origin requests
/// from file:// URIs to other file:// URIs are allowed.
/// </summary>
public bool AllowFileAccessFromFileURLs
{
get
{
return GetIfLoaded(_initialAllowFileAccessFromFileURLs,
() => ((IWebPreferencesPrivate) _webView.preferences()).allowFileAccessFromFileURLs() != 0);
}
set
{
SetIfLoaded(value, ref _initialAllowFileAccessFromFileURLs,
B => ((IWebPreferencesPrivate) _webView.preferences()).setAllowFileAccessFromFileURLs(B ? 1 : 0));
}
}
/// <summary>
/// Gets or sets a value indicating how cookies are handled.
/// </summary>
public CookieAcceptPolicy CookieAcceptPolicy
{
get
{
return GetIfLoaded(_initialCookieAcceptPolicy,
() => _webView.preferences().cookieStorageAcceptPolicy().ToCookieAcceptPolicy());
}
set
{
SetIfLoaded(value, ref _initialCookieAcceptPolicy,
(Policy) => {
_webView.preferences().setCookieStorageAcceptPolicy(Policy.ToWebKitCookieStorageAcceptPolicy());
((IWebViewPrivate) _webView).setCookieEnabled(Policy == CookieAcceptPolicy.Never ? 0 : 1);
});
}
}
public bool AllowAnimatedImages
{
get
{
return GetIfLoaded(_initialAllowAnimatedImages,
() => _webView.preferences().allowsAnimatedImages() != 0);
}
set
{
SetIfLoaded(value, ref _initialAllowAnimatedImages,
B => _webView.preferences().setAllowsAnimatedImages(B ? 1 : 0));
}
}
public X509Certificate ClientCertificate { get; set; }
/// <summary>
/// Gets the host.
/// </summary>
/// <value>The host.</value>
public IWebKitBrowserHost Host
{
get { return _webKitBrowserHost; }
}
/// <summary>
/// Gets the web view HWND.
/// </summary>
/// <value>The web view HWND.</value>
public IntPtr WebViewHWND
{
get { return _webViewHwnd; }
}
/// <summary>
/// Gets or sets an object that can be accessed by JavaScript contained within the WebKitBrowser control.
/// </summary>
/// <value>The object to be exposed to JavaScript.</value>
public object ObjectForScripting
{
get { return _scriptObject; }
set
{
_scriptObject = value;
CreateWindowScriptObject((JSContext)GetGlobalScriptContext());
}
}
#endregion
#region Constructors / initialization functions
/// <summary>
/// Initializes a new instance of the WebKitBrowser control.
/// </summary>
public WebKitBrowserCore()
{
PageSettings = new PageSettings();
}
/// <summary>
/// Initializes a new instance of the <see cref="WebKitBrowserCore"/> class.
/// </summary>
/// <param name="WebKitBrowserHost">The web kit browser host.</param>
private WebKitBrowserCore(IWebKitBrowserHost WebKitBrowserHost)
{
PageSettings = new PageSettings();
Initialize(WebKitBrowserHost);
}
/// <summary>
/// Initializes the specified host.
/// </summary>
/// <param name="WebKitBrowserHost">The host.</param>
public void Initialize(IWebKitBrowserHost WebKitBrowserHost)
{
if (WebKitBrowserHost == null)
throw new ArgumentNullException("WebKitBrowserHost");
this._webKitBrowserHost = WebKitBrowserHost;
if(!WebKitBrowserHost.InDesignMode)
{
// Control Events
this._webKitBrowserHost.Load += WebKitBrowser_Load;
this._webKitBrowserHost.Resize += WebKitBrowser_Resize;
// If this is the first time the library has been loaded,
// initialize the activation context required to load the
// WebKit COM component registration free
if((_actCtxRefCount++) == 0)
{
var fi = new FileInfo(Assembly.GetExecutingAssembly().Location);
_activationContext = new ActivationContext(Path.Combine(fi.DirectoryName, "WebKitBrowser.dll.manifest"));
_activationContext.Initialize();
// TODO: more error handling here
// Enable OLE for drag and drop functionality - WebKit
// will throw an OutOfMemory exception if we don't...
Application.OleRequired();
}
// If this control is brought to focus, focus our webkit child window
this._webKitBrowserHost.GotFocus += (_, __) => NativeMethods.SetFocus(_webViewHwnd);
_activationContext.Activate();
_webView = new WebViewClass();
_activationContext.Deactivate();
}
}
private void InitializeWebKit()
{
_activationContext.Activate();
_frameLoadDelegate = new WebFrameLoadDelegate();
Marshal.AddRef(Marshal.GetIUnknownForObject(_frameLoadDelegate));
_downloadDelegate = new WebDownloadDelegate();
Marshal.AddRef(Marshal.GetIUnknownForObject(_downloadDelegate));
_policyDelegate = new WebPolicyDelegate(AllowNavigation, AllowDownloads, AllowNewWindows);
Marshal.AddRef(Marshal.GetIUnknownForObject(_policyDelegate));
_uiDelegate = new WebUIDelegate(this);
Marshal.AddRef(Marshal.GetIUnknownForObject(_uiDelegate));
_resourceLoadDelegate = new WebResourceLoadDelegate();
Marshal.AddRef(Marshal.GetIUnknownForObject(_resourceLoadDelegate));
_webNotificationCenter = new WebNotificationCenter();
Marshal.AddRef(Marshal.GetIUnknownForObject(_webNotificationCenter)); // TODO: find out if this is really needed
_webNotificationObserver = new WebNotificationObserver();
_webNotificationCenter.defaultCenter().addObserver(_webNotificationObserver, "WebProgressEstimateChangedNotification", _webView);
_webNotificationCenter.defaultCenter().addObserver(_webNotificationObserver, "WebProgressStartedNotification", _webView);
_webNotificationCenter.defaultCenter().addObserver(_webNotificationObserver, "WebProgressFinishedNotification", _webView);
_webView.setPolicyDelegate(_policyDelegate);
_webView.setFrameLoadDelegate(_frameLoadDelegate);
_webView.setDownloadDelegate(_downloadDelegate);
_webView.setUIDelegate(_uiDelegate);
_webView.setHostWindow(this._webKitBrowserHost.Handle.ToInt32());
//_webView.setResourceLoadDelegate(_resourceLoadDelegate);
var rect = new tagRECT();
rect.top = rect.left = 0;
rect.bottom = this._webKitBrowserHost.Height - 1;
rect.right = this._webKitBrowserHost.Width - 1;
_webView.initWithFrame(rect, null, null);
var webViewPrivate = (IWebViewPrivate)_webView;
_webViewHwnd = (IntPtr)webViewPrivate.viewWindow();
// Subscribe to FrameLoadDelegate events
_frameLoadDelegate.DidRecieveTitle += FrameLoadDelegate_DidRecieveTitle;
_frameLoadDelegate.DidFinishLoadForFrame += FrameLoadDelegate_DidFinishLoadForFrame;
_frameLoadDelegate.DidStartProvisionalLoadForFrame += FrameLoadDelegate_DidStartProvisionalLoadForFrame;
_frameLoadDelegate.DidCommitLoadForFrame += FrameLoadDelegate_DidCommitLoadForFrame;
_frameLoadDelegate.DidFailLoadWithError += FrameLoadDelegate_DidFailLoadWithError;
_frameLoadDelegate.DidFailProvisionalLoadWithError += FrameLoadDelegate_DidFailProvisionalLoadWithError;
_frameLoadDelegate.DidClearWindowObject += FrameLoadDelegate_DidClearWindowObject;
// DownloadDelegate events
_downloadDelegate.DidReceiveResponse += DownloadDelegate_DidReceiveResponse;
_downloadDelegate.DidReceiveDataOfLength += DownloadDelegate_DidReceiveDataOfLength;
_downloadDelegate.DecideDestinationWithSuggestedFilename += DownloadDelegate_DecideDestinationWithSuggestedFilename;
_downloadDelegate.DidBegin += DownloadDelegate_DidBegin;
_downloadDelegate.DidFinish += DownloadDelegate_DidFinish;
_downloadDelegate.DidFailWithError += DownloadDelegate_DidFailWithError;
// UIDelegate events
_uiDelegate.CreateWebViewWithRequest += UIDelegate_CreateWebViewWithRequest;
_uiDelegate.RunJavaScriptAlertPanelWithMessage += UIDelegate_RunJavaScriptAlertPanelWithMessage;
_uiDelegate.RunJavaScriptConfirmPanelWithMessage += UIDelegate_RunJavaScriptConfirmPanelWithMessage;
_uiDelegate.RunJavaScriptTextInputPanelWithPrompt += UIDelegate_RunJavaScriptTextInputPanelWithPrompt;
// Notification events
_webNotificationObserver.OnNotify += webNotificationObserver_OnNotify;
_activationContext.Deactivate();
}
#endregion
#region Control event handers
private void WebKitBrowser_Resize(object Sender, EventArgs Args)
{
// Resize the WebKit control
NativeMethods.MoveWindow(_webViewHwnd, 0, 0, this._webKitBrowserHost.Width - 1, this._webKitBrowserHost.Height - 1, true);
}
private void WebKitBrowser_Load(object Sender, EventArgs Args)
{
// Create the WebKit browser component
InitializeWebKit();
_loaded = _webView != null;
// intialize properties that depend on load
if (_initialUrl != null)
{
Navigate(_initialUrl.AbsoluteUri);
}
else
{
DocumentText = _initialText;
_policyDelegate.AllowInitialNavigation = false;
}
ScriptingEnabled = _initialJavaScriptEnabled;
LocalStorageEnabled = _initialLocalStorageEnabled;
LocalStorageDatabaseDirectory = _initialLocalStorageDatabaseDirectory;
AllowFileAccessFromFileURLs = _initialAllowFileAccessFromFileURLs;
CookieAcceptPolicy = _initialCookieAcceptPolicy;
AllowAnimatedImages = _initialAllowAnimatedImages;
}
// TODO: unused?
/*private void WebKitBrowser_HandleDestroyed(object sender, EventArgs e)
{
_webNotificationCenter.defaultCenter().removeObserver(_webNotificationObserver, "WebProgressEstimateChangedNotification", _webView);
_webNotificationCenter.defaultCenter().removeObserver(_webNotificationObserver, "WebProgressStartedNotification", _webView);
_webNotificationCenter.defaultCenter().removeObserver(_webNotificationObserver, "WebProgressFinishedNotification", _webView);
}*/
#endregion
#region WebFrameLoadDelegate event handlers
private void FrameLoadDelegate_DidCommitLoadForFrame(WebView WebView, IWebFrame Frame)
{
if (Frame == _webView.mainFrame())
{
Navigated(this, new WebBrowserNavigatedEventArgs(Url));
}
}
private void FrameLoadDelegate_DidStartProvisionalLoadForFrame(WebView WebView, IWebFrame Frame)
{
if (Frame == _webView.mainFrame())
{
var url = Frame.provisionalDataSource().request().url();
Navigating(this, new WebBrowserNavigatingEventArgs(new Uri(url), Frame.name()));
}
}
private void FrameLoadDelegate_DidFinishLoadForFrame(WebView WebView, IWebFrame Frame)
{
if (Frame == _webView.mainFrame())
{
_policyDelegate.AllowInitialNavigation = _policyDelegate.AllowNavigation;
DocumentCompleted(this, new WebBrowserDocumentCompletedEventArgs(Url));
}
}
private void FrameLoadDelegate_DidRecieveTitle(WebView WebView, string Title, IWebFrame Frame)
{
if (Frame == _webView.mainFrame())
{
DocumentTitle = Title;
DocumentTitleChanged(this, new EventArgs());
}
}
private void FrameLoadDelegate_DidFailProvisionalLoadWithError(WebView WebView, IWebError WebError, IWebFrame Frame)
{
// ignore an "error" where the page loading is interrupted by a policy change when dowloading a file
if (!(Frame == WebView.mainFrame() && WebError.Domain() == "WebKitErrorDomain" && WebError.code() == 102))
{
Error(this, new WebKitBrowserErrorEventArgs(WebError.localizedDescription()));
}
}
private void FrameLoadDelegate_DidFailLoadWithError(WebView WebView, IWebError WebError, IWebFrame Frame)
{
Error(this, new WebKitBrowserErrorEventArgs(WebError.localizedDescription()));
}
private void FrameLoadDelegate_DidClearWindowObject(WebView WebView, IntPtr Context, IntPtr WindowScriptObject, IWebFrame Frame)
{
CreateWindowScriptObject(new JSContext(Context));
}
#endregion
#region WebDownloadDelegate event handlers
private void DownloadDelegate_DidFailWithError(WebDownload Download, WebError WebError)
{
_downloads[Download].NotifyDidFailWithError(Download, WebError);
}
private void DownloadDelegate_DidFinish(WebDownload Download)
{
_downloads[Download].NotifyDidFinish(Download);
_downloads.Remove(Download);
}
private void DownloadDelegate_DidBegin(WebDownload Download)
{
// create WebKitDownload object to handle this download and notify listeners
var d = new WebKitDownload();
_downloads.Add(Download, d);
var args = new FileDownloadBeginEventArgs(d);
DownloadBegin(this, args);
if (args.Cancel)
d.Cancel();
}
private void DownloadDelegate_DecideDestinationWithSuggestedFilename(WebDownload Download, string FileName)
{
_downloads[Download].NotifyDecideDestinationWithSuggestedFilename(Download, FileName);
}
private void DownloadDelegate_DidReceiveDataOfLength(WebDownload Download, uint Length)
{
// returns false if we cancelled the download at this point
if (!_downloads[Download].NotifyDidReceiveDataOfLength(Download, Length))
_downloads.Remove(Download);
}
private void DownloadDelegate_DidReceiveResponse(WebDownload Download, WebURLResponse Response)
{
_downloads[Download].NotifyDidReceiveResponse(Download, Response);
}
#endregion
#region WebUIDelegate event handlers
private void UIDelegate_CreateWebViewWithRequest(IWebURLRequest Request, out WebView WebView)
{
// TODO: find out why url seems to always be empty:
// https://bugs.webkit.org/show_bug.cgi?id=41441 explains all
string url = (Request == null) ? "" : Request.url();
var args = new NewWindowRequestEventArgs(url);
NewWindowRequest(this, args);
if (!args.Cancel)
{
var b = new WebKitBrowserCore(_webKitBrowserHost);
WebView = (WebView) b._webView;
NewWindowCreated(this, new NewWindowCreatedEventArgs(b));
}
else
{
WebView = null;
}
}
private void UIDelegate_RunJavaScriptAlertPanelWithMessage(WebView Sender, string Message)
{
ShowJavaScriptAlertPanel(this, new ShowJavaScriptAlertPanelEventArgs(Message));
}
private int UIDelegate_RunJavaScriptConfirmPanelWithMessage(WebView Sender, string Message)
{
var args = new ShowJavaScriptConfirmPanelEventArgs(Message);
ShowJavaScriptConfirmPanel(this, args);
return args.ReturnValue ? 1 : 0;
}
private string UIDelegate_RunJavaScriptTextInputPanelWithPrompt(WebView Sender, string Message, string DefaultText)
{
var args = new ShowJavaScriptPromptPanelEventArgs(Message, DefaultText);
ShowJavaScriptPromptPanel(this, args);
return args.ReturnValue;
}
#endregion
#region WebNotificationObserver event handlers
private void webNotificationObserver_OnNotify(IWebNotification Notification)
{
switch (Notification.name())
{
case "WebProgressStartedNotification":
var startedArgs = new EventArgs();
ProgressStarted(this, startedArgs);
break;
case "WebProgressFinishedNotification":
var finishedArgs = new EventArgs();
ProgressFinished(this, finishedArgs);
break;
case "WebProgressEstimateChangedNotification":
var changedArgs = new ProgressChangedEventArgs((int)(_webView.estimatedProgress() * 100), null);
ProgressChanged(this, changedArgs);
break;
}
}
#endregion
#region Public Methods
/// <summary>
/// Navigates to the specified Url.
/// </summary>
/// <param name="NewUrl">Url to navigate to.</param>
public void Navigate(string NewUrl)
{
if (_loaded)
{
// prepend with "http://" if url not well formed
if (!Uri.IsWellFormedUriString(NewUrl, UriKind.Absolute))
NewUrl = "http://" + NewUrl;
_activationContext.Activate();
WebMutableURLRequest request = new WebMutableURLRequestClass();
request.initWithURL(NewUrl, _WebURLRequestCachePolicy.WebURLRequestUseProtocolCachePolicy, 60);
request.setHTTPMethod("GET");
if (ClientCertificate != null)
((IWebMutableURLRequestPrivate) request).setClientCertificate(ClientCertificate.Handle.ToInt32());
//use basic authentication if username and password are supplied.
if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
request.setValue("Basic " + Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(
string.Format("{0}:{1}", UserName, Password))), "Authorization");
_webView.mainFrame().loadRequest((WebURLRequest)request);
_activationContext.Deactivate();
}
else
{
_initialUrl = NewUrl.Length == 0 ? null : new Uri(NewUrl);
}
}
/// <summary>
/// Navigates to the previous page in the page history, if available.
/// </summary>
/// <returns>Success value.</returns>
public bool GoBack()
{
bool retVal = CanGoBack;
_webView.goBack();
return retVal;
}
/// <summary>
/// Navigates to the next page in the page history, if available.
/// </summary>
/// <returns>Success value.</returns>
public bool GoForward()
{
bool retVal = CanGoForward;
_webView.goForward();
return retVal;
}
/// <summary>
/// Reloads the current web page.
/// </summary>
public void Reload()
{
_webView.mainFrame().reload();
}
/// <summary>
/// Reloads the current web page.
/// </summary>
/// <param name="Option">Options for reloading the page.</param>
public void Reload(WebBrowserRefreshOption Option)
{
// TODO: implement
Reload();