summaryrefslogtreecommitdiffstats
path: root/Source/WebKit/blackberry/WebKitSupport/DOMSupport.cpp
blob: 433b8cdc99c69b6dc4068b29d4a025e9b2a2f19b (plain)
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
/*
 * Copyright (C) 2011, 2012 Research In Motion Limited. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"
#include "DOMSupport.h"

#include "FloatQuad.h"
#include "Frame.h"
#include "FrameView.h"
#include "HTMLFormElement.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HTMLTextAreaElement.h"
#include "Node.h"
#include "Range.h"
#include "RenderObject.h"
#include "RenderText.h"
#include "RenderTextControl.h"
#include "TextIterator.h"
#include "VisibleSelection.h"

#include "htmlediting.h"
#include "visible_units.h"

#include <limits>

#include <wtf/text/WTFString.h>

using WTF::Vector;

using namespace WebCore;

namespace BlackBerry {
namespace WebKit {
namespace DOMSupport {

void visibleTextQuads(const VisibleSelection& selection, Vector<FloatQuad>& quads)
{
    if (!selection.isRange())
        return;
    ASSERT(selection.firstRange());

    visibleTextQuads(*(selection.firstRange()), quads, true /* useSelectionHeight */);
}

void visibleTextQuads(const Range& range, Vector<FloatQuad>& quads, bool useSelectionHeight)
{
    // Range::textQuads includes hidden text, which we don't want.
    // To work around this, this is a copy of it which skips hidden elements.
    Node* startContainer = range.startContainer();
    Node* endContainer = range.endContainer();

    if (!startContainer || !endContainer)
        return;

    Node* stopNode = range.pastLastNode();
    for (Node* node = range.firstNode(); node != stopNode; node = node->traverseNextNode()) {
        RenderObject* r = node->renderer();
        if (!r || !r->isText())
            continue;

        if (r->style()->visibility() != VISIBLE)
            continue;

        RenderText* renderText = toRenderText(r);
        int startOffset = node == startContainer ? range.startOffset() : 0;
        int endOffset = node == endContainer ? range.endOffset() : std::numeric_limits<int>::max();
        renderText->absoluteQuadsForRange(quads, startOffset, endOffset, useSelectionHeight);
    }
}

bool isTextInputElement(Element* element)
{
    return element->isTextFormControl()
           || element->hasTagName(HTMLNames::textareaTag)
           || element->isContentEditable();
}

bool isPasswordElement(const Element* element)
{
    return element && element->hasTagName(HTMLNames::inputTag)
           && static_cast<const HTMLInputElement*>(element)->isPasswordField();
}

WTF::String inputElementText(Element* element)
{
    if (!element)
        return WTF::String();

    WTF::String elementText;
    if (element->hasTagName(HTMLNames::inputTag)) {
        const HTMLInputElement* inputElement = static_cast<const HTMLInputElement*>(element);
        elementText = inputElement->value();
    } else if (element->hasTagName(HTMLNames::textareaTag)) {
        const HTMLTextAreaElement* inputElement = static_cast<const HTMLTextAreaElement*>(element);
        elementText = inputElement->value();
    } else if (element->isContentEditable()) {
        RefPtr<Range> rangeForNode = rangeOfContents(element);
        elementText = rangeForNode.get()->text();
    }
    return elementText;
}

WTF::String webWorksContext(const WebCore::Element* element)
{
    if (!element)
        return WTF::String();

    DEFINE_STATIC_LOCAL(QualifiedName, webworksContextAttr, (nullAtom, "data-blackberry-webworks-context", nullAtom));
    if (element->fastHasAttribute(webworksContextAttr))
        return element->fastGetAttribute(webworksContextAttr);

    return WTF::String();
}

bool isElementTypePlugin(const Element* element)
{
    if (!element)
        return false;

    if (element->hasTagName(HTMLNames::objectTag)
        || element->hasTagName(HTMLNames::embedTag)
        || element->hasTagName(HTMLNames::appletTag))
        return true;

    return false;
}

HTMLTextFormControlElement* toTextControlElement(Node* node)
{
    if (!(node && node->isElementNode()))
        return 0;

    Element* element = static_cast<Element*>(node);
    if (!element->isFormControlElement())
        return 0;

    HTMLFormControlElement* formElement = static_cast<HTMLFormControlElement*>(element);
    if (!formElement->isTextFormControl())
        return 0;

    return static_cast<HTMLTextFormControlElement*>(formElement);
}

