Rubber-stamped by Brady Eidson.
[webbrowser.git] / WebCore / html / HTMLTextAreaElement.cpp
blob3030018609363995823c670a5fde20a90ba4f6d4
1 /*
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.
26 #include "config.h"
27 #include "HTMLTextAreaElement.h"
29 #include "BeforeTextInsertedEvent.h"
30 #include "ChromeClient.h"
31 #include "CSSValueKeywords.h"
32 #include "Document.h"
33 #include "Event.h"
34 #include "EventNames.h"
35 #include "ExceptionCode.h"
36 #include "FocusController.h"
37 #include "FormDataList.h"
38 #include "Frame.h"
39 #include "HTMLNames.h"
40 #include "InputElement.h"
41 #include "MappedAttribute.h"
42 #include "Page.h"
43 #include "RenderStyle.h"
44 #include "RenderTextControlMultiLine.h"
45 #include "ScriptEventListener.h"
46 #include "Text.h"
47 #include "TextIterator.h"
48 #include "VisibleSelection.h"
49 #include <wtf/StdLibExtras.h>
51 namespace WebCore {
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();
61 if (!frame)
62 return;
63 frame->page()->chrome()->client()->formStateDidChange(element);
66 HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
67 : HTMLTextFormControlElement(tagName, document, form)
68 , m_rows(defaultRows)
69 , m_cols(defaultCols)
70 , m_wrap(SoftWrap)
71 , m_cachedSelectionStart(-1)
72 , m_cachedSelectionEnd(-1)
73 , m_isDirty(false)
75 ASSERT(hasTagName(textareaTag));
76 setFormControlValueMatchesRenderer(true);
77 notifyFormStateChanged(this);
80 const AtomicString& HTMLTextAreaElement::formControlType() const
82 DEFINE_STATIC_LOCAL(const AtomicString, textarea, ("textarea"));
83 return textarea;
86 bool HTMLTextAreaElement::saveFormControlState(String& result) const
88 result = value();
89 return true;
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();
107 if (rows <= 0)
108 rows = defaultRows;
109 if (m_rows != rows) {
110 m_rows = rows;
111 if (renderer())
112 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
114 } else if (attr->name() == colsAttr) {
115 int cols = attr->value().toInt();
116 if (cols <= 0)
117 cols = defaultCols;
118 if (m_cols != cols) {
119 m_cols = cols;
120 if (renderer())
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.
126 WrapMethod wrap;
127 if (equalIgnoringCase(attr->value(), "physical") || equalIgnoringCase(attr->value(), "hard") || equalIgnoringCase(attr->value(), "on"))
128 wrap = HardWrap;
129 else if (equalIgnoringCase(attr->value(), "off"))
130 wrap = NoWrap;
131 else
132 wrap = SoftWrap;
133 if (wrap != m_wrap) {
134 m_wrap = wrap;
136 if (shouldWrapText()) {
137 addCSSProperty(attr, CSSPropertyWhiteSpace, CSSValuePreWrap);
138 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
139 } else {
140 addCSSProperty(attr, CSSPropertyWhiteSpace, CSSValuePre);
141 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueNormal);
144 if (renderer())
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
152 } else
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())
164 return false;
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);
171 return true;
174 void HTMLTextAreaElement::reset()
176 setValue(defaultValue());
177 m_isDirty = false;
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)
193 ASSERT(renderer());
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.
201 select();
202 #else
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);
207 #endif
208 } else {
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
229 ASSERT(event);
230 ASSERT(renderer());
231 int signedMaxLength = maxLength();
232 if (signedMaxLength < 0)
233 return;
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()
251 updateValue();
254 void HTMLTextAreaElement::updateValue() const
256 if (formControlValueMatchesRenderer())
257 return;
259 ASSERT(renderer());
260 m_value = toRenderTextControl(renderer())->text();
261 const_cast<HTMLTextAreaElement*>(this)->setFormControlValueMatchesRenderer(true);
262 notifyFormStateChanged(this);
263 m_isDirty = true;
266 String HTMLTextAreaElement::value() const
268 updateValue();
269 return m_value;
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())
283 return;
285 m_value = normalizedValue;
286 setFormControlValueMatchesRenderer(true);
287 updatePlaceholderVisibility(false);
288 if (inDocument())
289 document()->updateStyleIfNeeded();
290 if (renderer())
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);
301 updateValidity();
304 String HTMLTextAreaElement::defaultValue() const
306 String value = "";
308 // Since there may be comments, ignore nodes other than text nodes.
309 for (Node* n = firstChild(); n; n = n->nextSibling()) {
310 if (n->isTextNode())
311 value += static_cast<Text*>(n)->data();
314 UChar firstCharacter = value[0];
315 if (firstCharacter == '\r' && value[1] == '\n')
316 value.remove(0, 2);
317 else if (firstCharacter == '\r' || firstCharacter == '\n')
318 value.remove(0, 1);
320 return value;
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()) {
329 if (n->isTextNode())
330 textNodes.append(n);
332 ExceptionCode ec;
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);
348 setValue(value);
351 int HTMLTextAreaElement::maxLength() const
353 bool ok;
354 int value = getAttribute(maxlengthAttr).string().toInt(&ok);
355 return ok && value >= 0 ? value : -1;
358 void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionCode& ec)
360 if (newValue < 0)
361 ec = INDEX_SIZE_ERR;
362 else
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.
369 if (!m_isDirty)
370 return false;
372 int max = maxLength();
373 if (max < 0)
374 return false;
375 return value().length() > static_cast<unsigned>(max);
378 void HTMLTextAreaElement::accessKeyAction(bool)
380 focus();
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
405 return true;
408 } // namespace