Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / HTMLTextAreaElement.cpp
index 7ea7aa6..59385d8 100644 (file)
 #include "config.h"
 #include "core/html/HTMLTextAreaElement.h"
 
-#include "CSSValueKeywords.h"
-#include "HTMLNames.h"
-#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "bindings/core/v8/ExceptionState.h"
+#include "bindings/core/v8/ExceptionStatePlaceholder.h"
+#include "core/CSSValueKeywords.h"
+#include "core/HTMLNames.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/Text.h"
 #include "core/editing/TextIterator.h"
 #include "core/events/BeforeTextInsertedEvent.h"
 #include "core/events/Event.h"
-#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/LocalFrame.h"
 #include "core/html/FormDataList.h"
 #include "core/html/forms/FormController.h"
+#include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/TextControlInnerElements.h"
-#include "core/frame/Frame.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
 #include "core/rendering/RenderTextControlMultiLine.h"
 #include "platform/text/PlatformLocale.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/StringBuilder.h"
 
-namespace WebCore {
+namespace blink {
 
 using namespace HTMLNames;
 
@@ -81,21 +84,20 @@ HTMLTextAreaElement::HTMLTextAreaElement(Document& document, HTMLFormElement* fo
     , m_cols(defaultCols)
     , m_wrap(SoftWrap)
     , m_isDirty(false)
+    , m_valueIsUpToDate(true)
 {
-    setFormControlValueMatchesRenderer(true);
-    ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(Document& document, HTMLFormElement* form)
+PassRefPtrWillBeRawPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(Document& document, HTMLFormElement* form)
 {
-    RefPtr<HTMLTextAreaElement> textArea = adoptRef(new HTMLTextAreaElement(document, form));
+    RefPtrWillBeRawPtr<HTMLTextAreaElement> textArea = adoptRefWillBeNoop(new HTMLTextAreaElement(document, form));
     textArea->ensureUserAgentShadowRoot();
     return textArea.release();
 }
 
 void HTMLTextAreaElement::didAddUserAgentShadowRoot(ShadowRoot& root)
 {
-    root.appendChild(TextControlInnerTextElement::create(document()));
+    root.appendChild(TextControlInnerEditorElement::create(document()));
 }
 
 const AtomicString& HTMLTextAreaElement::formControlType() const
@@ -114,12 +116,12 @@ void HTMLTextAreaElement::restoreFormControlState(const FormControlState& state)
     setValue(state[0]);
 }
 
-void HTMLTextAreaElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
+void HTMLTextAreaElement::childrenChanged(const ChildrenChange& change)
 {
-    HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
+    HTMLElement::childrenChanged(change);
     setLastChangeWasNotUserEdit();
     if (m_isDirty)
-        setInnerTextValue(value());
+        setInnerEditorValue(value());
     else
         setNonDirtyValue(defaultValue());
 }
@@ -160,7 +162,7 @@ void HTMLTextAreaElement::parseAttribute(const QualifiedName& name, const Atomic
         if (m_rows != rows) {
             m_rows = rows;
             if (renderer())
-                renderer()->setNeedsLayoutAndPrefWidthsRecalc();
+                renderer()->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
         }
     } else if (name == colsAttr) {
         int cols = value.toInt();
@@ -169,7 +171,7 @@ void HTMLTextAreaElement::parseAttribute(const QualifiedName& name, const Atomic
         if (m_cols != cols) {
             m_cols = cols;
             if (renderer())
-                renderer()->setNeedsLayoutAndPrefWidthsRecalc();
+                renderer()->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
         }
     } else if (name == wrapAttr) {
         // The virtual/physical values were a Netscape extension of HTML 3.0, now deprecated.
@@ -184,13 +186,15 @@ void HTMLTextAreaElement::parseAttribute(const QualifiedName& name, const Atomic
         if (wrap != m_wrap) {
             m_wrap = wrap;
             if (renderer())
-                renderer()->setNeedsLayoutAndPrefWidthsRecalc();
+                renderer()->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
         }
     } else if (name == accesskeyAttr) {
         // ignore for the moment
-    } else if (name == maxlengthAttr)
+    } else if (name == maxlengthAttr) {
         setNeedsValidityCheck();
-    else
+    } else if (name == minlengthAttr) {
+        setNeedsValidityCheck();
+    } else
         HTMLTextFormControlElement::parseAttribute(name, value);
 }
 
@@ -238,12 +242,9 @@ bool HTMLTextAreaElement::shouldShowFocusRingOnMouseFocus() const
 
 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
 {
-    if (!restorePreviousSelection || !hasCachedSelection()) {
-        // If this is the first focus, set a caret at the beginning of the text.
-        // This matches some browsers' behavior; see bug 11746 Comment #15.
-        // http://bugs.webkit.org/show_bug.cgi?id=11746#c15
+    if (!restorePreviousSelection)
         setSelectionRange(0, 0);
-    else
+    else
         restoreCachedSelection();
 
     if (document().frame())
@@ -262,21 +263,25 @@ void HTMLTextAreaElement::defaultEventHandler(Event* event)
 
 void HTMLTextAreaElement::handleFocusEvent(Element*, FocusType)
 {
-    if (Frame* frame = document().frame())
+    if (LocalFrame* frame = document().frame())
         frame->spellChecker().didBeginEditing(this);
 }
 
 void HTMLTextAreaElement::subtreeHasChanged()
 {
     setChangedSinceLastFormControlChangeEvent(true);
-    setFormControlValueMatchesRenderer(false);
+    m_valueIsUpToDate = false;
     setNeedsValidityCheck();
+    setAutofilled(false);
 
     if (!focused())
         return;
 
     // When typing in a textarea, childrenChanged is not called, so we need to force the directionality check.
     calculateAndAdjustDirectionality();
+
+    ASSERT(document().isActive());
+    document().frameHost()->chrome().client().didChangeValueInTextField(*this);
 }
 
 void HTMLTextAreaElement::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent* event) const
@@ -288,7 +293,7 @@ void HTMLTextAreaElement::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent*
         return;
     unsigned unsignedMaxLength = static_cast<unsigned>(signedMaxLength);
 
-    const String& currentValue = innerTextValue();
+    const String& currentValue = innerEditorValue();
     unsigned currentLength = computeLengthForSubmission(currentValue);
     if (currentLength + computeLengthForSubmission(event->text()) < unsignedMaxLength)
         return;
@@ -298,7 +303,12 @@ void HTMLTextAreaElement::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent*
     // If the text field has no focus, we don't need to take account of the
     // selection length. The selection is the source of text drag-and-drop in
     // that case, and nothing in the text field will be removed.
-    unsigned selectionLength = focused() ? computeLengthForSubmission(plainText(document().frame()->selection().selection().toNormalizedRange().get())) : 0;
+    unsigned selectionLength = 0;
+    if (focused()) {
+        Position start, end;
+        document().frame()->selection().selection().toNormalizedPositions(start, end);
+        selectionLength = computeLengthForSubmission(plainText(start, end));
+    }
     ASSERT(currentLength >= selectionLength);
     unsigned baseLength = currentLength - selectionLength;
     unsigned appendableLength = unsignedMaxLength > baseLength ? unsignedMaxLength - baseLength : 0;
@@ -314,12 +324,11 @@ String HTMLTextAreaElement::sanitizeUserInputValue(const String& proposedValue,
 
 void HTMLTextAreaElement::updateValue() const
 {
-    if (formControlValueMatchesRenderer())
+    if (m_valueIsUpToDate)
         return;
 
-    ASSERT(renderer());
-    m_value = innerTextValue();
-    const_cast<HTMLTextAreaElement*>(this)->setFormControlValueMatchesRenderer(true);
+    m_value = innerEditorValue();
+    const_cast<HTMLTextAreaElement*>(this)->m_valueIsUpToDate = true;
     const_cast<HTMLTextAreaElement*>(this)->notifyFormStateChanged();
     m_isDirty = true;
     const_cast<HTMLTextAreaElement*>(this)->updatePlaceholderVisibility(false);
@@ -331,21 +340,22 @@ String HTMLTextAreaElement::value() const
     return m_value;
 }
 
-void HTMLTextAreaElement::setValue(const String& value)
+void HTMLTextAreaElement::setValue(const String& value, TextFieldEventBehavior eventBehavior)
 {
-    setValueCommon(value);
+    RefPtrWillBeRawPtr<HTMLTextAreaElement> protector(this);
+    setValueCommon(value, eventBehavior);
     m_isDirty = true;
-    setNeedsValidityCheck();
+    if (document().focusedElement() == this)
+        document().frameHost()->chrome().client().didUpdateTextOfFocusedElementByNonUserInput();
 }
 
 void HTMLTextAreaElement::setNonDirtyValue(const String& value)
 {
-    setValueCommon(value);
+    setValueCommon(value, DispatchNoEvent, SetSeletion);
     m_isDirty = false;
-    setNeedsValidityCheck();
 }
 
-void HTMLTextAreaElement::setValueCommon(const String& newValue)
+void HTMLTextAreaElement::setValueCommon(const String& newValue, TextFieldEventBehavior eventBehavior, SetValueCommonOption setValueOption)
 {
     // Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
     // We normalize line endings coming from JavaScript here.
@@ -353,27 +363,50 @@ void HTMLTextAreaElement::setValueCommon(const String& newValue)
     normalizedValue.replace("\r\n", "\n");
     normalizedValue.replace('\r', '\n');
 
-    // Return early because we don't want to move the caret or trigger other side effects
-    // when the value isn't changing. This matches Firefox behavior, at least.
-    if (normalizedValue == value())
+    // Return early because we don't want to trigger other side effects
+    // when the value isn't changing.
+    // FIXME: Simple early return doesn't match the Firefox ever.
+    // Remove these lines.
+    if (normalizedValue == value()) {
+        if (setValueOption == SetSeletion) {
+            setNeedsValidityCheck();
+            if (isFinishedParsingChildren()) {
+                // Set the caret to the end of the text value except for initialize.
+                unsigned endOfString = m_value.length();
+                setSelectionRange(endOfString, endOfString, SelectionHasNoDirection, ChangeSelectionIfFocused);
+            }
+        }
         return;
+    }
 
     m_value = normalizedValue;
-    setInnerTextValue(m_value);
-    setLastChangeWasNotUserEdit();
+    setInnerEditorValue(m_value);
+    if (eventBehavior == DispatchNoEvent)
+        setLastChangeWasNotUserEdit();
     updatePlaceholderVisibility(false);
-    setNeedsStyleRecalc(SubtreeStyleChange);
-    setFormControlValueMatchesRenderer(true);
+    setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::ControlValue));
     m_suggestedValue = String();
-
-    // Set the caret to the end of the text value.
-    if (document().focusedElement() == this) {
+    setNeedsValidityCheck();
+    if (isFinishedParsingChildren()) {
+        // Set the caret to the end of the text value except for initialize.
         unsigned endOfString = m_value.length();
-        setSelectionRange(endOfString, endOfString);
+        setSelectionRange(endOfString, endOfString, SelectionHasNoDirection, ChangeSelectionIfFocused);
     }
 
     notifyFormStateChanged();
-    setTextAsOfLastFormControlChangeEvent(normalizedValue);
+    if (eventBehavior == DispatchNoEvent) {
+        setTextAsOfLastFormControlChangeEvent(normalizedValue);
+    } else {
+        if (eventBehavior == DispatchInputAndChangeEvent)
+            dispatchFormControlInputEvent();
+        dispatchFormControlChangeEvent();
+    }
+}
+
+void HTMLTextAreaElement::setInnerEditorValue(const String& value)
+{
+    HTMLTextFormControlElement::setInnerEditorValue(value);
+    m_valueIsUpToDate = true;
 }
 
 String HTMLTextAreaElement::defaultValue() const
@@ -391,10 +424,10 @@ String HTMLTextAreaElement::defaultValue() const
 
 void HTMLTextAreaElement::setDefaultValue(const String& defaultValue)
 {
-    RefPtr<Node> protectFromMutationEvents(this);
+    RefPtrWillBeRawPtr<Node> protectFromMutationEvents(this);
 
     // To preserve comments, remove only the text nodes, then add a single text node.
-    Vector<RefPtr<Node> > textNodes;
+    WillBeHeapVector<RefPtrWillBeMember<Node>> textNodes;
     for (Node* n = firstChild(); n; n = n->nextSibling()) {
         if (n->isTextNode())
             textNodes.append(n);
@@ -416,19 +449,42 @@ void HTMLTextAreaElement::setDefaultValue(const String& defaultValue)
 
 int HTMLTextAreaElement::maxLength() const
 {
-    bool ok;
-    int value = getAttribute(maxlengthAttr).string().toInt(&ok);
-    return ok && value >= 0 ? value : -1;
+    int value;
+    if (!parseHTMLInteger(getAttribute(maxlengthAttr), value))
+        return -1;
+    return value >= 0 ? value : -1;
+}
+
+int HTMLTextAreaElement::minLength() const
+{
+    int value;
+    if (!parseHTMLInteger(getAttribute(minlengthAttr), value))
+        return -1;
+    return value >= 0 ? value : -1;
 }
 
 void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionState& exceptionState)
 {
+    int min = minLength();
     if (newValue < 0)
         exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(newValue) + ") is not positive or 0.");
+    else if (min >= 0 && newValue < min)
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMinimumBound("maxLength", newValue, min));
     else
         setIntegralAttribute(maxlengthAttr, newValue);
 }
 
+void HTMLTextAreaElement::setMinLength(int newValue, ExceptionState& exceptionState)
+{
+    int max = maxLength();
+    if (newValue < 0)
+        exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(newValue) + ") is not positive or 0.");
+    else if (max >= 0 && newValue > max)
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("minLength", newValue, max));
+    else
+        setIntegralAttribute(minlengthAttr, newValue);
+}
+
 String HTMLTextAreaElement::suggestedValue() const
 {
     return m_suggestedValue;
@@ -437,10 +493,13 @@ String HTMLTextAreaElement::suggestedValue() const
 void HTMLTextAreaElement::setSuggestedValue(const String& value)
 {
     m_suggestedValue = value;
-    setInnerTextValue(m_suggestedValue);
+
+    if (!value.isNull())
+        setInnerEditorValue(m_suggestedValue);
+    else
+        setInnerEditorValue(m_value);
     updatePlaceholderVisibility(false);
-    setNeedsStyleRecalc(SubtreeStyleChange);
-    setFormControlValueMatchesRenderer(true);
+    setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::ControlValue));
 }
 
 String HTMLTextAreaElement::validationMessage() const