bool isPopupInputField(const Element* element)
{
    return isDateTimeInputField(element) || isColorInputField(element);
}

bool isDateTimeInputField(const Element* element)
{
    if (!element->hasTagName(HTMLNames::inputTag))
        return false;

    const HTMLInputElement* inputElement = static_cast<const HTMLInputElement*>(element);

    // The following types have popup's.
    if (inputElement->isDateControl()
        || inputElement->isDateTimeControl()
        || inputElement->isDateTimeLocalControl()
        || inputElement->isTimeControl()
        || inputElement->isMonthControl())
            return true;

    return false;
}

bool isColorInputField(const Element* element)
{
    if (!element->hasTagName(HTMLNames::inputTag))
        return false;

    const HTMLInputElement* inputElement = static_cast<const HTMLInputElement*>(element);

#if ENABLE(INPUT_TYPE_COLOR)
    if (inputElement->isColorControl())
        return true;
#endif

    return false;
}

// This is a Tristate return to allow us to override name matching when
// the attribute is expressly requested for a field. Default indicates
// that the setting is On which is the default but not expressly requested
// for the element being checked. On indicates that it is directly added
// to the element.
AttributeState elementSupportsAutocorrect(const Element* element)
{
    DEFINE_STATIC_LOCAL(QualifiedName, autocorrectAttr, (nullAtom, "autocorrect", nullAtom));
    return elementAttributeState(element, autocorrectAttr);
}

AttributeState elementSupportsAutocomplete(const Element* element)
{
    return elementAttributeState(element, HTMLNames::autocompleteAttr);
}

AttributeState elementSupportsSpellCheck(const Element* element)
{
    return elementAttributeState(element, HTMLNames::spellcheckAttr);
}

AttributeState elementAttributeState(const Element* element, const QualifiedName& attributeName)
{
    // First we check the input item itself. If the attribute is not defined,
    // we check its parent form.
    if (element->fastHasAttribute(attributeName)) {
        AtomicString attributeString = element->fastGetAttribute(attributeName);
        if (equalIgnoringCase(attributeString, "off"))
            return Off;
        if (equalIgnoringCase(attributeString, "on"))
            return On;
        // If we haven't returned, it wasn't set properly. Check the form for an explicit setting
        // because the attribute was provided, but invalid.
    }
    if (element->isFormControlElement()) {
        const HTMLFormControlElement* formElement = static_cast<const HTMLFormControlElement*>(element);
        if (formElement->form() && formElement->form()->fastHasAttribute(attributeName)) {
            AtomicString attributeString = formElement->form()->fastGetAttribute(attributeName);
            if (equalIgnoringCase(attributeString, "off"))
                return Off;
            if (equalIgnoringCase(attributeString, "on"))
                return On;
        }
    }

    return Default;
}

// Check if this is an input field that will be focused & require input support.
bool isTextBasedContentEditableElement(Element* element)
{
    if (!element)
        return false;

    if (element->isReadOnlyFormControl() || !element->isEnabledFormControl())
        return false;

    if (isPopupInputField(element))
        return false;

    return element->isTextFormControl() || element->isContentEditable();
}

IntRect transformedBoundingBoxForRange(const Range& range)
{
    // Based on Range::boundingBox, which does not handle transforms, and
    // RenderObject::absoluteBoundingBoxRect, which does.
    IntRect result;
    Vector<FloatQuad> quads;
    visibleTextQuads(range, quads);
    const size_t n = quads.size();
    for (size_t i = 0; i < n; ++i)
        result.unite(quads[i].enclosingBoundingBox());

    return result;
}

VisibleSelection visibleSelectionForInputElement(Element* element)
{
    return visibleSelectionForRangeInputElement(element, 0, inputElementText(element).length());
}

VisibleSelection visibleSelectionForRangeInputElement(Element* element, int start, int end)
{
    if (DOMSupport::toTextControlElement(element)) {
        RenderTextControl* textRender = toRenderTextControl(element->renderer());
        if (!textRender)
            return VisibleSelection();

        VisiblePosition startPosition = textRender->visiblePositionForIndex(start);
        VisiblePosition endPosition;
        if (start == end)
            endPosition = startPosition;
        else
            endPosition = textRender->visiblePositionForIndex(end);

        return VisibleSelection(startPosition, endPosition);
    }

    // Must be content editable, generate the range.
    RefPtr<Range> selectionRange = TextIterator::rangeFromLocationAndLength(element, start, end - start);

    if (!selectionRange)
        return VisibleSelection();

    if (start == end)
        return VisibleSelection(selectionRange.get()->startPosition(), DOWNSTREAM);

    VisiblePosition visibleStart(selectionRange->startPosition(), DOWNSTREAM);
    VisiblePosition visibleEnd(selectionRange->endPosition(), SEL_DEFAULT_AFFINITY);

    return VisibleSelection(visibleStart, visibleEnd);
}

