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 "ChromeClient.h"
30 #include "CSSValueKeywords.h"
33 #include "EventNames.h"
34 #include "FocusController.h"
35 #include "FormDataList.h"
37 #include "HTMLNames.h"
38 #include "MappedAttribute.h"
40 #include "RenderStyle.h"
41 #include "RenderTextControlMultiLine.h"
42 #include "ScriptEventListener.h"
44 #include "VisibleSelection.h"
45 #include <wtf/StdLibExtras.h>
49 using namespace HTMLNames;
51 static const int defaultRows = 2;
52 static const int defaultCols = 20;
54 static inline void notifyFormStateChanged(const HTMLTextAreaElement* element)
56 Frame* frame = element->document()->frame();
59 frame->page()->chrome()->client()->formStateDidChange(element);
62 HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
63 : HTMLFormControlElementWithState(tagName, document, form)
67 , m_cachedSelectionStart(-1)
68 , m_cachedSelectionEnd(-1)
70 ASSERT(hasTagName(textareaTag));
71 setFormControlValueMatchesRenderer(true);
72 notifyFormStateChanged(this);
75 const AtomicString& HTMLTextAreaElement::formControlType() const
77 DEFINE_STATIC_LOCAL(const AtomicString, textarea, ("textarea"));
81 bool HTMLTextAreaElement::saveFormControlState(String& result) const
87 void HTMLTextAreaElement::restoreFormControlState(const String& state)
89 setDefaultValue(state);
92 int HTMLTextAreaElement::selectionStart()
96 if (document()->focusedNode() != this && m_cachedSelectionStart >= 0)
97 return m_cachedSelectionStart;
98 return toRenderTextControl(renderer())->selectionStart();
101 int HTMLTextAreaElement::selectionEnd()
105 if (document()->focusedNode() != this && m_cachedSelectionEnd >= 0)
106 return m_cachedSelectionEnd;
107 return toRenderTextControl(renderer())->selectionEnd();
110 void HTMLTextAreaElement::setSelectionStart(int start)
114 toRenderTextControl(renderer())->setSelectionStart(start);
117 void HTMLTextAreaElement::setSelectionEnd(int end)
121 toRenderTextControl(renderer())->setSelectionEnd(end);
124 void HTMLTextAreaElement::select()
128 toRenderTextControl(renderer())->select();
131 void HTMLTextAreaElement::setSelectionRange(int start, int end)
135 toRenderTextControl(renderer())->setSelectionRange(start, end);
138 void HTMLTextAreaElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
140 setValue(defaultValue());
141 HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
144 void HTMLTextAreaElement::parseMappedAttribute(MappedAttribute* attr)
146 if (attr->name() == rowsAttr) {
147 int rows = attr->value().toInt();
150 if (m_rows != rows) {
153 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
155 } else if (attr->name() == colsAttr) {
156 int cols = attr->value().toInt();
159 if (m_cols != cols) {
162 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
164 } else if (attr->name() == wrapAttr) {
165 // The virtual/physical values were a Netscape extension of HTML 3.0, now deprecated.
166 // The soft/hard /off values are a recommendation for HTML 4 extension by IE and NS 4.
168 if (equalIgnoringCase(attr->value(), "physical") || equalIgnoringCase(attr->value(), "hard") || equalIgnoringCase(attr->value(), "on"))
170 else if (equalIgnoringCase(attr->value(), "off"))
174 if (wrap != m_wrap) {
177 if (shouldWrapText()) {
178 addCSSProperty(attr, CSSPropertyWhiteSpace, CSSValuePreWrap);
179 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
181 addCSSProperty(attr, CSSPropertyWhiteSpace, CSSValuePre);
182 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueNormal);
186 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
188 } else if (attr->name() == accesskeyAttr) {
189 // ignore for the moment
190 } else if (attr->name() == alignAttr) {
191 // Don't map 'align' attribute. This matches what Firefox, Opera and IE do.
192 // See http://bugs.webkit.org/show_bug.cgi?id=7075
193 } else if (attr->name() == onfocusAttr)
194 setAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(this, attr));
195 else if (attr->name() == onblurAttr)
196 setAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(this, attr));
197 else if (attr->name() == onselectAttr)
198 setAttributeEventListener(eventNames().selectEvent, createAttributeEventListener(this, attr));
199 else if (attr->name() == onchangeAttr)
200 setAttributeEventListener(eventNames().changeEvent, createAttributeEventListener(this, attr));
202 HTMLFormControlElementWithState::parseMappedAttribute(attr);
205 RenderObject* HTMLTextAreaElement::createRenderer(RenderArena* arena, RenderStyle*)
207 return new (arena) RenderTextControlMultiLine(this);
210 bool HTMLTextAreaElement::appendFormData(FormDataList& encoding, bool)
212 if (name().isEmpty())
215 // FIXME: It's not acceptable to ignore the HardWrap setting when there is no renderer.
216 // While we have no evidence this has ever been a practical problem, it would be best to fix it some day.
217 RenderTextControl* control = toRenderTextControl(renderer());
218 const String& text = (m_wrap == HardWrap && control) ? control->textWithHardLineBreaks() : value();
219 encoding.appendData(name(), text);
223 void HTMLTextAreaElement::reset()
225 setValue(defaultValue());
228 bool HTMLTextAreaElement::isKeyboardFocusable(KeyboardEvent*) const
230 // If a given text area can be focused at all, then it will always be keyboard focusable.
231 return isFocusable();
234 bool HTMLTextAreaElement::isMouseFocusable() const
236 return isFocusable();
239 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
243 if (!restorePreviousSelection || m_cachedSelectionStart < 0) {
244 #if ENABLE(ON_FIRST_TEXTAREA_FOCUS_SELECT_ALL)
245 // Devices with trackballs or d-pads may focus on a textarea in route
246 // to another focusable node. By selecting all text, the next movement
247 // can more readily be interpreted as moving to the next node.
250 // If this is the first focus, set a caret at the beginning of the text.
251 // This matches some browsers' behavior; see bug 11746 Comment #15.
252 // http://bugs.webkit.org/show_bug.cgi?id=11746#c15
253 setSelectionRange(0, 0);
256 // Restore the cached selection. This matches other browsers' behavior.
257 setSelectionRange(m_cachedSelectionStart, m_cachedSelectionEnd);
260 if (document()->frame())
261 document()->frame()->revealSelection();
264 void HTMLTextAreaElement::defaultEventHandler(Event* event)
266 if (renderer() && (event->isMouseEvent() || event->isDragEvent() || event->isWheelEvent() || event->type() == eventNames().blurEvent))
267 static_cast<RenderTextControlMultiLine*>(renderer())->forwardEvent(event);
269 HTMLFormControlElementWithState::defaultEventHandler(event);
272 void HTMLTextAreaElement::rendererWillBeDestroyed()
277 void HTMLTextAreaElement::updateValue() const
279 if (formControlValueMatchesRenderer())
283 m_value = toRenderTextControl(renderer())->text();
284 const_cast<HTMLTextAreaElement*>(this)->setFormControlValueMatchesRenderer(true);
285 notifyFormStateChanged(this);
288 String HTMLTextAreaElement::value() const
294 void HTMLTextAreaElement::setValue(const String& value)
296 // Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
297 // We normalize line endings coming from JavaScript here.
298 String normalizedValue = value.isNull() ? "" : value;
299 normalizedValue.replace("\r\n", "\n");
300 normalizedValue.replace('\r', '\n');
302 // Return early because we don't want to move the caret or trigger other side effects
303 // when the value isn't changing. This matches Firefox behavior, at least.
304 if (normalizedValue == this->value())
307 m_value = normalizedValue;
308 setFormControlValueMatchesRenderer(true);
310 document()->updateStyleIfNeeded();
312 renderer()->updateFromElement();
314 // Set the caret to the end of the text value.
315 if (document()->focusedNode() == this) {
316 unsigned endOfString = m_value.length();
317 setSelectionRange(endOfString, endOfString);
320 setNeedsStyleRecalc();
321 notifyFormStateChanged(this);
324 String HTMLTextAreaElement::defaultValue() const
328 // Since there may be comments, ignore nodes other than text nodes.
329 for (Node* n = firstChild(); n; n = n->nextSibling()) {
331 value += static_cast<Text*>(n)->data();
334 UChar firstCharacter = value[0];
335 if (firstCharacter == '\r' && value[1] == '\n')
337 else if (firstCharacter == '\r' || firstCharacter == '\n')
343 void HTMLTextAreaElement::setDefaultValue(const String& defaultValue)
345 // To preserve comments, remove only the text nodes, then add a single text node.
347 Vector<RefPtr<Node> > textNodes;
348 for (Node* n = firstChild(); n; n = n->nextSibling()) {
353 size_t size = textNodes.size();
354 for (size_t i = 0; i < size; ++i)
355 removeChild(textNodes[i].get(), ec);
357 // Normalize line endings.
358 // Add an extra line break if the string starts with one, since
359 // the code to read default values from the DOM strips the leading one.
360 String value = defaultValue;
361 value.replace("\r\n", "\n");
362 value.replace('\r', '\n');
363 if (value[0] == '\n')
364 value = "\n" + value;
366 insertBefore(document()->createTextNode(value), firstChild(), ec);
371 void HTMLTextAreaElement::accessKeyAction(bool)
376 const AtomicString& HTMLTextAreaElement::accessKey() const
378 return getAttribute(accesskeyAttr);
381 void HTMLTextAreaElement::setAccessKey(const String& value)
383 setAttribute(accesskeyAttr, value);
386 void HTMLTextAreaElement::setCols(int cols)
388 setAttribute(colsAttr, String::number(cols));
391 void HTMLTextAreaElement::setRows(int rows)
393 setAttribute(rowsAttr, String::number(rows));
396 VisibleSelection HTMLTextAreaElement::selection() const
398 if (!renderer() || m_cachedSelectionStart < 0 || m_cachedSelectionEnd < 0)
399 return VisibleSelection();
400 return toRenderTextControl(renderer())->selection(m_cachedSelectionStart, m_cachedSelectionEnd);
403 bool HTMLTextAreaElement::shouldUseInputMethod() const