forked from unoplatform/uno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InlineCollection.skia.cs
503 lines (400 loc) · 14 KB
/
InlineCollection.skia.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SkiaSharp;
using Windows.Foundation;
using Windows.UI.Composition;
using Windows.UI.Text;
using Windows.UI.Xaml.Documents.TextFormatting;
using Windows.UI.Xaml.Media;
using Uno.UI.Composition;
#nullable enable
namespace Windows.UI.Xaml.Documents
{
partial class InlineCollection
{
private static SKTextBlobBuilder _textBlobBuilder = new();
private readonly List<RenderLine> _renderLines = new();
private bool _invalidationPending;
private double _lastMeasuredWidth;
private Size _lastDesiredSize;
private Size _lastArrangedSize;
/// <summary>
/// Measures a block-level inline collection, i.e. one that belongs to a TextBlock (or Paragraph, in the future).
/// </summary>
internal Size Measure(Size availableSize)
{
if (!_invalidationPending &&
availableSize.Width <= _lastMeasuredWidth &&
availableSize.Width >= _lastDesiredSize.Width)
{
return _lastDesiredSize;
}
_invalidationPending = false;
_lastMeasuredWidth = availableSize.Width;
var parent = (IBlock)_collection.GetParent();
var wrapping = parent.TextWrapping;
int maxLines = parent.MaxLines;
float lineHeight = (float)parent.LineHeight;
var lineStackingStrategy = lineHeight == 0 ? LineStackingStrategy.MaxHeight : parent.LineStackingStrategy;
_renderLines.Clear();
List<RenderSegmentSpan> lineSegmentSpans = new();
bool previousLineWrapped = false;
float availableWidth = wrapping == TextWrapping.NoWrap ? float.PositiveInfinity : (float)availableSize.Width;
float widestLineWidth = 0;
float x = 0;
float height = 0;
foreach (var inline in PreorderTree)
{
if (inline is LineBreak lineBreak)
{
Segment breakSegment = new(lineBreak);
RenderSegmentSpan breakSegmentSpan = new(breakSegment, 0, 0, 0, 0, 0, 0);
lineSegmentSpans.Add(breakSegmentSpan);
MoveToNextLine(currentLineWrapped: false);
}
else if (inline is Run run)
{
float characterSpacing = (float)run.FontSize * run.CharacterSpacing / 1000;
foreach (var segment in run.Segments)
{
// TODO: After bidi is implemented, consider that adjacent segments may not have a word break or new line between them but may just
// switch direction and thus must appear together without wrapping. We don't need to worry about this for now since every segment
// ends in either a word break or line break
// Exclude leading spaces at the start of the line only if the previous line ended because it was wrapped and not because of a line break
int start = x == 0 && previousLineWrapped ? segment.LeadingSpaces : 0;
BeginSegmentFitting:
if (maxLines > 0 && _renderLines.Count == maxLines)
{
goto MaxLinesHit;
}
float remainingWidth = availableWidth - x;
(int length, float width) = GetSegmentRenderInfo(segment, start, characterSpacing);
// Check if whole segment fits
if (width <= remainingWidth)
{
// Add in as many trailing spaces as possible
float widthWithoutTrailingSpaces = width;
int end = segment.LineBreakAfter ? segment.Glyphs.Count - 1 : segment.Glyphs.Count;
int trailingSpaces = 0;
while (start + length < end &&
(width + GetGlyphWidthWithSpacing(segment.Glyphs[length], characterSpacing)) is var newWidth &&
newWidth <= remainingWidth)
{
width = newWidth;
length++;
trailingSpaces++;
}
RenderSegmentSpan segmentSpan = new(segment, start, length, trailingSpaces, characterSpacing, width, widthWithoutTrailingSpaces);
lineSegmentSpans.Add(segmentSpan);
x += width;
if (segment.LineBreakAfter)
{
MoveToNextLine(currentLineWrapped: false);
}
else if (length < end)
{
MoveToNextLine(currentLineWrapped: true);
}
continue;
}
// Whole segment does not fit so tack on as many leading spaces as possible
if (start == 0 && segment.LeadingSpaces > 0)
{
int spaces = 0;
width = 0;
if (x == 0)
{
// minimum 1 space if this is the start of the line
spaces = 1;
width = GetGlyphWidthWithSpacing(segment.Glyphs[0], characterSpacing);
}
while (spaces < segment.LeadingSpaces &&
(width + GetGlyphWidthWithSpacing(segment.Glyphs[spaces], characterSpacing)) is var newWidth &&
newWidth < remainingWidth)
{
width = newWidth;
spaces++;
}
if (width > 0)
{
RenderSegmentSpan segmentSpan = new(segment, 0, spaces, 0, characterSpacing, width, 0);
lineSegmentSpans.Add(segmentSpan);
x += width;
start = segment.LeadingSpaces;
}
}
if (x > 0)
{
// There is content on this line and the segment did not fit so wrap to the next line and retry adding the segment
MoveToNextLine(currentLineWrapped: true);
goto BeginSegmentFitting;
}
// There is no content on the line so wrap the segment according to the wrapping mode.
if (wrapping == TextWrapping.WrapWholeWords)
{
// Put the whole segment on the line and move to the next line.
RenderSegmentSpan segmentSpan = new(segment, start, length, segment.TrailingSpaces, characterSpacing, width, width);
lineSegmentSpans.Add(segmentSpan);
x += width;
MoveToNextLine(currentLineWrapped: !segment.LineBreakAfter);
}
else // wrapping == TextWrapping.Wrap
{
// Put as much of the segment on this line as possible then continue fitting the rest of the segment on the next line
length = 1;
width = GetGlyphWidthWithSpacing(segment.Glyphs[start], characterSpacing);
while (start + length < segment.Glyphs.Count
&& (width + GetGlyphWidthWithSpacing(segment.Glyphs[start + length], characterSpacing)) is var newWidth
&& newWidth < remainingWidth)
{
width = newWidth;
length++;
}
RenderSegmentSpan segmentSpan = new(segment, start, length, 0, characterSpacing, width, width);
lineSegmentSpans.Add(segmentSpan);
x += width;
start += length;
MoveToNextLine(currentLineWrapped: true);
goto BeginSegmentFitting;
}
}
}
}
if (lineSegmentSpans.Count != 0)
{
MoveToNextLine(false);
}
MaxLinesHit:
if (_renderLines.Count == 0)
{
_lastDesiredSize = new Size(0, 0);
}
else
{
_lastDesiredSize = new Size(widestLineWidth, height);
}
return _lastDesiredSize;
// Local functions
static float GetGlyphWidthWithSpacing(GlyphInfo glyph, float characterSpacing)
{
return glyph.AdvanceX > 0 ? glyph.AdvanceX + characterSpacing : glyph.AdvanceX;
}
// Gets rendering info for a segment, excluding any trailing spaces.
static (int Length, float Width) GetSegmentRenderInfo(Segment segment, int startGlyph, float characterSpacing)
{
var glyphs = segment.Glyphs;
int end = segment.LineBreakAfter ? glyphs.Count - 1 : glyphs.Count;
end -= segment.TrailingSpaces;
float width = 0;
for (int i = startGlyph; i < end; i++)
{
width += GetGlyphWidthWithSpacing(glyphs[i], characterSpacing);
}
return (end - startGlyph, width);
}
void MoveToNextLine(bool currentLineWrapped)
{
var renderLine = new RenderLine(lineSegmentSpans, lineStackingStrategy, lineHeight, _renderLines.Count == 0, currentLineWrapped);
_renderLines.Add(renderLine);
lineSegmentSpans.Clear();
if (x > widestLineWidth)
{
widestLineWidth = x;
}
x = 0;
height += renderLine.Height;
previousLineWrapped = currentLineWrapped;
}
}
internal Size Arrange(Size finalSize)
{
_lastArrangedSize = finalSize;
if (!_invalidationPending &&
finalSize.Width <= _lastMeasuredWidth &&
finalSize.Width >= _lastDesiredSize.Width)
{
return _lastDesiredSize;
}
return Measure(finalSize);
}
internal void InvalidateMeasure()
{
// Mark invalidation as pending, but temporarily keep
// the least last measured width, last desired size, and
// last arranged size, so that asynchronous rendering can still
// use them to render properly.
_invalidationPending = true;
}
/// <summary>
/// Renders a block-level inline collection, i.e. one that belongs to a TextBlock (or Paragraph, in the future).
/// </summary>
internal void Draw(in DrawingSession session)
{
if (_renderLines.Count == 0)
{
return;
}
var canvas = session.Surface.Canvas;
var parent = (IBlock)_collection.GetParent();
var alignment = parent.TextAlignment;
if (parent.FlowDirection == FlowDirection.RightToLeft)
{
alignment = alignment switch
{
TextAlignment.Left => TextAlignment.Right,
TextAlignment.Right => TextAlignment.Left,
_ => alignment,
};
}
float y = 0;
foreach (var line in _renderLines)
{
// TODO: (Performance) Stop rendering when the lines exceed the available height
(float x, float justifySpaceOffset) = line.GetOffsets((float)_lastArrangedSize.Width, alignment);
y += line.Height;
float baselineOffsetY = line.BaselineOffsetY;
for (int s = 0; s < line.RenderOrderedSegmentSpans.Count; s++)
{
var segmentSpan = line.RenderOrderedSegmentSpans[s];
if (segmentSpan.GlyphsLength == 0)
{
continue;
}
var segment = segmentSpan.Segment;
var inline = segment.Inline;
var fontInfo = inline.FontInfo;
var paint = inline.Paint;
if (segment.FallbackFont is FontDetails fallback)
{
paint = segment.Paint!;
fontInfo = fallback;
}
if (inline.Foreground is SolidColorBrush scb)
{
paint.Color = new SKColor(
red: scb.Color.R,
green: scb.Color.G,
blue: scb.Color.B,
alpha: (byte)(scb.Color.A * scb.Opacity * session.Filters.Opacity));
}
var decorations = inline.TextDecorations;
const TextDecorations allDecorations = TextDecorations.Underline | TextDecorations.Strikethrough;
if ((decorations & allDecorations) != 0)
{
var metrics = fontInfo.SKFontMetrics;
float width = s == line.RenderOrderedSegmentSpans.Count - 1 ? segmentSpan.WidthWithoutTrailingSpaces : segmentSpan.Width;
if ((decorations & TextDecorations.Underline) != 0)
{
// TODO: what should default thickness/position be if metrics does not contain it?
float yPos = y + baselineOffsetY + (metrics.UnderlinePosition ?? 0);
DrawDecoration(canvas, x, yPos, width, metrics.UnderlineThickness ?? 1, paint);
}
if ((decorations & TextDecorations.Strikethrough) != 0)
{
// TODO: what should default thickness/position be if metrics does not contain it?
float yPos = y + baselineOffsetY + (metrics.StrikeoutPosition ?? fontInfo.SKFontSize / -2);
DrawDecoration(canvas, x, yPos, width, metrics.StrikeoutThickness ?? 1, paint);
}
}
var run = _textBlobBuilder.AllocatePositionedRun(fontInfo.SKFont, segmentSpan.GlyphsLength);
var glyphs = run.GetGlyphSpan();
var positions = run.GetPositionSpan();
if (segment.Direction == FlowDirection.LeftToRight)
{
for (int i = 0; i < segmentSpan.GlyphsLength; i++)
{
var glyphInfo = segment.Glyphs[segmentSpan.GlyphsStart + i];
if (glyphInfo.AdvanceX > 0)
{
x += segmentSpan.CharacterSpacing;
}
glyphs[i] = glyphInfo.GlyphId;
positions[i] = new SKPoint(x + glyphInfo.OffsetX - segmentSpan.CharacterSpacing, glyphInfo.OffsetY);
x += glyphInfo.AdvanceX;
}
}
else // FlowDirection.RightToLeft
{
// Enumerate clusters in reverse order to draw left-to-right
for (int i = segmentSpan.GlyphsLength - 1; i >= 0; i--)
{
int cluster = segment.Glyphs[segmentSpan.GlyphsStart + i].Cluster;
int clusterGlyphCount = 1;
while (i > 0 && segment.Glyphs[segmentSpan.GlyphsStart + i - 1].Cluster == cluster)
{
i--;
clusterGlyphCount++;
}
for (int j = i; j < i + clusterGlyphCount; j++)
{
var glyphInfo = segment.Glyphs[segmentSpan.GlyphsStart + j];
if (glyphInfo.AdvanceX > 0)
{
x += segmentSpan.CharacterSpacing;
}
glyphs[j] = glyphInfo.GlyphId;
positions[j] = new SKPoint(x + glyphInfo.OffsetX, glyphInfo.OffsetY);
x += glyphInfo.AdvanceX;
}
}
}
using var textBlob = _textBlobBuilder.Build();
canvas.DrawText(textBlob, 0, y + baselineOffsetY, paint);
x += justifySpaceOffset * segmentSpan.TrailingSpaces;
}
}
static void DrawDecoration(SKCanvas canvas, float x, float y, float width, float thickness, SKPaint paint)
{
paint.StrokeWidth = thickness;
paint.IsStroke = true;
canvas.DrawLine(x, y, x + width, y, paint);
paint.IsStroke = false;
}
}
internal RenderLine? GetRenderLineAt(double y, bool extendedSelection)
{
if (_renderLines.Count == 0)
{
return null;
}
RenderLine line;
float lineY = 0;
int i = 0;
do
{
line = _renderLines[i++];
lineY += line.Height;
if (y <= lineY && (extendedSelection || y >= lineY - line.Height))
{
return line;
}
} while (i < _renderLines.Count);
return extendedSelection ? line : null;
}
internal RenderSegmentSpan? GetRenderSegmentSpanAt(Point point, bool extendedSelection)
{
var parent = (IBlock)_collection.GetParent();
var line = GetRenderLineAt(point.Y, extendedSelection);
if (line == null)
{
return null;
}
RenderSegmentSpan span;
(float spanX, float justifySpaceOffset) = line.GetOffsets((float)_lastArrangedSize.Width, parent.TextAlignment);
int i = 0;
do
{
span = line.RenderOrderedSegmentSpans[i++];
spanX += span.Width;
if (point.X <= spanX && (extendedSelection || point.X >= spanX - span.Width))
{
return span;
}
spanX += justifySpaceOffset * span.TrailingSpaces;
} while (i < line.RenderOrderedSegmentSpans.Count);
return extendedSelection ? span : null;
}
}
}