forked from ArthurHub/HTML-Renderer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphicsAdapter.cs
More file actions
507 lines (433 loc) · 17 KB
/
GraphicsAdapter.cs
File metadata and controls
507 lines (433 loc) · 17 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
// "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.Drawing;
using System.Drawing.Drawing2D;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core.Utils;
using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.WinForms.Utilities;
namespace TheArtOfDev.HtmlRenderer.WinForms.Adapters
{
/// <summary>
/// Adapter for WinForms Graphics for core.
/// </summary>
internal sealed class GraphicsAdapter : RGraphics
{
#region Fields and Consts
/// <summary>
/// used for <see cref="MeasureString(string,RFont,double,out int,out double)"/> calculation.
/// </summary>
private static readonly int[] _charFit = new int[1];
/// <summary>
/// used for <see cref="MeasureString(string,RFont,double,out int,out double)"/> calculation.
/// </summary>
private static readonly int[] _charFitWidth = new int[1000];
/// <summary>
/// Used for GDI+ measure string.
/// </summary>
private static readonly CharacterRange[] _characterRanges = new CharacterRange[1];
/// <summary>
/// The string format to use for measuring strings for GDI+ text rendering
/// </summary>
private static readonly StringFormat _stringFormat;
/// <summary>
/// The string format to use for rendering strings for GDI+ text rendering
/// </summary>
private static readonly StringFormat _stringFormat2;
/// <summary>
/// The wrapped WinForms graphics object
/// </summary>
private readonly Graphics _g;
/// <summary>
/// Use GDI+ text rendering to measure/draw text.
/// </summary>
private readonly bool _useGdiPlusTextRendering;
#if !MONO
/// <summary>
/// the initialized HDC used
/// </summary>
private IntPtr _hdc;
#endif
/// <summary>
/// if to release the graphics object on dispose
/// </summary>
private readonly bool _releaseGraphics;
/// <summary>
/// If text alignment was set to RTL
/// </summary>
private bool _setRtl;
#endregion
/// <summary>
/// Init static resources.
/// </summary>
static GraphicsAdapter()
{
_stringFormat = new StringFormat(StringFormat.GenericTypographic);
_stringFormat.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.MeasureTrailingSpaces;
_stringFormat2 = new StringFormat(StringFormat.GenericTypographic);
}
/// <summary>
/// Init.
/// </summary>
/// <param name="g">the win forms graphics object to use</param>
/// <param name="useGdiPlusTextRendering">Use GDI+ text rendering to measure/draw text</param>
/// <param name="releaseGraphics">optional: if to release the graphics object on dispose (default - false)</param>
public GraphicsAdapter(Graphics g, bool useGdiPlusTextRendering, bool releaseGraphics = false)
: base(WinFormsAdapter.Instance, Utils.Convert(g.ClipBounds))
{
ArgChecker.AssertArgNotNull(g, "g");
_g = g;
_releaseGraphics = releaseGraphics;
#if MONO
_useGdiPlusTextRendering = true;
#else
_useGdiPlusTextRendering = useGdiPlusTextRendering;
#endif
}
public override void PopClip()
{
ReleaseHdc();
_clipStack.Pop();
_g.SetClip(Utils.Convert(_clipStack.Peek()), CombineMode.Replace);
}
public override void PushClip(RRect rect)
{
ReleaseHdc();
_clipStack.Push(rect);
_g.SetClip(Utils.Convert(rect), CombineMode.Replace);
}
public override void PushClipExclude(RRect rect)
{
ReleaseHdc();
_clipStack.Push(_clipStack.Peek());
_g.SetClip(Utils.Convert(rect), CombineMode.Exclude);
}
public override Object SetAntiAliasSmoothingMode()
{
ReleaseHdc();
var prevMode = _g.SmoothingMode;
_g.SmoothingMode = SmoothingMode.AntiAlias;
return prevMode;
}
public override void ReturnPreviousSmoothingMode(Object prevMode)
{
if (prevMode != null)
{
ReleaseHdc();
_g.SmoothingMode = (SmoothingMode)prevMode;
}
}
public override RSize MeasureString(string str, RFont font)
{
if (_useGdiPlusTextRendering)
{
ReleaseHdc();
var fontAdapter = (FontAdapter)font;
var realFont = fontAdapter.Font;
_characterRanges[0] = new CharacterRange(0, str.Length);
_stringFormat.SetMeasurableCharacterRanges(_characterRanges);
var size = _g.MeasureCharacterRanges(str, realFont, RectangleF.Empty, _stringFormat)[0].GetBounds(_g).Size;
if (font.Height < 0)
{
var height = realFont.Height;
var descent = realFont.Size * realFont.FontFamily.GetCellDescent(realFont.Style) / realFont.FontFamily.GetEmHeight(realFont.Style);
#if !MONO
fontAdapter.SetMetrics(height, (int)Math.Round((height - descent + .5f)));
#else
fontAdapter.SetMetrics(height, (int)Math.Round((height - descent + 1f)));
#endif
}
return Utils.Convert(size);
}
else
{
#if !MONO
SetFont(font);
var size = new Size();
Win32Utils.GetTextExtentPoint32(_hdc, str, str.Length, ref size);
if (font.Height < 0)
{
TextMetric lptm;
Win32Utils.GetTextMetrics(_hdc, out lptm);
((FontAdapter)font).SetMetrics(size.Height, lptm.tmHeight - lptm.tmDescent + lptm.tmUnderlined + 1);
}
return Utils.Convert(size);
#else
throw new InvalidProgramException("Invalid Mono code");
#endif
}
}
public override void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth)
{
charFit = 0;
charFitWidth = 0;
if (_useGdiPlusTextRendering)
{
ReleaseHdc();
var size = MeasureString(str, font);
for (int i = 1; i <= str.Length; i++)
{
charFit = i - 1;
RSize pSize = MeasureString(str.Substring(0, i), font);
if (pSize.Height <= size.Height && pSize.Width < maxWidth)
charFitWidth = pSize.Width;
else
break;
}
}
else
{
#if !MONO
SetFont(font);
var size = new Size();
Win32Utils.GetTextExtentExPoint(_hdc, str, str.Length, (int)Math.Round(maxWidth), _charFit, _charFitWidth, ref size);
charFit = _charFit[0];
charFitWidth = charFit > 0 ? _charFitWidth[charFit - 1] : 0;
#endif
}
}
public override void DrawString(string str, RFont font, RColor color, RPoint point, RSize size, bool rtl)
{
if (_useGdiPlusTextRendering)
{
ReleaseHdc();
SetRtlAlignGdiPlus(rtl);
var brush = ((BrushAdapter)_adapter.GetSolidBrush(color)).Brush;
_g.DrawString(str, ((FontAdapter)font).Font, brush, (int)(Math.Round(point.X) + (rtl ? size.Width : 0)), (int)Math.Round(point.Y), _stringFormat2);
}
else
{
#if !MONO
var pointConv = Utils.ConvertRound(point);
var colorConv = Utils.Convert(color);
if (color.A == 255)
{
SetFont(font);
SetTextColor(colorConv);
SetRtlAlignGdi(rtl);
Win32Utils.TextOut(_hdc, pointConv.X, pointConv.Y, str, str.Length);
}
else
{
InitHdc();
SetRtlAlignGdi(rtl);
DrawTransparentText(_hdc, str, font, pointConv, Utils.ConvertRound(size), colorConv);
}
#endif
}
}
public override void DrawSmallCapString(string str, RFont regularFont, RFont reducedFont, RColor color, RPoint point, bool rtl)
{
double additionalOffsetForSmallCaps = regularFont.UnderlineOffset - reducedFont.UnderlineOffset;
int i = 0;
int len = str.Length;
while (i < len)
{
int j = i;
while (j < len && !char.IsLower(str, j))
j++;
if (j != i)
{
RSize normalSize = MeasureString(str.Substring(i, j - i), regularFont);
DrawString(str.Substring(i, j - i), regularFont, color, point, new RSize(normalSize.Width, normalSize.Height), rtl);
point.X += normalSize.Width;
i = j;
}
while (j < len && char.IsLower(str, j))
j++;
if (j != i)
{
point.Y += additionalOffsetForSmallCaps;
RSize reducedSize = MeasureString(str.Substring(i, j - i).ToUpper(), reducedFont);
DrawString(str.Substring(i, j - i).ToUpper(), reducedFont, color, point, new RSize(reducedSize.Width, reducedSize.Height), rtl);
point.X += reducedSize.Width;
point.Y -= additionalOffsetForSmallCaps;
i = j;
}
}
}
public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation)
{
var brush = new TextureBrush(((ImageAdapter)image).Image, Utils.Convert(dstRect));
brush.TranslateTransform((float)translateTransformLocation.X, (float)translateTransformLocation.Y);
return new BrushAdapter(brush, true);
}
public override RGraphicsPath GetGraphicsPath()
{
return new GraphicsPathAdapter();
}
public override void Dispose()
{
ReleaseHdc();
if (_releaseGraphics)
_g.Dispose();
if (_useGdiPlusTextRendering && _setRtl)
_stringFormat2.FormatFlags ^= StringFormatFlags.DirectionRightToLeft;
}
#region Delegate graphics methods
public override void DrawLine(RPen pen, double x1, double y1, double x2, double y2)
{
ReleaseHdc();
_g.DrawLine(((PenAdapter)pen).Pen, (float)x1, (float)y1, (float)x2, (float)y2);
}
public override void DrawRectangle(RPen pen, double x, double y, double width, double height)
{
ReleaseHdc();
_g.DrawRectangle(((PenAdapter)pen).Pen, (float)x, (float)y, (float)width, (float)height);
}
public override void DrawRectangle(RBrush brush, double x, double y, double width, double height)
{
ReleaseHdc();
_g.FillRectangle(((BrushAdapter)brush).Brush, (float)x, (float)y, (float)width, (float)height);
}
public override void DrawImage(RImage image, RRect destRect, RRect srcRect)
{
ReleaseHdc();
_g.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect), Utils.Convert(srcRect), GraphicsUnit.Pixel);
}
public override void DrawImage(RImage image, RRect destRect)
{
ReleaseHdc();
_g.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect));
}
public override void DrawPath(RPen pen, RGraphicsPath path)
{
_g.DrawPath(((PenAdapter)pen).Pen, ((GraphicsPathAdapter)path).GraphicsPath);
}
public override void DrawPath(RBrush brush, RGraphicsPath path)
{
ReleaseHdc();
_g.FillPath(((BrushAdapter)brush).Brush, ((GraphicsPathAdapter)path).GraphicsPath);
}
public override void DrawPolygon(RBrush brush, RPoint[] points)
{
if (points != null && points.Length > 0)
{
ReleaseHdc();
_g.FillPolygon(((BrushAdapter)brush).Brush, Utils.Convert(points));
}
}
#endregion
#region Private methods
/// <summary>
/// Release current HDC to be able to use <see cref="Graphics"/> methods.
/// </summary>
private void ReleaseHdc()
{
#if !MONO
if (_hdc != IntPtr.Zero)
{
Win32Utils.SelectClipRgn(_hdc, IntPtr.Zero);
_g.ReleaseHdc(_hdc);
_hdc = IntPtr.Zero;
}
#endif
}
#if !MONO
/// <summary>
/// Init HDC for the current graphics object to be used to call GDI directly.
/// </summary>
private void InitHdc()
{
if (_hdc == IntPtr.Zero)
{
var clip = _g.Clip.GetHrgn(_g);
_hdc = _g.GetHdc();
_setRtl = false;
Win32Utils.SetBkMode(_hdc, 1);
Win32Utils.SelectClipRgn(_hdc, clip);
Win32Utils.DeleteObject(clip);
}
}
/// <summary>
/// Set a resource (e.g. a font) for the specified device context.
/// WARNING: Calling Font.ToHfont() many times without releasing the font handle crashes the app.
/// </summary>
private void SetFont(RFont font)
{
InitHdc();
Win32Utils.SelectObject(_hdc, ((FontAdapter)font).HFont);
}
/// <summary>
/// Set the text color of the device context.
/// </summary>
private void SetTextColor(Color color)
{
InitHdc();
int rgb = (color.B & 0xFF) << 16 | (color.G & 0xFF) << 8 | color.R;
Win32Utils.SetTextColor(_hdc, rgb);
}
/// <summary>
/// Change text align to Left-to-Right or Right-to-Left if required.
/// </summary>
private void SetRtlAlignGdi(bool rtl)
{
if (_setRtl)
{
if (!rtl)
Win32Utils.SetTextAlign(_hdc, Win32Utils.TextAlignDefault);
}
else if (rtl)
{
Win32Utils.SetTextAlign(_hdc, Win32Utils.TextAlignRtl);
}
_setRtl = rtl;
}
/// <summary>
/// Special draw logic to draw transparent text using GDI.<br/>
/// 1. Create in-memory DC<br/>
/// 2. Copy background to in-memory DC<br/>
/// 3. Draw the text to in-memory DC<br/>
/// 4. Copy the in-memory DC to the proper location with alpha blend<br/>
/// </summary>
private static void DrawTransparentText(IntPtr hdc, string str, RFont font, Point point, Size size, Color color)
{
IntPtr dib;
var memoryHdc = Win32Utils.CreateMemoryHdc(hdc, size.Width, size.Height, out dib);
try
{
// copy target background to memory HDC so when copied back it will have the proper background
Win32Utils.BitBlt(memoryHdc, 0, 0, size.Width, size.Height, hdc, point.X, point.Y, Win32Utils.BitBltCopy);
// Create and select font
Win32Utils.SelectObject(memoryHdc, ((FontAdapter)font).HFont);
Win32Utils.SetTextColor(memoryHdc, (color.B & 0xFF) << 16 | (color.G & 0xFF) << 8 | color.R);
// Draw text to memory HDC
Win32Utils.TextOut(memoryHdc, 0, 0, str, str.Length);
// copy from memory HDC to normal HDC with alpha blend so achieve the transparent text
Win32Utils.AlphaBlend(hdc, point.X, point.Y, size.Width, size.Height, memoryHdc, 0, 0, size.Width, size.Height, new BlendFunction(color.A));
}
finally
{
Win32Utils.ReleaseMemoryHdc(memoryHdc, dib);
}
}
#endif
/// <summary>
/// Change text align to Left-to-Right or Right-to-Left if required.
/// </summary>
private void SetRtlAlignGdiPlus(bool rtl)
{
if (_setRtl)
{
if (!rtl)
_stringFormat2.FormatFlags ^= StringFormatFlags.DirectionRightToLeft;
}
else if (rtl)
{
_stringFormat2.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
}
_setRtl = rtl;
}
#endregion
}
}