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, 2010 Apple Inc. All rights reserved.
6 * (C) 2006 Alexey Proskuryakov (ap@nypop.com)
7 * Copyright (C) 2007 Samuel Weinig (sam@webkit.org)
8 *
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.
13 *
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.
18 *
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.
23 *
24 */
25
26 #include "config.h"
27 #include "HTMLTextAreaElement.h"
28
29 #include "Attribute.h"
30 #include "BeforeTextInsertedEvent.h"
31 #include "CSSValueKeywords.h"
32 #include "Chrome.h"
33 #include "ChromeClient.h"
34 #include "Document.h"
35 #include "Event.h"
36 #include "EventNames.h"
37 #include "ExceptionCode.h"
38 #include "FocusController.h"
39 #include "FormDataList.h"
40 #include "Frame.h"
41 #include "HTMLNames.h"
42 #include "InputElement.h"
43 #include "Page.h"
44 #include "RenderStyle.h"
45 #include "RenderTextControlMultiLine.h"
46 #include "ScriptEventListener.h"
47 #include "Text.h"
48 #include "TextIterator.h"
49 #include "VisibleSelection.h"
50 #include <wtf/StdLibExtras.h>
51
52 namespace WebCore {
53
54 using namespace HTMLNames;
55
56 static const int defaultRows = 2;
57 static const int defaultCols = 20;
58
notifyFormStateChanged(const HTMLTextAreaElement * element)59 static inline void notifyFormStateChanged(const HTMLTextAreaElement* element)
60 {
61 Frame* frame = element->document()->frame();
62 if (!frame)
63 return;
64 frame->page()->chrome()->client()->formStateDidChange(element);
65 }
66
HTMLTextAreaElement(const QualifiedName & tagName,Document * document,HTMLFormElement * form)67 HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
68 : HTMLTextFormControlElement(tagName, document, form)
69 , m_rows(defaultRows)
70 , m_cols(defaultCols)
71 , m_wrap(SoftWrap)
72 , m_cachedSelectionStart(-1)
73 , m_cachedSelectionEnd(-1)
74 , m_isDirty(false)
75 {
76 ASSERT(hasTagName(textareaTag));
77 setFormControlValueMatchesRenderer(true);
78 }
79
create(const QualifiedName & tagName,Document * document,HTMLFormElement * form)80 PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
81 {
82 return adoptRef(new HTMLTextAreaElement(tagName, document, form));
83 }
84
formControlType() const85 const AtomicString& HTMLTextAreaElement::formControlType() const
86 {
87 DEFINE_STATIC_LOCAL(const AtomicString, textarea, ("textarea"));
88 return textarea;
89 }
90
saveFormControlState(String & result) const91 bool HTMLTextAreaElement::saveFormControlState(String& result) const
92 {
93 String currentValue = value();
94 if (currentValue == defaultValue())
95 return false;
96 result = currentValue;
97 return true;
98 }
99
restoreFormControlState(const String & state)100 void HTMLTextAreaElement::restoreFormControlState(const String& state)
101 {
102 setValue(state);
103 }
104
childrenChanged(bool changedByParser,Node * beforeChange,Node * afterChange,int childCountDelta)105 void HTMLTextAreaElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
106 {
107 if (!m_isDirty)
108 setNonDirtyValue(defaultValue());
109 HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
110 }
111
parseMappedAttribute(Attribute * attr)112 void HTMLTextAreaElement::parseMappedAttribute(Attribute* attr)
113 {
114 if (attr->name() == rowsAttr) {
115 int rows = attr->value().toInt();
116 if (rows <= 0)
117 rows = defaultRows;
118 if (m_rows != rows) {
119 m_rows = rows;
120 if (renderer())
121 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
122 }
123 } else if (attr->name() == colsAttr) {
124 int cols = attr->value().toInt();
125 if (cols <= 0)
126 cols = defaultCols;
127 if (m_cols != cols) {
128 m_cols = cols;
129 if (renderer())
130 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
131 }
132 } else if (attr->name() == wrapAttr) {
133 // The virtual/physical values were a Netscape extension of HTML 3.0, now deprecated.
134 // The soft/hard /off values are a recommendation for HTML 4 extension by IE and NS 4.
135 WrapMethod wrap;
136 if (equalIgnoringCase(attr->value(), "physical") || equalIgnoringCase(attr->value(), "hard") || equalIgnoringCase(attr->value(), "on"))
137 wrap = HardWrap;
138 else if (equalIgnoringCase(attr->value(), "off"))
139 wrap = NoWrap;
140 else
141 wrap = SoftWrap;
142 if (wrap != m_wrap) {
143 m_wrap = wrap;
144
145 if (shouldWrapText()) {
146 addCSSProperty(attr, CSSPropertyWhiteSpace, CSSValuePreWrap);
147 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
148 } else {
149 addCSSProperty(attr, CSSPropertyWhiteSpace, CSSValuePre);
150 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueNormal);
151 }
152
153 if (renderer())
154 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
155 }
156 } else if (attr->name() == accesskeyAttr) {
157 // ignore for the moment
158 } else if (attr->name() == alignAttr) {
159 // Don't map 'align' attribute. This matches what Firefox, Opera and IE do.
160 // See http://bugs.webkit.org/show_bug.cgi?id=7075
161 } else if (attr->name() == maxlengthAttr)
162 setNeedsValidityCheck();
163 else
164 HTMLTextFormControlElement::parseMappedAttribute(attr);
165 }
166
createRenderer(RenderArena * arena,RenderStyle *)167 RenderObject* HTMLTextAreaElement::createRenderer(RenderArena* arena, RenderStyle*)
168 {
169 return new (arena) RenderTextControlMultiLine(this, placeholderShouldBeVisible());
170 }
171
appendFormData(FormDataList & encoding,bool)172 bool HTMLTextAreaElement::appendFormData(FormDataList& encoding, bool)
173 {
174 if (name().isEmpty())
175 return false;
176
177 document()->updateLayout();
178
179 // FIXME: It's not acceptable to ignore the HardWrap setting when there is no renderer.
180 // While we have no evidence this has ever been a practical problem, it would be best to fix it some day.
181 RenderTextControl* control = toRenderTextControl(renderer());
182 const String& text = (m_wrap == HardWrap && control) ? control->textWithHardLineBreaks() : value();
183 encoding.appendData(name(), text);
184 return true;
185 }
186
reset()187 void HTMLTextAreaElement::reset()
188 {
189 setNonDirtyValue(defaultValue());
190 }
191
isKeyboardFocusable(KeyboardEvent *) const192 bool HTMLTextAreaElement::isKeyboardFocusable(KeyboardEvent*) const
193 {
194 // If a given text area can be focused at all, then it will always be keyboard focusable.
195 return isFocusable();
196 }
197
isMouseFocusable() const198 bool HTMLTextAreaElement::isMouseFocusable() const
199 {
200 return isFocusable();
201 }
202
updateFocusAppearance(bool restorePreviousSelection)203 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
204 {
205 ASSERT(renderer());
206 ASSERT(!document()->childNeedsAndNotInStyleRecalc());
207
208 if (!restorePreviousSelection || m_cachedSelectionStart < 0) {
209 #if ENABLE(ON_FIRST_TEXTAREA_FOCUS_SELECT_ALL)
210 // Devices with trackballs or d-pads may focus on a textarea in route
211 // to another focusable node. By selecting all text, the next movement
212 // can more readily be interpreted as moving to the next node.
213 select();
214 #else
215 // If this is the first focus, set a caret at the beginning of the text.
216 // This matches some browsers' behavior; see bug 11746 Comment #15.
217 // http://bugs.webkit.org/show_bug.cgi?id=11746#c15
218 setSelectionRange(0, 0);
219 #endif
220 } else {
221 // Restore the cached selection. This matches other browsers' behavior.
222 setSelectionRange(m_cachedSelectionStart, m_cachedSelectionEnd);
223 }
224
225 if (document()->frame())
226 document()->frame()->selection()->revealSelection();
227 }
228
defaultEventHandler(Event * event)229 void HTMLTextAreaElement::defaultEventHandler(Event* event)
230 {
231 if (renderer() && (event->isMouseEvent() || event->isDragEvent() || event->isWheelEvent() || event->type() == eventNames().blurEvent))
232 toRenderTextControlMultiLine(renderer())->forwardEvent(event);
233 else if (renderer() && event->isBeforeTextInsertedEvent())
234 handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(event));
235
236 HTMLFormControlElementWithState::defaultEventHandler(event);
237 }
238
handleBeforeTextInsertedEvent(BeforeTextInsertedEvent * event) const239 void HTMLTextAreaElement::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent* event) const
240 {
241 ASSERT(event);
242 ASSERT(renderer());
243 int signedMaxLength = maxLength();
244 if (signedMaxLength < 0)
245 return;
246 unsigned unsignedMaxLength = static_cast<unsigned>(signedMaxLength);
247
248 unsigned currentLength = numGraphemeClusters(toRenderTextControl(renderer())->text());
249 // selectionLength represents the selection length of this text field to be
250 // removed by this insertion.
251 // If the text field has no focus, we don't need to take account of the
252 // selection length. The selection is the source of text drag-and-drop in
253 // that case, and nothing in the text field will be removed.
254 unsigned selectionLength = focused() ? numGraphemeClusters(plainText(document()->frame()->selection()->selection().toNormalizedRange().get())) : 0;
255 ASSERT(currentLength >= selectionLength);
256 unsigned baseLength = currentLength - selectionLength;
257 unsigned appendableLength = unsignedMaxLength > baseLength ? unsignedMaxLength - baseLength : 0;
258 event->setText(sanitizeUserInputValue(event->text(), appendableLength));
259 }
260
sanitizeUserInputValue(const String & proposedValue,unsigned maxLength)261 String HTMLTextAreaElement::sanitizeUserInputValue(const String& proposedValue, unsigned maxLength)
262 {
263 return proposedValue.left(numCharactersInGraphemeClusters(proposedValue, maxLength));
264 }
265
rendererWillBeDestroyed()266 void HTMLTextAreaElement::rendererWillBeDestroyed()
267 {
268 updateValue();
269 }
270
updateValue() const271 void HTMLTextAreaElement::updateValue() const
272 {
273 if (formControlValueMatchesRenderer())
274 return;
275
276 ASSERT(renderer());
277 m_value = toRenderTextControl(renderer())->text();
278 const_cast<HTMLTextAreaElement*>(this)->setFormControlValueMatchesRenderer(true);
279 notifyFormStateChanged(this);
280 m_isDirty = true;
281 const_cast<HTMLTextAreaElement*>(this)->updatePlaceholderVisibility(false);
282 }
283
value() const284 String HTMLTextAreaElement::value() const
285 {
286 updateValue();
287 return m_value;
288 }
289
setValue(const String & value)290 void HTMLTextAreaElement::setValue(const String& value)
291 {
292 setValueCommon(value);
293 m_isDirty = true;
294 setNeedsValidityCheck();
295 setTextAsOfLastFormControlChangeEvent(value);
296 }
297
setNonDirtyValue(const String & value)298 void HTMLTextAreaElement::setNonDirtyValue(const String& value)
299 {
300 setValueCommon(value);
301 m_isDirty = false;
302 setNeedsValidityCheck();
303 setTextAsOfLastFormControlChangeEvent(value);
304 }
305
setValueCommon(const String & value)306 void HTMLTextAreaElement::setValueCommon(const String& value)
307 {
308 // Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
309 // We normalize line endings coming from JavaScript here.
310 String normalizedValue = value.isNull() ? "" : value;
311 normalizedValue.replace("\r\n", "\n");
312 normalizedValue.replace('\r', '\n');
313
314 // Return early because we don't want to move the caret or trigger other side effects
315 // when the value isn't changing. This matches Firefox behavior, at least.
316 if (normalizedValue == this->value())
317 return;
318
319 m_value = normalizedValue;
320 updatePlaceholderVisibility(false);
321 setNeedsStyleRecalc();
322 setFormControlValueMatchesRenderer(true);
323
324 // Set the caret to the end of the text value.
325 if (document()->focusedNode() == this) {
326 unsigned endOfString = m_value.length();
327 setSelectionRange(endOfString, endOfString);
328 }
329
330 notifyFormStateChanged(this);
331 }
332
defaultValue() const333 String HTMLTextAreaElement::defaultValue() const
334 {
335 String value = "";
336
337 // Since there may be comments, ignore nodes other than text nodes.
338 for (Node* n = firstChild(); n; n = n->nextSibling()) {
339 if (n->isTextNode())
340 value += static_cast<Text*>(n)->data();
341 }
342
343 return value;
344 }
345
setDefaultValue(const String & defaultValue)346 void HTMLTextAreaElement::setDefaultValue(const String& defaultValue)
347 {
348 // To preserve comments, remove only the text nodes, then add a single text node.
349
350 Vector<RefPtr<Node> > textNodes;
351 for (Node* n = firstChild(); n; n = n->nextSibling()) {
352 if (n->isTextNode())
353 textNodes.append(n);
354 }
355 ExceptionCode ec;
356 size_t size = textNodes.size();
357 for (size_t i = 0; i < size; ++i)
358 removeChild(textNodes[i].get(), ec);
359
360 // Normalize line endings.
361 String value = defaultValue;
362 value.replace("\r\n", "\n");
363 value.replace('\r', '\n');
364
365 insertBefore(document()->createTextNode(value), firstChild(), ec);
366
367 if (!m_isDirty)
368 setNonDirtyValue(value);
369 }
370
maxLength() const371 int HTMLTextAreaElement::maxLength() const
372 {
373 bool ok;
374 int value = getAttribute(maxlengthAttr).string().toInt(&ok);
375 return ok && value >= 0 ? value : -1;
376 }
377
setMaxLength(int newValue,ExceptionCode & ec)378 void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionCode& ec)
379 {
380 if (newValue < 0)
381 ec = INDEX_SIZE_ERR;
382 else
383 setAttribute(maxlengthAttr, String::number(newValue));
384 }
385
tooLong(const String & value,NeedsToCheckDirtyFlag check) const386 bool HTMLTextAreaElement::tooLong(const String& value, NeedsToCheckDirtyFlag check) const
387 {
388 // Return false for the default value even if it is longer than maxLength.
389 if (check == CheckDirtyFlag && !m_isDirty)
390 return false;
391
392 int max = maxLength();
393 if (max < 0)
394 return false;
395 return numGraphemeClusters(value) > static_cast<unsigned>(max);
396 }
397
isValidValue(const String & candidate) const398 bool HTMLTextAreaElement::isValidValue(const String& candidate) const
399 {
400 return !valueMissing(candidate) && !tooLong(candidate, IgnoreDirtyFlag);
401 }
402
accessKeyAction(bool)403 void HTMLTextAreaElement::accessKeyAction(bool)
404 {
405 focus();
406 }
407
setCols(int cols)408 void HTMLTextAreaElement::setCols(int cols)
409 {
410 setAttribute(colsAttr, String::number(cols));
411 }
412
setRows(int rows)413 void HTMLTextAreaElement::setRows(int rows)
414 {
415 setAttribute(rowsAttr, String::number(rows));
416 }
417
lastChangeWasUserEdit() const418 bool HTMLTextAreaElement::lastChangeWasUserEdit() const
419 {
420 if (!renderer())
421 return false;
422 return toRenderTextControl(renderer())->lastChangeWasUserEdit();
423 }
424
shouldUseInputMethod() const425 bool HTMLTextAreaElement::shouldUseInputMethod() const
426 {
427 return true;
428 }
429
430 } // namespace
431