forked from AvaloniaUI/Avalonia.HtmlRenderer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHtmlContainer.cs
471 lines (418 loc) · 18.6 KB
/
HtmlContainer.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
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Html;
using Avalonia.Input;
using Avalonia.Media;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core;
using TheArtOfDev.HtmlRenderer.Core.Entities;
using TheArtOfDev.HtmlRenderer.Core.Parse;
using TheArtOfDev.HtmlRenderer.Core.Utils;
using TheArtOfDev.HtmlRenderer.Avalonia.Adapters;
using TheArtOfDev.HtmlRenderer.Avalonia.Utilities;
namespace TheArtOfDev.HtmlRenderer.Avalonia
{
/// <summary>
/// Low level handling of Html Renderer logic, this class is used by <see cref="HtmlParser"/>,
/// <see cref="HtmlLabel"/>, <see cref="HtmlToolTip"/> and <see cref="HtmlRender"/>.<br/>
/// </summary>
/// <seealso cref="HtmlContainerInt"/>
public sealed class HtmlContainer : IDisposable
{
#region Fields and Consts
/// <summary>
/// The internal core html container
/// </summary>
private readonly HtmlContainerInt _htmlContainerInt;
#endregion
/// <summary>
/// Init.
/// </summary>
public HtmlContainer()
{
_htmlContainerInt = new HtmlContainerInt(AvaloniaAdapter.Instance);
}
/// <summary>
/// Raised when the set html document has been fully loaded.<br/>
/// Allows manipulation of the html dom, scroll position, etc.
/// </summary>
public event EventHandler LoadComplete
{
add { _htmlContainerInt.LoadComplete += value; }
remove { _htmlContainerInt.LoadComplete -= value; }
}
/// <summary>
/// Raised when the user clicks on a link in the html.<br/>
/// Allows canceling the execution of the link.
/// </summary>
public event EventHandler<HtmlLinkClickedEventArgs> LinkClicked
{
add { _htmlContainerInt.LinkClicked += value; }
remove { _htmlContainerInt.LinkClicked -= value; }
}
/// <summary>
/// Raised when html renderer requires refresh of the control hosting (invalidation and re-layout).
/// </summary>
/// <remarks>
/// There is no guarantee that the event will be raised on the main thread, it can be raised on thread-pool thread.
/// </remarks>
public event EventHandler<HtmlRefreshEventArgs> Refresh
{
add { _htmlContainerInt.Refresh += value; }
remove { _htmlContainerInt.Refresh -= value; }
}
/// <summary>
/// Raised when Html Renderer request scroll to specific location.<br/>
/// This can occur on document anchor click.
/// </summary>
public event EventHandler<HtmlScrollEventArgs> ScrollChange
{
add { _htmlContainerInt.ScrollChange += value; }
remove { _htmlContainerInt.ScrollChange -= value; }
}
/// <summary>
/// Raised when an error occurred during html rendering.<br/>
/// </summary>
/// <remarks>
/// There is no guarantee that the event will be raised on the main thread, it can be raised on thread-pool thread.
/// </remarks>
public event EventHandler<HtmlRenderErrorEventArgs> RenderError
{
add { _htmlContainerInt.RenderError += value; }
remove { _htmlContainerInt.RenderError -= value; }
}
/// <summary>
/// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/>
/// This event allows to provide the stylesheet manually or provide new source (file or Uri) to load from.<br/>
/// If no alternative data is provided the original source will be used.<br/>
/// </summary>
public event EventHandler<HtmlStylesheetLoadEventArgs> StylesheetLoad
{
add { _htmlContainerInt.StylesheetLoad += value; }
remove { _htmlContainerInt.StylesheetLoad -= value; }
}
/// <summary>
/// Raised when an image is about to be loaded by file path or URI.<br/>
/// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI.
/// </summary>
public event EventHandler<HtmlImageLoadEventArgs> ImageLoad
{
add { _htmlContainerInt.ImageLoad += value; }
remove { _htmlContainerInt.ImageLoad -= value; }
}
/// <summary>
/// The internal core html container
/// </summary>
internal HtmlContainerInt HtmlContainerInt
{
get { return _htmlContainerInt; }
}
/// <summary>
/// the parsed stylesheet data used for handling the html
/// </summary>
public CssData CssData
{
get { return _htmlContainerInt.CssData; }
}
/// <summary>
/// Gets or sets a value indicating if image asynchronous loading should be avoided (default - false).<br/>
/// True - images are loaded synchronously during html parsing.<br/>
/// False - images are loaded asynchronously to html parsing when downloaded from URL or loaded from disk.<br/>
/// </summary>
/// <remarks>
/// Asynchronously image loading allows to unblock html rendering while image is downloaded or loaded from disk using IO
/// ports to achieve better performance.<br/>
/// Asynchronously image loading should be avoided when the full html content must be available during render, like render to image.
/// </remarks>
public bool AvoidAsyncImagesLoading
{
get { return _htmlContainerInt.AvoidAsyncImagesLoading; }
set { _htmlContainerInt.AvoidAsyncImagesLoading = value; }
}
/// <summary>
/// Gets or sets a value indicating if image loading only when visible should be avoided (default - false).<br/>
/// True - images are loaded as soon as the html is parsed.<br/>
/// False - images that are not visible because of scroll location are not loaded until they are scrolled to.
/// </summary>
/// <remarks>
/// Images late loading improve performance if the page contains image outside the visible scroll area, especially if there is large
/// amount of images, as all image loading is delayed (downloading and loading into memory).<br/>
/// Late image loading may effect the layout and actual size as image without set size will not have actual size until they are loaded
/// resulting in layout change during user scroll.<br/>
/// Early image loading may also effect the layout if image without known size above the current scroll location are loaded as they
/// will push the html elements down.
/// </remarks>
public bool AvoidImagesLateLoading
{
get { return _htmlContainerInt.AvoidImagesLateLoading; }
set { _htmlContainerInt.AvoidImagesLateLoading = value; }
}
/// <summary>
/// Is content selection is enabled for the rendered html (default - true).<br/>
/// If set to 'false' the rendered html will be static only with ability to click on links.
/// </summary>
public bool IsSelectionEnabled
{
get { return _htmlContainerInt.IsSelectionEnabled; }
set { _htmlContainerInt.IsSelectionEnabled = value; }
}
/// <summary>
/// Is the build-in context menu enabled and will be shown on mouse right click (default - true)
/// </summary>
public bool IsContextMenuEnabled
{
get { return _htmlContainerInt.IsContextMenuEnabled; }
set { _htmlContainerInt.IsContextMenuEnabled = value; }
}
/// <summary>
/// The scroll offset of the html.<br/>
/// This will adjust the rendered html by the given offset so the content will be "scrolled".<br/>
/// </summary>
/// <example>
/// Element that is rendered at location (50,100) with offset of (0,200) will not be rendered as it
/// will be at -100 therefore outside the client Rect.
/// </example>
public Point ScrollOffset
{
get { return Util.Convert(_htmlContainerInt.ScrollOffset); }
set { _htmlContainerInt.ScrollOffset = Util.Convert(value); }
}
/// <summary>
/// The top-left most location of the rendered html.<br/>
/// This will offset the top-left corner of the rendered html.
/// </summary>
public Point Location
{
get { return Util.Convert(_htmlContainerInt.Location); }
set { _htmlContainerInt.Location = Util.Convert(value); }
}
/// <summary>
/// The max width and height of the rendered html.<br/>
/// The max width will effect the html layout wrapping lines, resize images and tables where possible.<br/>
/// The max height does NOT effect layout, but will not render outside it (clip).<br/>
/// <see cref="ActualSize"/> can be exceed the max size by layout restrictions (unwrappable line, set image size, etc.).<br/>
/// Set zero for unlimited (width\height separately).<br/>
/// </summary>
public Size MaxSize
{
get { return Util.Convert(_htmlContainerInt.MaxSize); }
set { _htmlContainerInt.MaxSize = Util.Convert(value); }
}
/// <summary>
/// The actual size of the rendered html (after layout)
/// </summary>
public Size ActualSize
{
get { return Util.Convert(_htmlContainerInt.ActualSize); }
internal set { _htmlContainerInt.ActualSize = Util.Convert(value); }
}
/// <summary>
/// Get the currently selected text segment in the html.
/// </summary>
public string SelectedText
{
get { return _htmlContainerInt.SelectedText; }
}
/// <summary>
/// Copy the currently selected html segment with style.
/// </summary>
public string SelectedHtml
{
get { return _htmlContainerInt.SelectedHtml; }
}
/// <summary>
/// Clear the current selection.
/// </summary>
public void ClearSelection()
{
HtmlContainerInt.ClearSelection();
}
/// <summary>
/// Init with optional document and stylesheet.
/// </summary>
/// <param name="htmlSource">the html to init with, init empty if not given</param>
/// <param name="baseCssData">optional: the stylesheet to init with, init default if not given</param>
public void SetHtml(string htmlSource, CssData baseCssData = null)
{
_htmlContainerInt.SetHtml(htmlSource, baseCssData);
}
/// <summary>
/// Clear the content of the HTML container releasing any resources used to render previously existing content.
/// </summary>
public void Clear()
{
_htmlContainerInt.Clear();
}
/// <summary>
/// Get html from the current DOM tree with style if requested.
/// </summary>
/// <param name="styleGen">Optional: controls the way styles are generated when html is generated (default: <see cref="HtmlGenerationStyle.Inline"/>)</param>
/// <returns>generated html</returns>
public string GetHtml(HtmlGenerationStyle styleGen = HtmlGenerationStyle.Inline)
{
return _htmlContainerInt.GetHtml(styleGen);
}
/// <summary>
/// Get attribute value of element at the given x,y location by given key.<br/>
/// If more than one element exist with the attribute at the location the inner most is returned.
/// </summary>
/// <param name="location">the location to find the attribute at</param>
/// <param name="attribute">the attribute key to get value by</param>
/// <returns>found attribute value or null if not found</returns>
public string GetAttributeAt(Point location, string attribute)
{
return _htmlContainerInt.GetAttributeAt(Util.Convert(location), attribute);
}
/// <summary>
/// Get all the links in the HTML with the element Rect and href data.
/// </summary>
/// <returns>collection of all the links in the HTML</returns>
public List<LinkElementData<Rect>> GetLinks()
{
var linkElements = new List<LinkElementData<Rect>>();
foreach (var link in HtmlContainerInt.GetLinks())
{
linkElements.Add(new LinkElementData<Rect>(link.Id, link.Href, Util.Convert(link.Rectangle)));
}
return linkElements;
}
/// <summary>
/// Get css link href at the given x,y location.
/// </summary>
/// <param name="location">the location to find the link at</param>
/// <returns>css link href if exists or null</returns>
public string GetLinkAt(Point location)
{
return _htmlContainerInt.GetLinkAt(Util.Convert(location));
}
/// <summary>
/// Get the Rect of html element as calculated by html layout.<br/>
/// Element if found by id (id attribute on the html element).<br/>
/// Note: to get the screen Rect you need to adjust by the hosting control.<br/>
/// </summary>
/// <param name="elementId">the id of the element to get its Rect</param>
/// <returns>the Rect of the element or null if not found</returns>
public Rect? GetElementRectangle(string elementId)
{
var r = _htmlContainerInt.GetElementRectangle(elementId);
return r.HasValue ? Util.Convert(r.Value) : (Rect?)null;
}
/// <summary>
/// Measures the bounds of box and children, recursively.
/// </summary>
public void PerformLayout()
{
using (var ig = new GraphicsAdapter())
{
_htmlContainerInt.PerformLayout(ig);
}
}
/// <summary>
/// Render the html using the given device.
/// </summary>
/// <param name="g">the device to use to render</param>
/// <param name="clip">the clip rectangle of the html container</param>
public void PerformPaint(DrawingContext g, Rect clip)
{
ArgChecker.AssertArgNotNull(g, "g");
using (var ig = new GraphicsAdapter(g, Util.Convert(clip)))
{
_htmlContainerInt.PerformPaint(ig);
}
}
/// <summary>
/// Handle mouse down to handle selection.
/// </summary>
/// <param name="parent">the control hosting the html to invalidate</param>
/// <param name="e">the mouse event args</param>
public void HandleLeftMouseDown(Control parent, PointerEventArgs e)
{
ArgChecker.AssertArgNotNull(parent, "parent");
ArgChecker.AssertArgNotNull(e, "e");
_htmlContainerInt.HandleMouseDown(new ControlAdapter(parent), Util.Convert(e.GetPosition(parent)));
}
/// <summary>
/// Handle mouse up to handle selection and link click.
/// </summary>
/// <param name="parent">the control hosting the html to invalidate</param>
/// <param name="e">the mouse event args</param>
public void HandleLeftMouseUp(Control parent, PointerEventArgs e)
{
ArgChecker.AssertArgNotNull(parent, "parent");
ArgChecker.AssertArgNotNull(e, "e");
var mouseEvent = new RMouseEvent(true);
_htmlContainerInt.HandleMouseUp(new ControlAdapter(parent), Util.Convert(e.GetPosition(parent)), mouseEvent);
}
/// <summary>
/// Handle mouse double click to select word under the mouse.
/// </summary>
/// <param name="parent">the control hosting the html to set cursor and invalidate</param>
/// <param name="e">mouse event args</param>
public void HandleMouseDoubleClick(Control parent, PointerEventArgs e)
{
ArgChecker.AssertArgNotNull(parent, "parent");
ArgChecker.AssertArgNotNull(e, "e");
_htmlContainerInt.HandleMouseDoubleClick(new ControlAdapter(parent), Util.Convert(e.GetPosition(parent)));
}
/// <summary>
/// Handle mouse move to handle hover cursor and text selection.
/// </summary>
/// <param name="parent">the control hosting the html to set cursor and invalidate</param>
/// <param name="mousePos">the mouse event args</param>
public void HandleMouseMove(Control parent, Point mousePos)
{
ArgChecker.AssertArgNotNull(parent, "parent");
_htmlContainerInt.HandleMouseMove(new ControlAdapter(parent), Util.Convert(mousePos));
}
/// <summary>
/// Handle mouse leave to handle hover cursor.
/// </summary>
/// <param name="parent">the control hosting the html to set cursor and invalidate</param>
public void HandleMouseLeave(Control parent)
{
ArgChecker.AssertArgNotNull(parent, "parent");
_htmlContainerInt.HandleMouseLeave(new ControlAdapter(parent));
}
/// <summary>
/// Handle key down event for selection and copy.
/// </summary>
/// <param name="parent">the control hosting the html to invalidate</param>
/// <param name="e">the pressed key</param>
public void HandleKeyDown(Control parent, KeyEventArgs e)
{
ArgChecker.AssertArgNotNull(parent, "parent");
ArgChecker.AssertArgNotNull(e, "e");
_htmlContainerInt.HandleKeyDown(new ControlAdapter(parent), CreateKeyEevent(e));
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_htmlContainerInt.Dispose();
}
#region Private methods
/// <summary>
/// Create HtmlRenderer key event from Avalonia key event.
/// </summary>
private static RKeyEvent CreateKeyEevent(KeyEventArgs e)
{
var control = (e.Modifiers & InputModifiers.Control) == InputModifiers.Control;
return new RKeyEvent(control, e.Key == Key.A, e.Key == Key.C);
}
#endregion
}
}