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 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 "HTMLTextAreaElement.h"
29 #include "BeforeTextInsertedEvent.h"
30 #include "ChromeClient.h"
31 #include "CSSValueKeywords.h"
34 #include "EventNames.h"
35 #include "ExceptionCode.h"
36 #include "FocusController.h"
37 #include "FormDataList.h"
39 #include "HTMLNames.h"
40 #include "InputElement.h"
41 #include "MappedAttribute.h"
43 #include "RenderStyle.h"
44 #include "RenderTextControlMultiLine.h"
45 #include "ScriptEventListener.h"
47 #include "TextIterator.h"
48 #include "VisibleSelection.h"
49 #include <wtf/StdLibExtras.h>
53 using namespace HTMLNames
;
55 static const int defaultRows
= 2;
56 static const int defaultCols
= 20;
58 static inline void notifyFormStateChanged(const HTMLTextAreaElement
* element
)
60 Frame
* frame
= element
->document()->frame();
63 frame
->page()->chrome()->client()->formStateDidChange(element
);
66 HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName
& tagName
, Document
* document
, HTMLFormElement
* form
)
67 : HTMLTextFormControlElement(tagName
, document
, form
)
71 , m_cachedSelectionStart(-1)
72 , m_cachedSelectionEnd(-1)
75 ASSERT(hasTagName(textareaTag
));
76 setFormControlValueMatchesRenderer(true);
77 notifyFormStateChanged(this);
80 const AtomicString
& HTMLTextAreaElement::formControlType() const
82 DEFINE_STATIC_LOCAL(const AtomicString
, textarea
, ("textarea"));
86 bool HTMLTextAreaElement::saveFormControlState(String
& result
) const
92 void HTMLTextAreaElement::restoreFormControlState(const String
& state
)
94 setDefaultValue(state
);
97 void HTMLTextAreaElement::childrenChanged(bool changedByParser
, Node
* beforeChange
, Node
* afterChange
, int childCountDelta
)
99 setValue(defaultValue());
100 HTMLElement::childrenChanged(changedByParser
, beforeChange
, afterChange
, childCountDelta
);
103 void HTMLTextAreaElement::parseMappedAttribute(MappedAttribute
* attr
)
105 if (attr
->name() == rowsAttr
) {
106 int rows
= attr
->value().toInt();
109 if (m_rows
!= rows
) {
112 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
114 } else if (attr
->name() == colsAttr
) {
115 int cols
= attr
->value().toInt();
118 if (m_cols
!= cols
) {
121 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
123 } else if (attr
->name() == wrapAttr
) {
124 // The virtual/physical values were a Netscape extension of HTML 3.0, now deprecated.
125 // The soft/hard /off values are a recommendation for HTML 4 extension by IE and NS 4.
127 if (equalIgnoringCase(attr
->value(), "physical") || equalIgnoringCase(attr
->value(), "hard") || equalIgnoringCase(attr
->value(), "on"))
129 else if (equalIgnoringCase(attr
->value(), "off"))
133 if (wrap
!= m_wrap
) {
136 if (shouldWrapText()) {
137 addCSSProperty(attr
, CSSPropertyWhiteSpace
, CSSValuePreWrap
);
138 addCSSProperty(attr
, CSSPropertyWordWrap
, CSSValueBreakWord
);
140 addCSSProperty(attr
, CSSPropertyWhiteSpace
, CSSValuePre
);
141 addCSSProperty(attr
, CSSPropertyWordWrap
, CSSValueNormal
);
145 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
147 } else if (attr
->name() == accesskeyAttr
) {
148 // ignore for the moment
149 } else if (attr
->name() == alignAttr
) {
150 // Don't map 'align' attribute. This matches what Firefox, Opera and IE do.
151 // See http://bugs.webkit.org/show_bug.cgi?id=7075
153 HTMLTextFormControlElement::parseMappedAttribute(attr
);
156 RenderObject
* HTMLTextAreaElement::createRenderer(RenderArena
* arena
, RenderStyle
*)
158 return new (arena
) RenderTextControlMultiLine(this, placeholderShouldBeVisible());
161 bool HTMLTextAreaElement::appendFormData(FormDataList
& encoding
, bool)
163 if (name().isEmpty())
166 // FIXME: It's not acceptable to ignore the HardWrap setting when there is no renderer.
167 // While we have no evidence this has ever been a practical problem, it would be best to fix it some day.
168 RenderTextControl
* control
= toRenderTextControl(renderer());
169 const String
& text
= (m_wrap
== HardWrap
&& control
) ? control
->textWithHardLineBreaks() : value();
170 encoding
.appendData(name(), text
);
174 void HTMLTextAreaElement::reset()
176 setValue(defaultValue());
180 bool HTMLTextAreaElement::isKeyboardFocusable(KeyboardEvent
*) const
182 // If a given text area can be focused at all, then it will always be keyboard focusable.
183 return isFocusable();
186 bool HTMLTextAreaElement::isMouseFocusable() const
188 return isFocusable();
191 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection
)
194 ASSERT(!document()->childNeedsAndNotInStyleRecalc());
196 if (!restorePreviousSelection
|| m_cachedSelectionStart
< 0) {
197 #if ENABLE(ON_FIRST_TEXTAREA_FOCUS_SELECT_ALL)
198 // Devices with trackballs or d-pads may focus on a textarea in route
199 // to another focusable node. By selecting all text, the next movement
200 // can more readily be interpreted as moving to the next node.
203 // If this is the first focus, set a caret at the beginning of the text.
204 // This matches some browsers' behavior; see bug 11746 Comment #15.
205 // http://bugs.webkit.org/show_bug.cgi?id=11746#c15
206 setSelectionRange(0, 0);
209 // Restore the cached selection. This matches other browsers' behavior.
210 setSelectionRange(m_cachedSelectionStart
, m_cachedSelectionEnd
);
213 if (document()->frame())
214 document()->frame()->revealSelection();
217 void HTMLTextAreaElement::defaultEventHandler(Event
* event
)
219 if (renderer() && (event
->isMouseEvent() || event
->isDragEvent() || event
->isWheelEvent() || event
->type() == eventNames().blurEvent
))
220 toRenderTextControlMultiLine(renderer())->forwardEvent(event
);
221 else if (renderer() && event
->isBeforeTextInsertedEvent())
222 handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent
*>(event
));
224 HTMLFormControlElementWithState::defaultEventHandler(event
);
227 void HTMLTextAreaElement::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent
* event
) const
231 int signedMaxLength
= maxLength();
232 if (signedMaxLength
< 0)
234 unsigned unsignedMaxLength
= static_cast<unsigned>(signedMaxLength
);
236 unsigned currentLength
= toRenderTextControl(renderer())->text().numGraphemeClusters();
237 unsigned selectionLength
= plainText(document()->frame()->selection()->selection().toNormalizedRange().get()).numGraphemeClusters();
238 ASSERT(currentLength
>= selectionLength
);
239 unsigned baseLength
= currentLength
- selectionLength
;
240 unsigned appendableLength
= unsignedMaxLength
> baseLength
? unsignedMaxLength
- baseLength
: 0;
241 event
->setText(sanitizeUserInputValue(event
->text(), appendableLength
));
244 String
HTMLTextAreaElement::sanitizeUserInputValue(const String
& proposedValue
, unsigned maxLength
)
246 return proposedValue
.left(proposedValue
.numCharactersInGraphemeClusters(maxLength
));
249 void HTMLTextAreaElement::rendererWillBeDestroyed()
254 void HTMLTextAreaElement::updateValue() const
256 if (formControlValueMatchesRenderer())
260 m_value
= toRenderTextControl(renderer())->text();
261 const_cast<HTMLTextAreaElement
*>(this)->setFormControlValueMatchesRenderer(true);
262 notifyFormStateChanged(this);
266 String
HTMLTextAreaElement::value() const
272 void HTMLTextAreaElement::setValue(const String
& value
)
274 // Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
275 // We normalize line endings coming from JavaScript here.
276 String normalizedValue
= value
.isNull() ? "" : value
;
277 normalizedValue
.replace("\r\n", "\n");
278 normalizedValue
.replace('\r', '\n');
280 // Return early because we don't want to move the caret or trigger other side effects
281 // when the value isn't changing. This matches Firefox behavior, at least.
282 if (normalizedValue
== this->value())
285 m_value
= normalizedValue
;
286 setFormControlValueMatchesRenderer(true);
287 updatePlaceholderVisibility(false);
289 document()->updateStyleIfNeeded();
291 renderer()->updateFromElement();
293 // Set the caret to the end of the text value.
294 if (document()->focusedNode() == this) {
295 unsigned endOfString
= m_value
.length();
296 setSelectionRange(endOfString
, endOfString
);
299 setNeedsStyleRecalc();
300 notifyFormStateChanged(this);
304 String
HTMLTextAreaElement::defaultValue() const
308 // Since there may be comments, ignore nodes other than text nodes.
309 for (Node
* n
= firstChild(); n
; n
= n
->nextSibling()) {
311 value
+= static_cast<Text
*>(n
)->data();
314 UChar firstCharacter
= value
[0];
315 if (firstCharacter
== '\r' && value
[1] == '\n')
317 else if (firstCharacter
== '\r' || firstCharacter
== '\n')
323 void HTMLTextAreaElement::setDefaultValue(const String
& defaultValue
)
325 // To preserve comments, remove only the text nodes, then add a single text node.
327 Vector
<RefPtr
<Node
> > textNodes
;
328 for (Node
* n
= firstChild(); n
; n
= n
->nextSibling()) {
333 size_t size
= textNodes
.size();
334 for (size_t i
= 0; i
< size
; ++i
)
335 removeChild(textNodes
[i
].get(), ec
);
337 // Normalize line endings.
338 // Add an extra line break if the string starts with one, since
339 // the code to read default values from the DOM strips the leading one.
340 String value
= defaultValue
;
341 value
.replace("\r\n", "\n");
342 value
.replace('\r', '\n');
343 if (value
[0] == '\n')
344 value
= "\n" + value
;
346 insertBefore(document()->createTextNode(value
), firstChild(), ec
);
351 int HTMLTextAreaElement::maxLength() const
354 int value
= getAttribute(maxlengthAttr
).string().toInt(&ok
);
355 return ok
&& value
>= 0 ? value
: -1;
358 void HTMLTextAreaElement::setMaxLength(int newValue
, ExceptionCode
& ec
)
363 setAttribute(maxlengthAttr
, String::number(newValue
));
366 bool HTMLTextAreaElement::tooLong() const
368 // Return false for the default value even if it is longer than maxLength.
372 int max
= maxLength();
375 return value().length() > static_cast<unsigned>(max
);
378 void HTMLTextAreaElement::accessKeyAction(bool)
383 const AtomicString
& HTMLTextAreaElement::accessKey() const
385 return getAttribute(accesskeyAttr
);
388 void HTMLTextAreaElement::setAccessKey(const String
& value
)
390 setAttribute(accesskeyAttr
, value
);
393 void HTMLTextAreaElement::setCols(int cols
)
395 setAttribute(colsAttr
, String::number(cols
));
398 void HTMLTextAreaElement::setRows(int rows
)
400 setAttribute(rowsAttr
, String::number(rows
));
403 bool HTMLTextAreaElement::shouldUseInputMethod() const