2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
6 * (C) 2006 Alexey Proskuryakov (ap@nypop.com)
7 * Copyright (C) 2007 Samuel Weinig (sam@webkit.org)
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public License
20 * along with this library; see the file COPYING.LIB. If not, write to
21 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
27 #include "core/html/HTMLTextAreaElement.h"
29 #include "bindings/core/v8/ExceptionState.h"
30 #include "bindings/core/v8/ExceptionStatePlaceholder.h"
31 #include "core/CSSValueKeywords.h"
32 #include "core/HTMLNames.h"
33 #include "core/dom/Document.h"
34 #include "core/dom/ExceptionCode.h"
35 #include "core/dom/Text.h"
36 #include "core/dom/shadow/ShadowRoot.h"
37 #include "core/editing/FrameSelection.h"
38 #include "core/editing/SpellChecker.h"
39 #include "core/editing/TextIterator.h"
40 #include "core/events/BeforeTextInsertedEvent.h"
41 #include "core/events/Event.h"
42 #include "core/frame/FrameHost.h"
43 #include "core/frame/LocalFrame.h"
44 #include "core/html/FormDataList.h"
45 #include "core/html/forms/FormController.h"
46 #include "core/html/shadow/ShadowElementNames.h"
47 #include "core/html/shadow/TextControlInnerElements.h"
48 #include "core/page/Chrome.h"
49 #include "core/page/ChromeClient.h"
50 #include "core/rendering/RenderTextControlMultiLine.h"
51 #include "platform/text/PlatformLocale.h"
52 #include "wtf/StdLibExtras.h"
53 #include "wtf/text/StringBuilder.h"
57 using namespace HTMLNames;
59 static const int defaultRows = 2;
60 static const int defaultCols = 20;
62 // On submission, LF characters are converted into CRLF.
63 // This function returns number of characters considering this.
64 static unsigned numberOfLineBreaks(const String& text)
66 unsigned length = text.length();
68 for (unsigned i = 0; i < length; i++) {
75 static inline unsigned computeLengthForSubmission(const String& text)
77 return text.length() + numberOfLineBreaks(text);
80 HTMLTextAreaElement::HTMLTextAreaElement(Document& document, HTMLFormElement* form)
81 : HTMLTextFormControlElement(textareaTag, document, form)
86 , m_valueIsUpToDate(true)
88 ScriptWrappable::init(this);
91 PassRefPtrWillBeRawPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(Document& document, HTMLFormElement* form)
93 RefPtrWillBeRawPtr<HTMLTextAreaElement> textArea = adoptRefWillBeNoop(new HTMLTextAreaElement(document, form));
94 textArea->ensureUserAgentShadowRoot();
95 return textArea.release();
98 void HTMLTextAreaElement::didAddUserAgentShadowRoot(ShadowRoot& root)
100 root.appendChild(TextControlInnerEditorElement::create(document()));
103 const AtomicString& HTMLTextAreaElement::formControlType() const
105 DEFINE_STATIC_LOCAL(const AtomicString, textarea, ("textarea", AtomicString::ConstructFromLiteral));
109 FormControlState HTMLTextAreaElement::saveFormControlState() const
111 return m_isDirty ? FormControlState(value()) : FormControlState();
114 void HTMLTextAreaElement::restoreFormControlState(const FormControlState& state)
119 void HTMLTextAreaElement::childrenChanged(const ChildrenChange& change)
121 HTMLElement::childrenChanged(change);
122 setLastChangeWasNotUserEdit();
124 setInnerEditorValue(value());
126 setNonDirtyValue(defaultValue());
129 bool HTMLTextAreaElement::isPresentationAttribute(const QualifiedName& name) const
131 if (name == alignAttr) {
132 // Don't map 'align' attribute. This matches what Firefox, Opera and IE do.
133 // See http://bugs.webkit.org/show_bug.cgi?id=7075
137 if (name == wrapAttr)
139 return HTMLTextFormControlElement::isPresentationAttribute(name);
142 void HTMLTextAreaElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
144 if (name == wrapAttr) {
145 if (shouldWrapText()) {
146 addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePreWrap);
147 addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
149 addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePre);
150 addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueNormal);
153 HTMLTextFormControlElement::collectStyleForPresentationAttribute(name, value, style);
156 void HTMLTextAreaElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
158 if (name == rowsAttr) {
159 int rows = value.toInt();
162 if (m_rows != rows) {
165 renderer()->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
167 } else if (name == colsAttr) {
168 int cols = value.toInt();
171 if (m_cols != cols) {
174 renderer()->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
176 } else if (name == wrapAttr) {
177 // The virtual/physical values were a Netscape extension of HTML 3.0, now deprecated.
178 // The soft/hard /off values are a recommendation for HTML 4 extension by IE and NS 4.
180 if (equalIgnoringCase(value, "physical") || equalIgnoringCase(value, "hard") || equalIgnoringCase(value, "on"))
182 else if (equalIgnoringCase(value, "off"))
186 if (wrap != m_wrap) {
189 renderer()->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
191 } else if (name == accesskeyAttr) {
192 // ignore for the moment
193 } else if (name == maxlengthAttr)
194 setNeedsValidityCheck();
196 HTMLTextFormControlElement::parseAttribute(name, value);
199 RenderObject* HTMLTextAreaElement::createRenderer(RenderStyle*)
201 return new RenderTextControlMultiLine(this);
204 bool HTMLTextAreaElement::appendFormData(FormDataList& encoding, bool)
206 if (name().isEmpty())
209 document().updateLayout();
211 const String& text = (m_wrap == HardWrap) ? valueWithHardLineBreaks() : value();
212 encoding.appendData(name(), text);
214 const AtomicString& dirnameAttrValue = fastGetAttribute(dirnameAttr);
215 if (!dirnameAttrValue.isNull())
216 encoding.appendData(dirnameAttrValue, directionForFormData());
220 void HTMLTextAreaElement::resetImpl()
222 setNonDirtyValue(defaultValue());
225 bool HTMLTextAreaElement::hasCustomFocusLogic() const
230 bool HTMLTextAreaElement::isKeyboardFocusable() const
232 // If a given text area can be focused at all, then it will always be keyboard focusable.
233 return isFocusable();
236 bool HTMLTextAreaElement::shouldShowFocusRingOnMouseFocus() const
241 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
243 if (!restorePreviousSelection)
244 setSelectionRange(0, 0);
246 restoreCachedSelection();
248 if (document().frame())
249 document().frame()->selection().revealSelection();
252 void HTMLTextAreaElement::defaultEventHandler(Event* event)
254 if (renderer() && (event->isMouseEvent() || event->isDragEvent() || event->hasInterface(EventNames::WheelEvent) || event->type() == EventTypeNames::blur))
256 else if (renderer() && event->isBeforeTextInsertedEvent())
257 handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(event));
259 HTMLTextFormControlElement::defaultEventHandler(event);
262 void HTMLTextAreaElement::handleFocusEvent(Element*, FocusType)
264 if (LocalFrame* frame = document().frame())
265 frame->spellChecker().didBeginEditing(this);
268 void HTMLTextAreaElement::subtreeHasChanged()
270 setChangedSinceLastFormControlChangeEvent(true);
271 m_valueIsUpToDate = false;
272 setNeedsValidityCheck();
273 setAutofilled(false);
278 // When typing in a textarea, childrenChanged is not called, so we need to force the directionality check.
279 calculateAndAdjustDirectionality();
281 ASSERT(document().isActive());
282 document().frameHost()->chrome().client().didChangeValueInTextField(*this);
285 void HTMLTextAreaElement::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent* event) const
289 int signedMaxLength = maxLength();
290 if (signedMaxLength < 0)
292 unsigned unsignedMaxLength = static_cast<unsigned>(signedMaxLength);
294 const String& currentValue = innerEditorValue();
295 unsigned currentLength = computeLengthForSubmission(currentValue);
296 if (currentLength + computeLengthForSubmission(event->text()) < unsignedMaxLength)
299 // selectionLength represents the selection length of this text field to be
300 // removed by this insertion.
301 // If the text field has no focus, we don't need to take account of the
302 // selection length. The selection is the source of text drag-and-drop in
303 // that case, and nothing in the text field will be removed.
304 unsigned selectionLength = focused() ? computeLengthForSubmission(plainText(document().frame()->selection().selection().toNormalizedRange().get())) : 0;
305 ASSERT(currentLength >= selectionLength);
306 unsigned baseLength = currentLength - selectionLength;
307 unsigned appendableLength = unsignedMaxLength > baseLength ? unsignedMaxLength - baseLength : 0;
308 event->setText(sanitizeUserInputValue(event->text(), appendableLength));
311 String HTMLTextAreaElement::sanitizeUserInputValue(const String& proposedValue, unsigned maxLength)
313 if (maxLength > 0 && U16_IS_LEAD(proposedValue[maxLength - 1]))
315 return proposedValue.left(maxLength);
318 void HTMLTextAreaElement::updateValue() const
320 if (m_valueIsUpToDate)
324 m_value = innerEditorValue();
325 const_cast<HTMLTextAreaElement*>(this)->m_valueIsUpToDate = true;
326 const_cast<HTMLTextAreaElement*>(this)->notifyFormStateChanged();
328 const_cast<HTMLTextAreaElement*>(this)->updatePlaceholderVisibility(false);
331 String HTMLTextAreaElement::value() const
337 void HTMLTextAreaElement::setValue(const String& value, TextFieldEventBehavior eventBehavior)
339 RefPtrWillBeRawPtr<HTMLTextAreaElement> protector(this);
340 setValueCommon(value, eventBehavior);
342 if (document().focusedElement() == this)
343 document().frameHost()->chrome().client().didUpdateTextOfFocusedElementByNonUserInput();
346 void HTMLTextAreaElement::setNonDirtyValue(const String& value)
348 setValueCommon(value, DispatchNoEvent, ChangeSelection);
352 void HTMLTextAreaElement::setValueCommon(const String& newValue, TextFieldEventBehavior eventBehavior, SelectionOption selectionOption)
354 // Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
355 // We normalize line endings coming from JavaScript here.
356 String normalizedValue = newValue.isNull() ? "" : newValue;
357 normalizedValue.replace("\r\n", "\n");
358 normalizedValue.replace('\r', '\n');
360 // Return early because we don't want to trigger other side effects
361 // when the value isn't changing.
362 // FIXME: Simple early return doesn't match the Firefox ever.
363 // Remove these lines.
364 if (normalizedValue == value()) {
365 if (selectionOption == ChangeSelection) {
366 setNeedsValidityCheck();
367 if (isFinishedParsingChildren()) {
368 // Set the caret to the end of the text value except for initialize.
369 unsigned endOfString = m_value.length();
370 setSelectionRange(endOfString, endOfString, SelectionHasNoDirection, NotChangeSelection);
376 m_value = normalizedValue;
377 setInnerEditorValue(m_value);
378 if (eventBehavior == DispatchNoEvent)
379 setLastChangeWasNotUserEdit();
380 updatePlaceholderVisibility(false);
381 setNeedsStyleRecalc(SubtreeStyleChange);
382 m_suggestedValue = String();
383 setNeedsValidityCheck();
384 if (isFinishedParsingChildren()) {
385 // Set the caret to the end of the text value except for initialize.
386 unsigned endOfString = m_value.length();
387 setSelectionRange(endOfString, endOfString, SelectionHasNoDirection, NotChangeSelection);
390 notifyFormStateChanged();
391 if (eventBehavior == DispatchNoEvent) {
392 setTextAsOfLastFormControlChangeEvent(normalizedValue);
394 if (eventBehavior == DispatchInputAndChangeEvent)
395 dispatchFormControlInputEvent();
396 dispatchFormControlChangeEvent();
400 void HTMLTextAreaElement::setInnerEditorValue(const String& value)
402 HTMLTextFormControlElement::setInnerEditorValue(value);
403 m_valueIsUpToDate = true;
406 String HTMLTextAreaElement::defaultValue() const
410 // Since there may be comments, ignore nodes other than text nodes.
411 for (Node* n = firstChild(); n; n = n->nextSibling()) {
413 value.append(toText(n)->data());
416 return value.toString();
419 void HTMLTextAreaElement::setDefaultValue(const String& defaultValue)
421 RefPtrWillBeRawPtr<Node> protectFromMutationEvents(this);
423 // To preserve comments, remove only the text nodes, then add a single text node.
424 WillBeHeapVector<RefPtrWillBeMember<Node> > textNodes;
425 for (Node* n = firstChild(); n; n = n->nextSibling()) {
429 size_t size = textNodes.size();
430 for (size_t i = 0; i < size; ++i)
431 removeChild(textNodes[i].get(), IGNORE_EXCEPTION);
433 // Normalize line endings.
434 String value = defaultValue;
435 value.replace("\r\n", "\n");
436 value.replace('\r', '\n');
438 insertBefore(document().createTextNode(value), firstChild(), IGNORE_EXCEPTION);
441 setNonDirtyValue(value);
444 int HTMLTextAreaElement::maxLength() const
447 int value = getAttribute(maxlengthAttr).string().toInt(&ok);
448 return ok && value >= 0 ? value : -1;
451 void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionState& exceptionState)
454 exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(newValue) + ") is not positive or 0.");
456 setIntegralAttribute(maxlengthAttr, newValue);
459 String HTMLTextAreaElement::suggestedValue() const
461 return m_suggestedValue;
464 void HTMLTextAreaElement::setSuggestedValue(const String& value)
466 m_suggestedValue = value;
469 setInnerEditorValue(m_suggestedValue);
471 setInnerEditorValue(m_value);
472 updatePlaceholderVisibility(false);
473 setNeedsStyleRecalc(SubtreeStyleChange);
476 String HTMLTextAreaElement::validationMessage() const
482 return customValidationMessage();
485 return locale().queryString(blink::WebLocalizedString::ValidationValueMissing);
488 return locale().validationMessageTooLongText(computeLengthForSubmission(value()), maxLength());
493 bool HTMLTextAreaElement::valueMissing() const
495 return willValidate() && valueMissing(value());
498 bool HTMLTextAreaElement::tooLong() const
500 return willValidate() && tooLong(value(), CheckDirtyFlag);
503 bool HTMLTextAreaElement::tooLong(const String& value, NeedsToCheckDirtyFlag check) const
505 // Return false for the default value or value set by script even if it is
506 // longer than maxLength.
507 if (check == CheckDirtyFlag && !lastChangeWasUserEdit())
510 int max = maxLength();
513 return computeLengthForSubmission(value) > static_cast<unsigned>(max);
516 bool HTMLTextAreaElement::isValidValue(const String& candidate) const
518 return !valueMissing(candidate) && !tooLong(candidate, IgnoreDirtyFlag);
521 void HTMLTextAreaElement::accessKeyAction(bool)
526 void HTMLTextAreaElement::setCols(int cols)
528 setIntegralAttribute(colsAttr, cols);
531 void HTMLTextAreaElement::setRows(int rows)
533 setIntegralAttribute(rowsAttr, rows);
536 bool HTMLTextAreaElement::matchesReadOnlyPseudoClass() const
541 bool HTMLTextAreaElement::matchesReadWritePseudoClass() const
543 return !isReadOnly();
546 void HTMLTextAreaElement::updatePlaceholderText()
548 HTMLElement* placeholder = placeholderElement();
549 const AtomicString& placeholderText = fastGetAttribute(placeholderAttr);
550 if (placeholderText.isEmpty()) {
552 userAgentShadowRoot()->removeChild(placeholder);
556 RefPtrWillBeRawPtr<HTMLDivElement> newElement = HTMLDivElement::create(document());
557 placeholder = newElement.get();
558 placeholder->setShadowPseudoId(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
559 placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
560 userAgentShadowRoot()->insertBefore(placeholder, innerEditorElement()->nextSibling());
562 placeholder->setTextContent(placeholderText);
565 bool HTMLTextAreaElement::isInteractiveContent() const
570 bool HTMLTextAreaElement::supportsAutofocus() const