File: CaretRectComputation.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (369 lines) | stat: -rw-r--r-- 15,268 bytes parent folder | download | duplicates (6)
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
/*
 * Copyright (C) 2020 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "CaretRectComputation.h"

#include "Editing.h"
#include "InlineIteratorBoxInlines.h"
#include "InlineIteratorLineBox.h"
#include "InlineIteratorTextBox.h"
#include "InlineIteratorTextBoxInlines.h"
#include "InlineIteratorSVGTextBox.h"
#include "LayoutIntegrationLineLayout.h"
#include "LineSelection.h"
#include "RenderBlockFlow.h"
#include "RenderBoxInlines.h"
#include "RenderBoxModelObjectInlines.h"
#include "RenderInline.h"
#include "RenderLineBreak.h"
#include "RenderSVGInlineText.h"
#include "RenderText.h"

namespace WebCore {

int caretWidth()
{
#if PLATFORM(IOS_FAMILY)
    return 2; // This value should be kept in sync with UIKit. See <rdar://problem/15580601>.
#elif PLATFORM(MAC) && HAVE(REDESIGNED_TEXT_CURSOR)
    return redesignedTextCursorEnabled() ? 2 : 1;
#else
    return 1;
#endif
}

static LayoutRect computeCaretRectForEmptyElement(const RenderBoxModelObject& renderer, LayoutUnit logicalWidth, LayoutUnit textIndentOffset, CaretRectMode caretRectMode)
{
    ASSERT(!renderer.firstChild() || renderer.firstChild()->isPseudoElement());

    // FIXME: This does not take into account either :first-line or :first-letter
    // However, as soon as some content is entered, the line boxes will be
    // constructed and this kludge is not called any more. So only the caret size
    // of an empty :first-line'd block is wrong. I think we can live with that.
    const RenderStyle& currentStyle = renderer.firstLineStyle();
    const WritingMode writingMode = currentStyle.writingMode();

    enum CaretAlignment { AlignLogicalLeft, AlignLogicalRight, AlignCenter };
    CaretAlignment alignment;
    switch (currentStyle.textAlign()) {
    case TextAlignMode::Left:
    case TextAlignMode::WebKitLeft:
        alignment = writingMode.isLogicalLeftLineLeft()
            ? AlignLogicalLeft : AlignLogicalRight;
        break;
    case TextAlignMode::Center:
    case TextAlignMode::WebKitCenter:
        alignment = AlignCenter;
        break;
    case TextAlignMode::Right:
    case TextAlignMode::WebKitRight:
        alignment = writingMode.isLogicalLeftLineLeft()
            ? AlignLogicalRight : AlignLogicalLeft;
        break;
    case TextAlignMode::Justify:
    case TextAlignMode::Start:
        alignment = writingMode.isLogicalLeftInlineStart()
            ? AlignLogicalLeft : AlignLogicalRight;
        break;
    case TextAlignMode::End:
        alignment = writingMode.isLogicalLeftInlineStart()
            ? AlignLogicalRight : AlignLogicalLeft;
        break;
    }

    LayoutUnit x = renderer.borderAndPaddingLogicalLeft();
    LayoutUnit maxX = logicalWidth - renderer.borderAndPaddingLogicalRight();

    switch (alignment) {
    case AlignLogicalLeft:
        if (writingMode.isLogicalLeftInlineStart())
            x += textIndentOffset;
        break;
    case AlignCenter:
        x = (x + maxX) / 2;
        if (writingMode.isLogicalLeftInlineStart())
            x += textIndentOffset / 2;
        else
            x -= textIndentOffset / 2;
        break;
    case AlignLogicalRight:
        x = maxX - caretWidth();
        if (!writingMode.isLogicalLeftInlineStart())
            x -= textIndentOffset;
        break;
    }
    x = std::min(x, std::max<LayoutUnit>(maxX - caretWidth(), 0));

    auto lineHeight = renderer.lineHeight(true, writingMode.isHorizontal() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
    auto height = std::min(lineHeight, LayoutUnit { currentStyle.metricsOfPrimaryFont().height() });
    auto y = renderer.borderAndPaddingBefore() + (lineHeight > height ? (lineHeight - height) / 2 : LayoutUnit { });

    auto rect = LayoutRect(x, y, caretWidth(), height);

    if (caretRectMode == CaretRectMode::ExpandToEndOfLine)
        rect.shiftMaxXEdgeTo(logicalWidth);

    return writingMode.isHorizontal() ? rect : rect.transposedRect();
}

static LayoutRect computeCaretRectForLinePosition(const InlineIterator::LineBoxIterator& lineBox, float logicalLeftPosition, CaretRectMode caretRectMode)
{
    auto& root = lineBox->formattingContextRoot();
    auto writingMode = root.writingMode();
    auto lineSelectionRect = LineSelection::logicalRect(*lineBox);

    int height = lineSelectionRect.height();
    int top = lineSelectionRect.y();

    // Distribute the caret's width to either side of the offset.
    float left = logicalLeftPosition;
    int caretWidthLeftOfOffset = caretWidth() / 2;
    left -= caretWidthLeftOfOffset;
    int caretWidthRightOfOffset = caretWidth() - caretWidthLeftOfOffset;
    left = roundf(left);

    float lineLeft = lineSelectionRect.x();
    float lineRight = lineSelectionRect.maxX();

    bool rightAligned = false;
    switch (root.style().textAlign()) {
    case TextAlignMode::Right:
    case TextAlignMode::WebKitRight:
        rightAligned = writingMode.isLogicalLeftLineLeft();
        break;
    case TextAlignMode::Left:
    case TextAlignMode::WebKitLeft:
    case TextAlignMode::Center:
    case TextAlignMode::WebKitCenter:
        rightAligned = !writingMode.isLogicalLeftLineLeft();
        break;
    case TextAlignMode::Justify:
    case TextAlignMode::Start:
        rightAligned = !writingMode.isLogicalLeftInlineStart();
        break;
    case TextAlignMode::End:
        rightAligned = writingMode.isLogicalLeftInlineStart();
        break;
    }

    float leftEdge = std::min<float>(0, lineLeft);
    float rightEdge = std::max<float>(root.logicalWidth(), lineRight);

    if (rightAligned) {
        left = std::max(left, leftEdge);
        left = std::min(left, lineRight - caretWidth());
    } else {
        left = std::min(left, rightEdge - caretWidthRightOfOffset);
        left = std::max(left, lineLeft);
    }

    auto rect = IntRect(left, top, caretWidth(), height);

    if (caretRectMode == CaretRectMode::ExpandToEndOfLine)
        rect.shiftMaxXEdgeTo(lineRight);

    return writingMode.isHorizontal() ? rect : rect.transposedRect();
}

static LayoutRect computeCaretRectForText(const InlineBoxAndOffset& boxAndOffset, CaretRectMode caretRectMode)
{
    if (!boxAndOffset.box)
        return { };

    auto& textBox = downcast<InlineIterator::TextBoxIterator>(boxAndOffset.box);

    auto positionForOffset = [&](auto offset) -> float {
        ASSERT(offset >= textBox->start());
        ASSERT(offset <= textBox->end());

        if (textBox->isLineBreak())
            return 0;

        auto [startOffset, endOffset] = [&] {
            if (textBox->direction() == TextDirection::RTL)
                return std::pair { textBox->selectableRange().clamp(offset), textBox->length() };
            return std::pair { 0u, textBox->selectableRange().clamp(offset) };
        }();

        LayoutRect selectionRect;
        // Get logical x coordinate relative to text run.
        auto textRun = textBox->textRun(InlineIterator::TextRunMode::Editing);
        textBox->fontCascade().adjustSelectionRectForText(textBox->renderer().canUseSimplifiedTextMeasuring().value_or(false), textRun, selectionRect, startOffset, endOffset);
        selectionRect.shiftXEdgeTo(selectionRect.maxX());

        // Convert to box coordinates.
        if (!textBox->writingMode().isLogicalLeftLineLeft())
            selectionRect.setX(textBox->logicalWidth() - selectionRect.x());
        selectionRect.move(textBox->logicalLeftIgnoringInlineDirection(), 0);

        // Finally, snap.
        return snapRectToDevicePixelsWithWritingDirection(selectionRect, textBox->renderer().document().deviceScaleFactor(), textRun.ltr()).x();
    };

    return computeCaretRectForLinePosition(textBox->lineBox(), positionForOffset(boxAndOffset.offset), caretRectMode);
}

static LayoutRect computeCaretRectForLineBreak(const InlineBoxAndOffset& boxAndOffset, CaretRectMode caretRectMode)
{
    ASSERT(!boxAndOffset.offset);

    if (!boxAndOffset.box)
        return { };

    auto lineBox = boxAndOffset.box->lineBox();
    auto position = boxAndOffset.box->writingMode().isLogicalLeftLineLeft()
        ? lineBox->contentLogicalLeft()
        : lineBox->contentLogicalRight();
    return computeCaretRectForLinePosition(lineBox, position, caretRectMode);
}

static LayoutRect computeCaretRectForSVGInlineText(const InlineBoxAndOffset& boxAndOffset, CaretRectMode)
{
    auto box = boxAndOffset.box;
    auto caretOffset = boxAndOffset.offset;
    if (!is<InlineIterator::SVGTextBoxIterator>(box))
        return { };

    auto textBox = downcast<InlineIterator::SVGTextBoxIterator>(box);
    if (!textBox)
        return { };

    if (caretOffset < textBox->start() || caretOffset > textBox->start() + textBox->length())
        return { };

    // Use the edge of the selection rect to determine the caret rect.
    if (caretOffset < textBox->start() + textBox->length()) {
        LayoutRect rect = textBox->localSelectionRect(caretOffset, caretOffset + 1);
        LayoutUnit x = !textBox->isInlineFlipped() ? rect.x() : rect.maxX();
        return LayoutRect(x, rect.y(), caretWidth(), rect.height());
    }

    LayoutRect rect = textBox->localSelectionRect(caretOffset - 1, caretOffset);
    LayoutUnit x = !textBox->isInlineFlipped() ? rect.maxX() : rect.x();
    return { x, rect.y(), caretWidth(), rect.height() };
}

static LayoutRect computeCaretRectForBox(const RenderBox& renderer, const InlineBoxAndOffset& boxAndOffset, CaretRectMode caretRectMode)
{
    // VisiblePositions at offsets inside containers either a) refer to the positions before/after
    // those containers (tables and select elements) or b) refer to the position inside an empty block.
    // They never refer to children.
    // FIXME: Paint the carets inside empty blocks differently than the carets before/after elements.

    LayoutRect rect(renderer.location(), LayoutSize(caretWidth(), renderer.height()));
    auto writingMode = boxAndOffset.box ? boxAndOffset.box->writingMode() : renderer.writingMode();

    if ((!boxAndOffset.offset) == writingMode.isInlineFlipped())
        rect.move(LayoutSize(renderer.width() - caretWidth(), 0_lu));

    if (boxAndOffset.box) {
        auto lineBox = boxAndOffset.box->lineBox();
        auto top = lineBox->contentLogicalTop();
        rect.setY(top);
        rect.setHeight(lineBox->contentLogicalBottom() - top);
    }

    // If height of box is smaller than font height, use the latter one,
    // otherwise the caret might become invisible.
    //
    // Also, if the box is not a replaced element, always use the font height.
    // This prevents the "big caret" bug described in:
    // <rdar://problem/3777804> Deleting all content in a document can result in giant tall-as-window insertion point
    //
    // FIXME: ignoring :first-line, missing good reason to take care of
    auto fontHeight = renderer.style().metricsOfPrimaryFont().height();
    if (fontHeight > rect.height() || (!renderer.isReplacedOrAtomicInline() && !renderer.isRenderTable()))
        rect.setHeight(fontHeight);

    // Move to local coords
    rect.moveBy(-renderer.location());

    // FIXME: Border/padding should be added for all elements but this workaround
    // is needed because we use offsets inside an "atomic" element to represent
    // positions before and after the element in deprecated editing offsets.
    if (renderer.element() && !(editingIgnoresContent(*renderer.element()) || isRenderedTable(renderer.element()))) {
        rect.setX(rect.x() + renderer.borderLeft() + renderer.paddingLeft());
        rect.setY(rect.y() + renderer.paddingTop() + renderer.borderTop());
    }

    if (caretRectMode == CaretRectMode::ExpandToEndOfLine)
        rect.shiftMaxXEdgeTo(renderer.x() + renderer.width());

    return writingMode.isHorizontal() ? rect : rect.transposedRect();
}

static LayoutRect computeCaretRectForBlock(const RenderBlock& renderer, const InlineBoxAndOffset& boxAndOffset, CaretRectMode caretRectMode)
{
    // Do the normal calculation in most cases.
    if (renderer.firstChild() && !renderer.firstChild()->isPseudoElement())
        return computeCaretRectForBox(renderer, boxAndOffset, caretRectMode);

    return computeCaretRectForEmptyElement(renderer, renderer.logicalWidth(), renderer.textIndentOffset(), caretRectMode);
}

static LayoutRect computeCaretRectForInline(const RenderInline& renderer)
{
    if (renderer.firstChild()) {
        // This condition is possible if the RenderInline is at an editing boundary,
        // i.e. the VisiblePosition is:
        //   <RenderInline editingBoundary=true>|<RenderText> </RenderText></RenderInline>
        // FIXME: need to figure out how to make this return a valid rect, note that
        // there are no line boxes created in the above case.
        return { };
    }

    LayoutRect caretRect = computeCaretRectForEmptyElement(renderer, renderer.borderAndPaddingLogicalWidth(), 0, CaretRectMode::Normal);

    if (auto firstInlineBox = InlineIterator::lineLeftmostInlineBoxFor(renderer))
        caretRect.moveBy(LayoutPoint { firstInlineBox->visualRectIgnoringBlockDirection().location() });

    return caretRect;
}

LayoutRect computeLocalCaretRect(const RenderObject& renderer, const InlineBoxAndOffset& boxAndOffset, CaretRectMode caretRectMode)
{
    if (is<RenderSVGInlineText>(renderer))
        return computeCaretRectForSVGInlineText(boxAndOffset, caretRectMode);

    if (is<RenderText>(renderer))
        return computeCaretRectForText(boxAndOffset, caretRectMode);

    if (is<RenderLineBreak>(renderer))
        return computeCaretRectForLineBreak(boxAndOffset, caretRectMode);

    if (auto* block = dynamicDowncast<RenderBlock>(renderer))
        return computeCaretRectForBlock(*block, boxAndOffset, caretRectMode);

    if (auto* box = dynamicDowncast<RenderBox>(renderer))
        return computeCaretRectForBox(*box, boxAndOffset, caretRectMode);

    if (auto* renderInline = dynamicDowncast<RenderInline>(renderer))
        return computeCaretRectForInline(*renderInline);

    return { };
}

};