Node* DOMContainerNodeForPosition(const Position& position)
{
    Node* nodeAtPos = position.containerNode();
    if (nodeAtPos && nodeAtPos->isInShadowTree())
        nodeAtPos = nodeAtPos->shadowAncestorNode();

    return nodeAtPos;
}

bool isPositionInNode(Node* node, const Position& position)
{
    if (!node)
        return false;

    Node* domNodeAtPos = DOMContainerNodeForPosition(position);
    if (!domNodeAtPos)
        return false;

    int offset = 0;
    if (domNodeAtPos == position.containerNode())
        offset = position.computeOffsetInContainerNode();

    RefPtr<Range> rangeForNode = rangeOfContents(node);
    int ec;

    return rangeForNode->isPointInRange(domNodeAtPos, offset, ec);
}

static bool matchesReservedStringEmail(const AtomicString& string)
{
    return string.contains("email", false /* caseSensitive */);
}

static bool matchesReservedStringUrl(const AtomicString& string)
{
    return equalIgnoringCase("url", string);
}

bool elementIdOrNameIndicatesEmail(const HTMLInputElement* inputElement)
{
    if (!inputElement)
        return false;

    if (matchesReservedStringEmail(inputElement->getIdAttribute()))
        return true;

    if (inputElement->fastHasAttribute(HTMLNames::nameAttr)) {
        if (matchesReservedStringEmail(inputElement->fastGetAttribute(HTMLNames::nameAttr)))
            return true;
    }

    return false;
}

bool elementIdOrNameIndicatesUrl(const HTMLInputElement* inputElement)
{
    if (!inputElement)
        return false;

    if (matchesReservedStringUrl(inputElement->getIdAttribute()))
        return true;

    if (inputElement->fastHasAttribute(HTMLNames::nameAttr)) {
        if (matchesReservedStringUrl(inputElement->fastGetAttribute(HTMLNames::nameAttr)))
            return true;
    }

    return false;
}

static bool matchesReservedStringPreventingAutocomplete(const AtomicString& string)
{
    if (matchesReservedStringEmail(string)
        || matchesReservedStringUrl(string)
        || string.contains("user", false /* caseSensitive */)
        || string.contains("name", false /* caseSensitive */)
        || string.contains("login", false /* caseSensitive */))
        return true;

    return false;
}

// This checks to see if an input element has a name or id attribute set to
// username or email. These are rough checks to avoid major sites that use
// login fields as input type=text and auto correction interfers with.
bool elementIdOrNameIndicatesNoAutocomplete(const Element* element)
{
    if (!element->hasTagName(HTMLNames::inputTag))
        return false;

    AtomicString idAttribute = element->getIdAttribute();
    if (matchesReservedStringPreventingAutocomplete(idAttribute))
        return true;

    if (element->fastHasAttribute(HTMLNames::nameAttr)) {
        AtomicString nameAttribute = element->fastGetAttribute(HTMLNames::nameAttr);
        if (matchesReservedStringPreventingAutocomplete(nameAttribute))
            return true;
    }

    return false;
}

bool elementPatternIndicatesNumber(const HTMLInputElement* inputElement)
{
    return elementPatternMatches("[0-9]", inputElement);
}

bool elementPatternIndicatesHexadecimal(const HTMLInputElement* inputElement)
{
    return elementPatternMatches("[0-9a-fA-F]", inputElement);
}

