forked from ArthurHub/HTML-Renderer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHtmlContainerInt.cs
More file actions
1062 lines (947 loc) · 39.2 KB
/
Copy pathHtmlContainerInt.cs
File metadata and controls
1062 lines (947 loc) · 39.2 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
// "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 System.Diagnostics;
using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core.Dom;
using TheArtOfDev.HtmlRenderer.Core.Entities;
using TheArtOfDev.HtmlRenderer.Core.Handlers;
using TheArtOfDev.HtmlRenderer.Core.Parse;
using TheArtOfDev.HtmlRenderer.Core.Utils;
namespace TheArtOfDev.HtmlRenderer.Core
{
/// <summary>
/// Low level handling of Html Renderer logic.<br/>
/// Allows html layout and rendering without association to actual control, those allowing to handle html rendering on any graphics object.<br/>
/// Using this class will require the client to handle all propagation's of mouse/keyboard events, layout/paint calls, scrolling offset,
/// location/size/rectangle handling and UI refresh requests.<br/>
/// </summary>
/// <remarks>
/// <para>
/// <b>MaxSize and ActualSize:</b><br/>
/// 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 exceed the max size by layout restrictions (unwrap-able line, set image size, etc.).<br/>
/// Set zero for unlimited (width/height separately).<br/>
/// </para>
/// <para>
/// <b>ScrollOffset:</b><br/>
/// This will adjust the rendered html by the given offset so the content will be "scrolled".<br/>
/// Element that is rendered at location (50,100) with offset of (0,200) will not be rendered
/// at -100, therefore outside the client rectangle.
/// </para>
/// <para>
/// <b>LinkClicked event</b><br/>
/// Raised when the user clicks on a link in the html.<br/>
/// Allows canceling the execution of the link to overwrite by custom logic.<br/>
/// If error occurred in event handler it will propagate up the stack.
/// </para>
/// <para>
/// <b>StylesheetLoad event:</b><br/>
/// Raised when a stylesheet is about to be loaded by file path or URL in 'link' element.<br/>
/// Allows to overwrite the loaded stylesheet by providing the stylesheet data manually, or different source (file or URL) to load from.<br/>
/// Example: The stylesheet 'href' can be non-valid URI string that is interpreted in the overwrite delegate by custom logic to pre-loaded stylesheet object<br/>
/// If no alternative data is provided the original source will be used.<br/>
/// </para>
/// <para>
/// <b>ImageLoad event:</b><br/>
/// Raised when an image is about to be loaded by file path, URL or inline data in 'img' element or background-image CSS style.<br/>
/// Allows to overwrite the loaded image by providing the image object manually, or different source (file or URL) to load from.<br/>
/// Example: image 'src' can be non-valid string that is interpreted in the overwrite delegate by custom logic to resource image object<br/>
/// Example: image 'src' in the html is relative - the overwrite intercepts the load and provide full source URL to load the image from<br/>
/// Example: image download requires authentication - the overwrite intercepts the load, downloads the image to disk using custom code and provide
/// file path to load the image from.<br/>
/// If no alternative data is provided the original source will be used.<br/>
/// </para>
/// <para>
/// <b>Refresh event:</b><br/>
/// Raised when html renderer requires refresh of the control hosting (invalidation and re-layout).<br/>
/// There is no guarantee that the event will be raised on the main thread, it can be raised on thread-pool thread.
/// </para>
/// <para>
/// <b>RenderError event:</b><br/>
/// Raised when an error occurred during html rendering.<br/>
/// </para>
/// </remarks>
public sealed class HtmlContainerInt : IDisposable
{
#region Fields and Consts
/// <summary>
/// Main adapter to framework specific logic.
/// </summary>
private readonly RAdapter _adapter;
/// <summary>
/// parser for CSS data
/// </summary>
private readonly CssParser _cssParser;
/// <summary>
/// the root css box of the parsed html
/// </summary>
private CssBox _root;
/// <summary>
/// list of all css boxes that have ":hover" selector on them
/// </summary>
private List<HoverBoxBlock> _hoverBoxes;
/// <summary>
/// Handler for text selection in the html.
/// </summary>
private SelectionHandler _selectionHandler;
/// <summary>
/// Handler for downloading of images in the html
/// </summary>
private ImageDownloader _imageDownloader;
/// <summary>
/// the text fore color use for selected text
/// </summary>
private RColor _selectionForeColor;
/// <summary>
/// the back-color to use for selected text
/// </summary>
private RColor _selectionBackColor;
/// <summary>
/// the parsed stylesheet data used for handling the html
/// </summary>
private CssData _cssData;
/// <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>
private bool _isSelectionEnabled = true;
/// <summary>
/// Is the build-in context menu enabled (default - true)
/// </summary>
private bool _isContextMenuEnabled = true;
/// <summary>
/// Gets or sets a value indicating if anti-aliasing should be avoided
/// for geometry like backgrounds and borders
/// </summary>
private bool _avoidGeometryAntialias;
/// <summary>
/// Gets or sets a value indicating if image asynchronous loading should be avoided (default - false).<br/>
/// </summary>
private bool _avoidAsyncImagesLoading;
/// <summary>
/// Gets or sets a value indicating if image loading only when visible should be avoided (default - false).<br/>
/// </summary>
private bool _avoidImagesLateLoading;
/// <summary>
/// is the load of the html document is complete
/// </summary>
private bool _loadComplete;
/// <summary>
/// the top-left most location of the rendered html
/// </summary>
private RPoint _location;
/// <summary>
/// the max width and height of the rendered html, effects layout, actual size cannot exceed this values.<br/>
/// Set zero for unlimited.<br/>
/// </summary>
private RSize _maxSize;
/// <summary>
/// Gets or sets the scroll offset of the document for scroll controls
/// </summary>
private RPoint _scrollOffset;
/// <summary>
/// The actual size of the rendered html (after layout)
/// </summary>
private RSize _actualSize;
/// <summary>
/// the top margin between the page start and the text
/// </summary>
private int _marginTop;
/// <summary>
/// the bottom margin between the page end and the text
/// </summary>
private int _marginBottom;
/// <summary>
/// the left margin between the page start and the text
/// </summary>
private int _marginLeft;
/// <summary>
/// the right margin between the page end and the text
/// </summary>
private int _marginRight;
#endregion
/// <summary>
/// Init.
/// </summary>
public HtmlContainerInt(RAdapter adapter)
{
ArgChecker.AssertArgNotNull(adapter, "global");
_adapter = adapter;
_cssParser = new CssParser(adapter);
}
/// <summary>
///
/// </summary>
internal RAdapter Adapter
{
get { return _adapter; }
}
/// <summary>
/// parser for CSS data
/// </summary>
internal CssParser CssParser
{
get { return _cssParser; }
}
/// <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;
/// <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;
/// <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;
/// <summary>
/// Raised when Html Renderer request scroll to specific location.<br/>
/// This can occur on document anchor click.
/// </summary>
public event EventHandler<HtmlScrollEventArgs> ScrollChange;
/// <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;
/// <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;
/// <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;
/// <summary>
/// the parsed stylesheet data used for handling the html
/// </summary>
public CssData CssData
{
get { return _cssData; }
}
/// <summary>
/// Gets or sets a value indicating if anti-aliasing should be avoided for geometry like backgrounds and borders (default - false).
/// </summary>
public bool AvoidGeometryAntialias
{
get { return _avoidGeometryAntialias; }
set { _avoidGeometryAntialias = value; }
}
/// <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 _avoidAsyncImagesLoading; }
set { _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 _avoidImagesLateLoading; }
set { _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 _isSelectionEnabled; }
set { _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 _isContextMenuEnabled; }
set { _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 rectangle.
/// </example>
public RPoint ScrollOffset
{
get { return _scrollOffset; }
set { _scrollOffset = 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 RPoint Location
{
get { return _location; }
set { _location = 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 (unwrapable line, set image size, etc.).<br/>
/// Set zero for unlimited (width\height separately).<br/>
/// </summary>
public RSize MaxSize
{
get { return _maxSize; }
set { _maxSize = value; }
}
/// <summary>
/// The actual size of the rendered html (after layout)
/// </summary>
public RSize ActualSize
{
get { return _actualSize; }
set { _actualSize = value; }
}
public RSize PageSize { get; set; }
/// <summary>
/// the top margin between the page start and the text
/// </summary>
public int MarginTop
{
get { return _marginTop; }
set
{
if (value > -1)
_marginTop = value;
}
}
/// <summary>
/// the bottom margin between the page end and the text
/// </summary>
public int MarginBottom
{
get { return _marginBottom; }
set
{
if (value > -1)
_marginBottom = value;
}
}
/// <summary>
/// the left margin between the page start and the text
/// </summary>
public int MarginLeft
{
get { return _marginLeft; }
set
{
if (value > -1)
_marginLeft = value;
}
}
/// <summary>
/// the right margin between the page end and the text
/// </summary>
public int MarginRight
{
get { return _marginRight; }
set
{
if (value > -1)
_marginRight = value;
}
}
/// <summary>
/// Set all 4 margins to the given value.
/// </summary>
/// <param name="value"></param>
public void SetMargins(int value)
{
if (value > -1)
_marginBottom = _marginLeft = _marginTop = _marginRight = value;
}
/// <summary>
/// Get the currently selected text segment in the html.
/// </summary>
public string SelectedText
{
get { return _selectionHandler.GetSelectedText(); }
}
/// <summary>
/// Copy the currently selected html segment with style.
/// </summary>
public string SelectedHtml
{
get { return _selectionHandler.GetSelectedHtml(); }
}
/// <summary>
/// the root css box of the parsed html
/// </summary>
internal CssBox Root
{
get { return _root; }
}
/// <summary>
/// the text fore color use for selected text
/// </summary>
internal RColor SelectionForeColor
{
get { return _selectionForeColor; }
set { _selectionForeColor = value; }
}
/// <summary>
/// the back-color to use for selected text
/// </summary>
internal RColor SelectionBackColor
{
get { return _selectionBackColor; }
set { _selectionBackColor = value; }
}
/// <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)
{
Clear();
if (!string.IsNullOrEmpty(htmlSource))
{
_loadComplete = false;
_cssData = baseCssData ?? _adapter.DefaultCssData;
DomParser parser = new DomParser(_cssParser);
_root = parser.GenerateCssTree(htmlSource, this, ref _cssData);
if (_root != null)
{
_selectionHandler = new SelectionHandler(_root);
_imageDownloader = new ImageDownloader();
}
}
}
/// <summary>
/// Clear the content of the HTML container releasing any resources used to render previously existing content.
/// </summary>
public void Clear()
{
if (_root != null)
{
_root.Dispose();
_root = null;
if (_selectionHandler != null)
_selectionHandler.Dispose();
_selectionHandler = null;
if (_imageDownloader != null)
_imageDownloader.Dispose();
_imageDownloader = null;
_hoverBoxes = null;
}
}
/// <summary>
/// Clear the current selection.
/// </summary>
public void ClearSelection()
{
if (_selectionHandler != null)
{
_selectionHandler.ClearSelection();
RequestRefresh(false);
}
}
/// <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 DomUtils.GenerateHtml(_root, 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(RPoint location, string attribute)
{
ArgChecker.AssertArgNotNullOrEmpty(attribute, "attribute");
var cssBox = DomUtils.GetCssBox(_root, OffsetByScroll(location));
return cssBox != null ? DomUtils.GetAttribute(cssBox, attribute) : null;
}
/// <summary>
/// Get all the links in the HTML with the element rectangle and href data.
/// </summary>
/// <returns>collection of all the links in the HTML</returns>
public List<LinkElementData<RRect>> GetLinks()
{
var linkBoxes = new List<CssBox>();
DomUtils.GetAllLinkBoxes(_root, linkBoxes);
var linkElements = new List<LinkElementData<RRect>>();
foreach (var box in linkBoxes)
{
linkElements.Add(new LinkElementData<RRect>(box.GetAttribute("id"), box.GetAttribute("href"), CommonUtils.GetFirstValueOrDefault(box.Rectangles, box.Bounds)));
}
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(RPoint location)
{
var link = DomUtils.GetLinkBox(_root, OffsetByScroll(location));
return link != null ? link.HrefLink : null;
}
/// <summary>
/// Get the rectangle 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 rectangle you need to adjust by the hosting control.<br/>
/// </summary>
/// <param name="elementId">the id of the element to get its rectangle</param>
/// <returns>the rectangle of the element or null if not found</returns>
public RRect? GetElementRectangle(string elementId)
{
ArgChecker.AssertArgNotNullOrEmpty(elementId, "elementId");
var box = DomUtils.GetBoxById(_root, elementId.ToLower());
return box != null ? CommonUtils.GetFirstValueOrDefault(box.Rectangles, box.Bounds) : (RRect?)null;
}
/// <summary>
/// Measures the bounds of box and children, recursively.
/// </summary>
/// <param name="g">Device context to draw</param>
public void PerformLayout(RGraphics g)
{
ArgChecker.AssertArgNotNull(g, "g");
_actualSize = RSize.Empty;
if (_root != null)
{
// if width is not restricted we set it to large value to get the actual later
_root.Size = new RSize(_maxSize.Width > 0 ? _maxSize.Width : 99999, 0);
_root.Location = _location;
_root.PerformLayout(g);
if (_maxSize.Width <= 0.1)
{
// in case the width is not restricted we need to double layout, first will find the width so second can layout by it (center alignment)
_root.Size = new RSize((int)Math.Ceiling(_actualSize.Width), 0);
_actualSize = RSize.Empty;
_root.PerformLayout(g);
}
if (!_loadComplete)
{
_loadComplete = true;
EventHandler handler = LoadComplete;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Render the html using the given device.
/// </summary>
/// <param name="g">the device to use to render</param>
public void PerformPaint(RGraphics g)
{
ArgChecker.AssertArgNotNull(g, "g");
if (MaxSize.Height > 0)
{
g.PushClip(new RRect(_location.X, _location.Y, Math.Min(_maxSize.Width, PageSize.Width), Math.Min(_maxSize.Height, PageSize.Height)));
}
else
{
g.PushClip(new RRect(MarginLeft, MarginTop, PageSize.Width, PageSize.Height));
}
if (_root != null)
{
_root.Paint(g);
}
g.PopClip();
}
/// <summary>
/// Handle mouse down to handle selection.
/// </summary>
/// <param name="parent">the control hosting the html to invalidate</param>
/// <param name="location">the location of the mouse</param>
public void HandleMouseDown(RControl parent, RPoint location)
{
ArgChecker.AssertArgNotNull(parent, "parent");
try
{
if (_selectionHandler != null)
_selectionHandler.HandleMouseDown(parent, OffsetByScroll(location), IsMouseInContainer(location));
}
catch (Exception ex)
{
ReportError(HtmlRenderErrorType.KeyboardMouse, "Failed mouse down handle", ex);
}
}
/// <summary>
/// Handle mouse up to handle selection and link click.
/// </summary>
/// <param name="parent">the control hosting the html to invalidate</param>
/// <param name="location">the location of the mouse</param>
/// <param name="e">the mouse event data</param>
public void HandleMouseUp(RControl parent, RPoint location, RMouseEvent e)
{
ArgChecker.AssertArgNotNull(parent, "parent");
try
{
if (_selectionHandler != null && IsMouseInContainer(location))
{
var ignore = _selectionHandler.HandleMouseUp(parent, e.LeftButton);
if (!ignore && e.LeftButton)
{
var loc = OffsetByScroll(location);
var link = DomUtils.GetLinkBox(_root, loc);
if (link != null)
{
HandleLinkClicked(parent, location, link);
}
}
}
}
catch (HtmlLinkClickedException)
{
throw;
}
catch (Exception ex)
{
ReportError(HtmlRenderErrorType.KeyboardMouse, "Failed mouse up handle", ex);
}
}
/// <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="location">the location of the mouse</param>
public void HandleMouseDoubleClick(RControl parent, RPoint location)
{
ArgChecker.AssertArgNotNull(parent, "parent");
try
{
if (_selectionHandler != null && IsMouseInContainer(location))
_selectionHandler.SelectWord(parent, OffsetByScroll(location));
}
catch (Exception ex)
{
ReportError(HtmlRenderErrorType.KeyboardMouse, "Failed mouse double click handle", ex);
}
}
/// <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="location">the location of the mouse</param>
public void HandleMouseMove(RControl parent, RPoint location)
{
ArgChecker.AssertArgNotNull(parent, "parent");
try
{
var loc = OffsetByScroll(location);
if (_selectionHandler != null && IsMouseInContainer(location))
_selectionHandler.HandleMouseMove(parent, loc);
/*
if( _hoverBoxes != null )
{
bool refresh = false;
foreach(var hoverBox in _hoverBoxes)
{
foreach(var rect in hoverBox.Item1.Rectangles.Values)
{
if( rect.Contains(loc) )
{
//hoverBox.Item1.Color = "gold";
refresh = true;
}
}
}
if(refresh)
RequestRefresh(true);
}
*/
}
catch (Exception ex)
{
ReportError(HtmlRenderErrorType.KeyboardMouse, "Failed mouse move handle", ex);
}
}
/// <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(RControl parent)
{
ArgChecker.AssertArgNotNull(parent, "parent");
try
{
if (_selectionHandler != null)
_selectionHandler.HandleMouseLeave(parent);
}
catch (Exception ex)
{
ReportError(HtmlRenderErrorType.KeyboardMouse, "Failed mouse leave handle", ex);
}
}
/// <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(RControl parent, RKeyEvent e)
{
ArgChecker.AssertArgNotNull(parent, "parent");
ArgChecker.AssertArgNotNull(e, "e");
try
{
if (e.Control && _selectionHandler != null)
{
// select all
if (e.AKeyCode)
{
_selectionHandler.SelectAll(parent);
}
// copy currently selected text
if (e.CKeyCode)
{
_selectionHandler.CopySelectedHtml();
}
}
}
catch (Exception ex)
{
ReportError(HtmlRenderErrorType.KeyboardMouse, "Failed key down handle", ex);
}
}
/// <summary>
/// Raise the stylesheet load event with the given event args.
/// </summary>
/// <param name="args">the event args</param>
internal void RaiseHtmlStylesheetLoadEvent(HtmlStylesheetLoadEventArgs args)
{
try
{
EventHandler<HtmlStylesheetLoadEventArgs> handler = StylesheetLoad;
if (handler != null)
handler(this, args);
}
catch (Exception ex)
{
ReportError(HtmlRenderErrorType.CssParsing, "Failed stylesheet load event", ex);
}
}
/// <summary>
/// Raise the image load event with the given event args.
/// </summary>
/// <param name="args">the event args</param>
internal void RaiseHtmlImageLoadEvent(HtmlImageLoadEventArgs args)
{
try
{
EventHandler<HtmlImageLoadEventArgs> handler = ImageLoad;
if (handler != null)
handler(this, args);
}
catch (Exception ex)
{
ReportError(HtmlRenderErrorType.Image, "Failed image load event", ex);
}
}
/// <summary>
/// Request invalidation and re-layout of the control hosting the renderer.
/// </summary>
/// <param name="layout">is re-layout is required for the refresh</param>
public void RequestRefresh(bool layout)
{
try
{
EventHandler<HtmlRefreshEventArgs> handler = Refresh;
if (handler != null)
handler(this, new HtmlRefreshEventArgs(layout));
}
catch (Exception ex)
{
ReportError(HtmlRenderErrorType.General, "Failed refresh request", ex);
}
}
/// <summary>
/// Report error in html render process.
/// </summary>
/// <param name="type">the type of error to report</param>
/// <param name="message">the error message</param>
/// <param name="exception">optional: the exception that occured</param>
internal void ReportError(HtmlRenderErrorType type, string message, Exception exception = null)
{
try
{
EventHandler<HtmlRenderErrorEventArgs> handler = RenderError;
if (handler != null)
handler(this, new HtmlRenderErrorEventArgs(type, message, exception));
}
catch
{ }
}
/// <summary>
/// Handle link clicked going over <see cref="LinkClicked"/> event and using <see cref="Process.Start()"/> if not canceled.
/// </summary>
/// <param name="parent">the control hosting the html to invalidate</param>
/// <param name="location">the location of the mouse</param>
/// <param name="link">the link that was clicked</param>
internal void HandleLinkClicked(RControl parent, RPoint location, CssBox link)
{
EventHandler<HtmlLinkClickedEventArgs> clickHandler = LinkClicked;
if (clickHandler != null)
{
var args = new HtmlLinkClickedEventArgs(link.HrefLink, link.HtmlTag.Attributes);
try
{
clickHandler(this, args);
}
catch (Exception ex)
{
throw new HtmlLinkClickedException("Error in link clicked intercept", ex);
}
if (args.Handled)
return;
}
if (!string.IsNullOrEmpty(link.HrefLink))
{
if (link.HrefLink.StartsWith("#") && link.HrefLink.Length > 1)
{
EventHandler<HtmlScrollEventArgs> scrollHandler = ScrollChange;
if (scrollHandler != null)
{
var rect = GetElementRectangle(link.HrefLink.Substring(1));
if (rect.HasValue)
{
scrollHandler(this, new HtmlScrollEventArgs(rect.Value.Location));
HandleMouseMove(parent, location);
}
}
}
else
{
var nfo = new ProcessStartInfo(link.HrefLink);
nfo.UseShellExecute = true;
Process.Start(nfo);
}
}
}
/// <summary>
/// Add css box that has ":hover" selector to be handled on mouse hover.
/// </summary>
/// <param name="box">the box that has the hover selector</param>
/// <param name="block">the css block with the css data with the selector</param>
internal void AddHoverBox(CssBox box, CssBlock block)
{
ArgChecker.AssertArgNotNull(box, "box");
ArgChecker.AssertArgNotNull(block, "block");
if (_hoverBoxes == null)
_hoverBoxes = new List<HoverBoxBlock>();
_hoverBoxes.Add(new HoverBoxBlock(box, block));
}
/// <summary>
/// Get image downloader to be used to download images for the current html rendering.<br/>
/// Lazy create single downloader to be used for all images in the current html.
/// </summary>
internal ImageDownloader GetImageDownloader()
{
return _imageDownloader;
}