@@ -457,20 +516,36 @@ String HTMLTextAreaElement::validationMessage() const
     if (tooLong())
         return locale().validationMessageTooLongText(computeLengthForSubmission(value()), maxLength());
 
+    if (tooShort())
+        return locale().validationMessageTooShortText(computeLengthForSubmission(value()), minLength());
+
     return String();
 }
 
 bool HTMLTextAreaElement::valueMissing() const
 {
-    return willValidate() && valueMissing(value());
+    // We should not call value() for performance.
+    return willValidate() && valueMissing(0);
+}
+
+bool HTMLTextAreaElement::valueMissing(const String* value) const
+{
+    return isRequiredFormControl() && !isDisabledOrReadOnly() && (value ? *value : this->value()).isEmpty();
 }
 
 bool HTMLTextAreaElement::tooLong() const
 {
-    return willValidate() && tooLong(value(), CheckDirtyFlag);
+    // We should not call value() for performance.
+    return willValidate() && tooLong(0, CheckDirtyFlag);
+}
+
+bool HTMLTextAreaElement::tooShort() const
+{
+    // We should not call value() for performance.
+    return willValidate() && tooShort(0, CheckDirtyFlag);
 }
 
-bool HTMLTextAreaElement::tooLong(const String& value, NeedsToCheckDirtyFlag check) const
+bool HTMLTextAreaElement::tooLong(const String* value, NeedsToCheckDirtyFlag check) const
 {
     // Return false for the default value or value set by script even if it is
     // longer than maxLength.
@@ -480,12 +555,27 @@ bool HTMLTextAreaElement::tooLong(const String& value, NeedsToCheckDirtyFlag che
     int max = maxLength();
     if (max < 0)
         return false;
-    return computeLengthForSubmission(value) > static_cast<unsigned>(max);
+    return computeLengthForSubmission(value ? *value : this->value()) > static_cast<unsigned>(max);
+}
+
+bool HTMLTextAreaElement::tooShort(const String* value, NeedsToCheckDirtyFlag check) const
+{
+    // Return false for the default value or value set by script even if it is
+    // shorter than minLength.
+    if (check == CheckDirtyFlag && !lastChangeWasUserEdit())
+        return false;
+
+    int min = minLength();
+    if (min <= 0)
+        return false;
+    // An empty string is excluded from minlength check.
+    unsigned len = computeLengthForSubmission(value ? *value : this->value());
+    return len > 0 && len < static_cast<unsigned>(min);
 }
 
 bool HTMLTextAreaElement::isValidValue(const String& candidate) const
 {
-    return !valueMissing(candidate) && !tooLong(candidate, IgnoreDirtyFlag);
+    return !valueMissing(&candidate) && !tooLong(&candidate, IgnoreDirtyFlag) && !tooShort(&candidate, IgnoreDirtyFlag);
 }
 
 void HTMLTextAreaElement::accessKeyAction(bool)
@@ -503,11 +593,6 @@ void HTMLTextAreaElement::setRows(int rows)
     setIntegralAttribute(rowsAttr, rows);
 }
 