bool elementPatternMatches(const char* pattern, const HTMLInputElement* inputElement)
{
    WTF::String patternString(pattern);
    if (!inputElement || patternString.isEmpty())
        return false;

    if (inputElement->fastHasAttribute(HTMLNames::patternAttr)) {
        WTF::String patternAttribute = inputElement->fastGetAttribute(HTMLNames::patternAttr);
        if (patternAttribute.startsWith(patternString)) {
            // The pattern is for hexadecimal, make sure nothing else is permitted.

            // Check if it was an exact match.
            if (patternAttribute.length() == patternString.length())
                return true;

            // Check for *
            if (patternAttribute.length() == patternString.length() + 1 && patternAttribute[patternString.length()] == '*')
                return true;

            // Is the regex specifying a character count?
            if (patternAttribute[patternString.length()] != '{' || !patternAttribute.endsWith("}"))
                return false;

            // Make sure the number in the regex is actually a number.
            unsigned count = 0;
            patternString = patternString + "{%d}";
            return (sscanf(patternAttribute.latin1().data(), patternString.latin1().data() + '\0', &count) == 1) && count > 0;
        }
    }
    return false;
}

IntPoint convertPointToFrame(const Frame* sourceFrame, const Frame* targetFrame, const IntPoint& point, const bool clampToTargetFrame)
{
    ASSERT(sourceFrame && targetFrame);
    if (sourceFrame == targetFrame)
        return point;

    ASSERT(sourceFrame->view() && targetFrame->view());
    ASSERT(targetFrame->tree());

    Frame* targetFrameParent = targetFrame->tree()->parent();
    IntRect targetFrameRect = targetFrame->view()->frameRect();
    IntPoint targetPoint = point;

    // Convert the target frame rect to source window content coordinates. This is only required
    // if the parent frame is not the source. If the parent is the source, subframeRect
    // is already in source content coordinates.
    if (targetFrameParent != sourceFrame)
        targetFrameRect = sourceFrame->view()->windowToContents(targetFrameParent->view()->contentsToWindow(targetFrameRect));

    // Requested point is outside of target frame, return InvalidPoint.
    if (clampToTargetFrame && !targetFrameRect.contains(targetPoint))
        targetPoint = IntPoint(targetPoint.x() < targetFrameRect.x() ? targetFrameRect.x() : std::min(targetPoint.x(), targetFrameRect.maxX()),
                targetPoint.y() < targetFrameRect.y() ? targetFrameRect.y() : std::min(targetPoint.y(), targetFrameRect.maxY()));
    else if (!targetFrameRect.contains(targetPoint))
        return InvalidPoint;

    // Adjust the points to be relative to the target.
    return targetFrame->view()->windowToContents(sourceFrame->view()->contentsToWindow(targetPoint));
}

VisibleSelection visibleSelectionForClosestActualWordStart(const VisibleSelection& selection)
{
    // VisibleSelection validation has a special case when the caret is at the end of a paragraph where
    // it selects the paragraph marker. As well, if the position is at the end of a word, it will select
    // only the space between words. We want to select an actual word so we move the selection to
    // the start of the leftmost word if the character after the selection point is whitespace.
    if (selection.selectionType() != VisibleSelection::RangeSelection && isWhitespace(selection.visibleStart().characterAfter())) {
        VisibleSelection leftSelection(previousWordPosition(selection.start()));
        bool leftSelectionIsOnWord = !isWhitespace(leftSelection.visibleStart().characterAfter());

        VisibleSelection rangeSelection(endOfWord(leftSelection.start()), selection.visibleStart());
        int leftDistance = TextIterator::rangeLength(rangeSelection.toNormalizedRange().get());

        VisibleSelection rightSelection(nextWordPosition(selection.start()));
        rightSelection = previousWordPosition(rightSelection.start());
        bool rightSelectionIsOnWord = !isWhitespace(rightSelection.visibleStart().characterAfter());

        rangeSelection = VisibleSelection(rightSelection.visibleStart(), selection.visibleStart());
        int rightDistance = TextIterator::rangeLength(rangeSelection.toNormalizedRange().get());

        // Make sure we found an actual word. If not, return the original selection.
        if (!leftSelectionIsOnWord && !rightSelectionIsOnWord)
            return selection;

        if (!rightSelectionIsOnWord || (leftSelectionIsOnWord && leftDistance < rightDistance)) {
            // Left is closer or right is invalid.
            return leftSelection;
        }

        // Right is closer or equal, or left was invalid.
        return rightSelection;
    }

    // No adjustment required.
    return selection;
}

// This function is copied from WebCore/page/Page.cpp.
Frame* incrementFrame(Frame* curr, bool forward, bool wrapFlag)
{
    return forward
        ? curr->tree()->traverseNextWithWrap(wrapFlag)
        : curr->tree()->traversePreviousWithWrap(wrapFlag);
}

} // DOMSupport
} // WebKit
} // BlackBerry