-
Notifications
You must be signed in to change notification settings - Fork 1
/
HtmlViewer.xaml.cs
483 lines (379 loc) · 15.1 KB
/
HtmlViewer.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
using DarkHelpers;
using DarkHelpers.Commands;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace DarkHtmlViewer
{
public partial class HtmlViewer : UserControl
{
private readonly ILogger<HtmlViewer> _logger;
private readonly Guid _instanceId;
private readonly DarkHtmlTempFileManager _fileManager;
#region Bindable properties
public string HtmlContent
{
get => (string)GetValue(HtmlContentProperty);
set => SetValue(HtmlContentProperty, value);
}
public static readonly DependencyProperty HtmlContentProperty =
DependencyProperty.Register(
nameof(HtmlContent),
typeof(string),
typeof(HtmlViewer),
new PropertyMetadata(
string.Empty,
new PropertyChangedCallback(OnHtmlContentCallBack)));
public ICommand LinkClickedCommand
{
get => (ICommand)GetValue(LinkClickedCommandProperty);
set => SetValue(LinkClickedCommandProperty, value);
}
public static readonly DependencyProperty LinkClickedCommandProperty =
DependencyProperty.Register(
nameof(LinkClickedCommand),
typeof(ICommand),
typeof(HtmlViewer),
new PropertyMetadata(null));
#endregion
#region Commands
public ICommand LoadCommand => new DarkCommand<string>(Load);
public ICommand ScrollCommand => new DarkAsyncCommand<string>(ScrollAsync);
public ICommand ScrollOnNextLoadCommand => new DarkCommand<string>(ScrollOnNextLoad);
public ICommand SaveScrollPositionForNextLoadCommand => new DarkAsyncCommand(SaveScrollPositionForNextLoadAsync);
public ICommand SearchCommand => new DarkAsyncCommand<string>(SearchAsync);
public ICommand SearchOnNextLoadCommand => new DarkCommand<string>(SearchOnNextLoad);
public ICommand PrintCommand => new DarkAsyncCommand(PrintAsync);
public ICommand ZoomCommand => new DarkCommand<double>(Zoom);
#endregion
public HtmlViewer()
{
InitializeComponent();
_instanceId = Guid.NewGuid();
_fileManager = new DarkHtmlTempFileManager(_instanceId, GetLogger<DarkHtmlTempFileManager>());
_logger = GetLogger<HtmlViewer>();
_logger.LogDebug("DarkHtmlViewer-{InstanceId}: Initializing", _instanceId);
InitializeWebView2();
}
#region Initialization
private bool _initialized;
private string _loadAfterInitialization = null;
private async void InitializeWebView2()
{
var initFilePath = _fileManager.GetFilePath();
_logger.LogDebug("DarkHtmlViewer-{InstanceId}: {Method}, init file: {InitFile}", _instanceId, nameof(InitializeWebView2), initFilePath);
webView2.CoreWebView2InitializationCompleted += WebView2_CoreWebView2InitializationCompleted;
webView2.NavigationStarting += WebView2_NavigationStarting;
webView2.NavigationCompleted += WebView2_NavigationCompleted;
var appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
var dataFolder = Path.Combine(appDataDir, "webView2_env");
var env = await CoreWebView2Environment.CreateAsync(null, dataFolder);
await webView2.EnsureCoreWebView2Async(env);
SetWebViewSource(initFilePath);
webView2.Visibility = Visibility.Visible;
_initialized = true;
LoadQeuedContentIfAny();
}
private void SetWebViewSource(string uri)
{
webView2.CoreWebView2?.Navigate(uri);
}
private void LoadQeuedContentIfAny()
{
if (_loadAfterInitialization is null)
{
return;
}
Load(_loadAfterInitialization);
}
private void WebView2_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
_logger.LogDebug("DarkHtmlViewer-{InstanceId}: {Method}", _instanceId, nameof(WebView2_CoreWebView2InitializationCompleted));
DisableAllExtraFunctionality(webView2.CoreWebView2.Settings);
SetupVirtualHostForAssets(webView2);
}
#endregion
#region Loading HTML content
private static void OnHtmlContentCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var viewer = sender as HtmlViewer;
if (viewer != null)
{
viewer.Load(e.NewValue?.ToString());
}
}
/// <summary>
/// Loads an HTML string
/// </summary>
public void Load(string html)
{
if (_initialized is false)
{
_loadAfterInitialization = html;
return;
}
_fileManager.Create(html);
var htmlFilePath = _fileManager.GetFilePath();
_logger.LogDebug("DarkHtmlViewer-{InstanceId}: {Method}, file: {HtmlFilePath}", _instanceId, nameof(Load), htmlFilePath);
SetWebViewSource(htmlFilePath);
}
#endregion
#region Navigation
private void WebView2_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
{
var linkName = Path.GetFileName(e.Uri);
var isTempFileName = _fileManager.IsTempFilePath(linkName);
if (isTempFileName)
{
return;
}
e.Cancel = true;
TriggerLinkClicked(linkName);
}
private void TriggerLinkClicked(string link)
{
LinkClickedCommand?.TryExecute(link);
}
private async void WebView2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
if (_scrollToNext is not null)
{
await ScrollAsync(_scrollToNext);
_scrollToNext = null;
}
else if(_scrollPositionXNext is not null)
{
await ScrollAsync(_scrollPositionXNext, _scrollPositionYNext);
_scrollPositionXNext = null;
_scrollPositionYNext = null;
}
if (_textToFind is not null)
{
await SearchAsync(_textToFind);
_textToFind = null;
}
}
#endregion
#region Scroll to
private string _scrollToNext = null;
/// <summary>
/// Tries to scroll to an element by ID
/// </summary>
public async Task ScrollAsync(string elementId)
{
var script = $"document.getElementById(\"{elementId}\").scrollIntoView();";
await webView2.ExecuteScriptAsync(script);
}
/// <summary>
/// Tries to scroll to a position
/// </summary>
private async Task ScrollAsync(string x, string y)
{
var script = $"window.scrollTo({x}, {y});";
await webView2.ExecuteScriptAsync(script);
}
/// <summary>
/// Sets the elementId to be scrolled to next time HTML content is loaded
/// </summary>
public void ScrollOnNextLoad(string elementId)
{
_scrollToNext = elementId;
}
#endregion
#region Save scroll position
private string _scrollPositionXNext = null;
private string _scrollPositionYNext = null;
/// <summary>
/// Saves the current scroll position and tries to restore it next time HTML content is loaded
/// <para>If <see cref="ScrollOnNextLoad"/> is used as well, this will be ignored</para>
/// </summary>
public async Task SaveScrollPositionForNextLoadAsync()
{
_scrollPositionXNext = await webView2.ExecuteScriptAsync("window.scrollX");
_scrollPositionYNext = await webView2.ExecuteScriptAsync("window.scrollY");
}
#endregion
#region Search
private string _textToFind = null;
/// <summary>
/// Finds text in the loaded HTML
/// </summary>
public async Task SearchAsync(string text)
{
var clean = CleanSearchText(text);
if (string.IsNullOrEmpty(clean))
{
return;
}
//TODO try to find a way to highlight all occurances instead of just the first one
var script = $"window.find('{clean}');";
await webView2.ExecuteScriptAsync(script);
}
private string CleanSearchText(string text)
{
if (string.IsNullOrEmpty(text))
{
return null;
}
var clean = text.Replace("'", "");
if (string.IsNullOrEmpty(clean))
{
return null;
}
return clean;
}
/// <summary>
/// Sets the text to be searched for next time HTML content is loaded
/// </summary>
public void SearchOnNextLoad(string text)
{
_textToFind = text;
}
#endregion
#region Printing
/// <summary>
/// Invokes the browser print dialog
/// </summary>
public async Task PrintAsync()
{
var script = "window.print();";
await webView2.ExecuteScriptAsync(script);
}
#endregion
#region Zoom
/// <summary>
/// Sets the zoom factor of the browser
/// </summary>
/// <param name="zoom">Zoom factor, 1.0 is default</param>
public void Zoom(double zoom)
{
webView2.ZoomFactor = zoom;
}
#endregion
#region Virtual host
private static VirtualHostNameToFolderMappingSettingsValidator _virtualAssetSettingsValidator;
private static VirtualHostNameToFolderMappingSettings VirtualAssetSettings;
/// <summary>
/// Configure the virtual host to folder mapping
/// </summary>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="VirtualHostNameToFolderMappingSettingsException"></exception>
public static void ConfigureVirtualHostNameToFolderMappingSettings(VirtualHostNameToFolderMappingSettings settings)
{
if (settings is null)
{
throw new ArgumentNullException(nameof(settings));
}
var validator = _virtualAssetSettingsValidator ??= new VirtualHostNameToFolderMappingSettingsValidator();
var validationResult = validator.Validate(settings);
if (!validationResult.IsValid)
{
var firstError = validationResult.Errors.FirstOrDefault();
throw new VirtualHostNameToFolderMappingSettingsException(firstError.PropertyName, firstError.ErrorMessage);
}
VirtualAssetSettings = settings;
}
private static void SetupVirtualHostForAssets(WebView2 webView)
{
if (VirtualAssetSettings is null)
{
return;
}
if (VirtualAssetSettings.IsEnabled is false)
{
return;
}
webView.CoreWebView2.SetVirtualHostNameToFolderMapping(VirtualAssetSettings.Hostname, VirtualAssetSettings.FolderPath, VirtualAssetSettings.AccessKind);
}
#endregion
#region Browser settings
private static void DisableAllExtraFunctionality(CoreWebView2Settings settings)
{
settings.AreBrowserAcceleratorKeysEnabled = true;
settings.AreDefaultContextMenusEnabled = false;
settings.AreDefaultScriptDialogsEnabled = false;
settings.AreDevToolsEnabled = false;
settings.IsScriptEnabled = false;
settings.IsStatusBarEnabled = false;
settings.IsWebMessageEnabled = false;
settings.IsZoomControlEnabled = false;
settings.IsBuiltInErrorPageEnabled = false;
settings.IsGeneralAutofillEnabled = false;
settings.IsPasswordAutosaveEnabled = false;
settings.IsSwipeNavigationEnabled = false;
}
#endregion
#region Logging
private static Func<ILoggerFactory> LoggerFactoryProvider;
public static void ConfigureLogger(Func<ILoggerFactory> loggerFactoryProvider)
{
LoggerFactoryProvider = loggerFactoryProvider;
}
private static ILogger<T> GetLogger<T>()
{
if (LoggerFactoryProvider is null)
{
return NullLogger<T>.Instance;
}
return LoggerFactoryProvider.Invoke().CreateLogger<T>();
}
#endregion
#region Cleanup
/// <summary>
/// Removes the temporary files created by the control
/// </summary>
public void Cleanup()
{
_fileManager.TryDeleteCurrentTempFile();
}
#endregion
#region Utils
/// <summary>
/// <para>Check installed runtime compatibility - basic</para>
/// <para>Tries to retreive the available browser version</para>
/// <para>Throws if there's a problem</para>
/// </summary>
/// <exception cref="WebView2RuntimeNotFoundException" />
public static void CheckBasicCompatibility()
{
_ = CoreWebView2Environment.GetAvailableBrowserVersionString();
}
/// <summary>
/// <para>Check installed runtime compatibility - full</para>
/// <para>Tries to create an instance of a <see cref="WebView2"/> with valid <see cref="CoreWebView2Environment"/>, <see cref="CoreWebView2Settings"/> and <see cref="VirtualHostNameToFolderMappingSettings"/> (if enabled)</para>
/// <para>Throws if there's a problem</para>
/// </summary>
/// <exception cref="Exception" />
/// <exception cref="ArgumentException" />
/// <exception cref="InvalidOperationException" />
/// <exception cref="ObjectDisposedException" />
/// <exception cref="WebView2RuntimeNotFoundException" />
public static async Task CheckFullCompatibilityAsync()
{
try
{
var webView = new WebView2()
{
Source = new Uri("https://www.google.com")
};
var env = await CoreWebView2Environment.CreateAsync().ConfigureAwait(false);
await webView.EnsureCoreWebView2Async().ConfigureAwait(false);
DisableAllExtraFunctionality(webView.CoreWebView2.Settings);
SetupVirtualHostForAssets(webView);
}
catch (Exception)
{
throw;
}
}
#endregion
}
}