-bool HTMLTextAreaElement::shouldUseInputMethod()
-{
-    return true;
-}
-
 bool HTMLTextAreaElement::matchesReadOnlyPseudoClass() const
 {
     return isReadOnly();
@@ -521,18 +606,18 @@ bool HTMLTextAreaElement::matchesReadWritePseudoClass() const
 void HTMLTextAreaElement::updatePlaceholderText()
 {
     HTMLElement* placeholder = placeholderElement();
-    String placeholderText = strippedPlaceholder();
+    const AtomicString& placeholderText = fastGetAttribute(placeholderAttr);
     if (placeholderText.isEmpty()) {
         if (placeholder)
             userAgentShadowRoot()->removeChild(placeholder);
         return;
     }
     if (!placeholder) {
-        RefPtr<HTMLDivElement> newElement = HTMLDivElement::create(document());
+        RefPtrWillBeRawPtr<HTMLDivElement> newElement = HTMLDivElement::create(document());
         placeholder = newElement.get();
         placeholder->setShadowPseudoId(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
         placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
-        userAgentShadowRoot()->insertBefore(placeholder, innerTextElement()->nextSibling());
+        userAgentShadowRoot()->insertBefore(placeholder, innerEditorElement()->nextSibling());
     }
     placeholder->setTextContent(placeholderText);
 }