[Release] Webkit-EFL Ver. 2.0_beta_118996_0.6.24
[framework/web/webkit-efl.git] / Source / WebCore / html / HTMLTextAreaElement.cpp
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 "Document.h"
33 #include "ElementShadow.h"
34 #include "Event.h"
35 #include "EventNames.h"
36 #include "ExceptionCode.h"
37 #include "FormDataList.h"
38 #include "Frame.h"
39 #include "HTMLNames.h"
40 #include "LocalizedStrings.h"
41 #include "RenderTextControlMultiLine.h"
42 #include "ShadowRoot.h"
43 #include "Text.h"
44 #include "TextControlInnerElements.h"
45 #include "TextIterator.h"
46 #include <wtf/StdLibExtras.h>
47 #include <wtf/text/StringBuilder.h>
48
49 namespace WebCore {
50
51 using namespace HTMLNames;
52
53 static const int defaultRows = 2;
54 static const int defaultCols = 20;
55
56 // On submission, LF characters are converted into CRLF.
57 // This function returns number of characters considering this.
58 static unsigned computeLengthForSubmission(const String& text)
59 {
60     unsigned count =  numGraphemeClusters(text);
61     unsigned length = text.length();
62     for (unsigned i = 0; i < length; i++) {
63         if (text[i] == '\n')
64             count++;
65     }
66     return count;
67 }
68
69 HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
70     : HTMLTextFormControlElement(tagName, document, form)
71     , m_rows(defaultRows)
72     , m_cols(defaultCols)
73     , m_wrap(SoftWrap)
74     , m_isDirty(false)
75     , m_wasModifiedByUser(false)
76 {
77     ASSERT(hasTagName(textareaTag));
78     setFormControlValueMatchesRenderer(true);
79 }
80
81 PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
82 {
83     RefPtr<HTMLTextAreaElement> textArea = adoptRef(new HTMLTextAreaElement(tagName, document, form));
84     textArea->createShadowSubtree();
85     return textArea.release();
86 }
87
88 void HTMLTextAreaElement::createShadowSubtree()
89 {
90     ASSERT(!shadow());
91     RefPtr<ShadowRoot> root = ShadowRoot::create(this, ShadowRoot::CreatingUserAgentShadowRoot);
92     root->appendChild(TextControlInnerTextElement::create(document()), ASSERT_NO_EXCEPTION);
93 }
94
95 const AtomicString& HTMLTextAreaElement::formControlType() const
96 {
97     DEFINE_STATIC_LOCAL(const AtomicString, textarea, ("textarea"));
98     return textarea;
99 }
100
101 bool HTMLTextAreaElement::saveFormControlState(String& result) const
102 {
103     String currentValue = value();
104     if (currentValue == defaultValue())
105         return false;
106     result = currentValue;
107     return true;
108 }
109
110 void HTMLTextAreaElement::restoreFormControlState(const String& state)
111 {
112     setValue(state);
113 }
114
115 void HTMLTextAreaElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
116 {
117     HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
118     setLastChangeWasNotUserEdit();
119     if (m_isDirty)
120         setInnerTextValue(value());
121     else
122         setNonDirtyValue(defaultValue());
123 }
124
125 bool HTMLTextAreaElement::isPresentationAttribute(const QualifiedName& name) const
126 {
127     if (name == alignAttr) {
128         // Don't map 'align' attribute.  This matches what Firefox, Opera and IE do.
129         // See http://bugs.webkit.org/show_bug.cgi?id=7075
130         return false;
131     }
132
133     if (name == wrapAttr)
134         return true;
135     return HTMLTextFormControlElement::isPresentationAttribute(name);
136 }
137
138 void HTMLTextAreaElement::collectStyleForAttribute(const Attribute& attribute, StylePropertySet* style)
139 {
140     if (attribute.name() == wrapAttr) {
141         if (shouldWrapText()) {
142             addPropertyToAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePreWrap);
143             addPropertyToAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
144         } else {
145             addPropertyToAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePre);
146             addPropertyToAttributeStyle(style, CSSPropertyWordWrap, CSSValueNormal);
147         }
148     } else
149         HTMLTextFormControlElement::collectStyleForAttribute(attribute, style);
150 }
151
152 void HTMLTextAreaElement::parseAttribute(const Attribute& attribute)
153 {
154     if (attribute.name() == rowsAttr) {
155         int rows = attribute.value().toInt();
156         if (rows <= 0)
157             rows = defaultRows;
158         if (m_rows != rows) {
159             m_rows = rows;
160             if (renderer())
161                 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
162         }
163     } else if (attribute.name() == colsAttr) {
164         int cols = attribute.value().toInt();
165         if (cols <= 0)
166             cols = defaultCols;
167         if (m_cols != cols) {
168             m_cols = cols;
169             if (renderer())
170                 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
171         }
172     } else if (attribute.name() == wrapAttr) {
173         // The virtual/physical values were a Netscape extension of HTML 3.0, now deprecated.
174         // The soft/hard /off values are a recommendation for HTML 4 extension by IE and NS 4.
175         WrapMethod wrap;
176         if (equalIgnoringCase(attribute.value(), "physical") || equalIgnoringCase(attribute.value(), "hard") || equalIgnoringCase(attribute.value(), "on"))
177             wrap = HardWrap;
178         else if (equalIgnoringCase(attribute.value(), "off"))
179             wrap = NoWrap;
180         else
181             wrap = SoftWrap;
182         if (wrap != m_wrap) {
183             m_wrap = wrap;
184             if (renderer())
185                 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
186         }
187     } else if (attribute.name() == accesskeyAttr) {
188         // ignore for the moment
189     } else if (attribute.name() == maxlengthAttr)
190         setNeedsValidityCheck();
191     else
192         HTMLTextFormControlElement::parseAttribute(attribute);
193 }
194
195 RenderObject* HTMLTextAreaElement::createRenderer(RenderArena* arena, RenderStyle*)
196 {
197     return new (arena) RenderTextControlMultiLine(this);
198 }
199
200 bool HTMLTextAreaElement::appendFormData(FormDataList& encoding, bool)
201 {
202     if (name().isEmpty())
203         return false;
204
205     document()->updateLayout();
206
207     const String& text = (m_wrap == HardWrap) ? valueWithHardLineBreaks() : value();
208     encoding.appendData(name(), text);
209
210     const AtomicString& dirnameAttrValue = fastGetAttribute(dirnameAttr);
211     if (!dirnameAttrValue.isNull())
212         encoding.appendData(dirnameAttrValue, directionForFormData());
213     return true;    
214 }
215
216 void HTMLTextAreaElement::reset()
217 {
218     setNonDirtyValue(defaultValue());
219 }
220
221 bool HTMLTextAreaElement::isKeyboardFocusable(KeyboardEvent*) const
222 {
223     // If a given text area can be focused at all, then it will always be keyboard focusable.
224     return isFocusable();
225 }
226
227 bool HTMLTextAreaElement::isMouseFocusable() const
228 {
229     return isFocusable();
230 }
231
232 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
233 {
234     if (!restorePreviousSelection || !hasCachedSelection()) {
235         // If this is the first focus, set a caret at the beginning of the text.  
236         // This matches some browsers' behavior; see bug 11746 Comment #15.
237         // http://bugs.webkit.org/show_bug.cgi?id=11746#c15
238         setSelectionRange(0, 0);
239     } else
240         restoreCachedSelection();
241
242     if (document()->frame())
243         document()->frame()->selection()->revealSelection();
244 }
245
246 void HTMLTextAreaElement::defaultEventHandler(Event* event)
247 {
248     if (renderer() && (event->isMouseEvent() || event->isDragEvent() || event->hasInterface(eventNames().interfaceForWheelEvent) || event->type() == eventNames().blurEvent))
249         forwardEvent(event);
250     else if (renderer() && event->isBeforeTextInsertedEvent())
251         handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(event));
252
253     HTMLTextFormControlElement::defaultEventHandler(event);
254 }
255
256 void HTMLTextAreaElement::subtreeHasChanged()
257 {
258     setChangedSinceLastFormControlChangeEvent(true);
259     setFormControlValueMatchesRenderer(false);
260     setNeedsValidityCheck();
261
262     if (!focused())
263         return;
264
265     if (Frame* frame = document()->frame())
266         frame->editor()->textDidChangeInTextArea(this);
267     // When typing in a textarea, childrenChanged is not called, so we need to force the directionality check.
268     calculateAndAdjustDirectionality();
269 }
270
271 void HTMLTextAreaElement::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent* event) const
272 {
273     ASSERT(event);
274     ASSERT(renderer());
275     int signedMaxLength = maxLength();
276     if (signedMaxLength < 0)
277         return;
278     unsigned unsignedMaxLength = static_cast<unsigned>(signedMaxLength);
279
280     unsigned currentLength = computeLengthForSubmission(innerTextValue());
281     // selectionLength represents the selection length of this text field to be
282     // removed by this insertion.
283     // If the text field has no focus, we don't need to take account of the
284     // selection length. The selection is the source of text drag-and-drop in
285     // that case, and nothing in the text field will be removed.
286     unsigned selectionLength = focused() ? computeLengthForSubmission(plainText(document()->frame()->selection()->selection().toNormalizedRange().get())) : 0;
287     ASSERT(currentLength >= selectionLength);
288     unsigned baseLength = currentLength - selectionLength;
289     unsigned appendableLength = unsignedMaxLength > baseLength ? unsignedMaxLength - baseLength : 0;
290     event->setText(sanitizeUserInputValue(event->text(), appendableLength));
291 }
292
293 String HTMLTextAreaElement::sanitizeUserInputValue(const String& proposedValue, unsigned maxLength)
294 {
295     return proposedValue.left(numCharactersInGraphemeClusters(proposedValue, maxLength));
296 }
297
298 HTMLElement* HTMLTextAreaElement::innerTextElement() const
299 {
300     Node* node = shadow()->oldestShadowRoot()->firstChild();
301     ASSERT(!node || node->hasTagName(divTag));
302     return toHTMLElement(node);
303 }
304
305 void HTMLTextAreaElement::rendererWillBeDestroyed()
306 {
307     updateValue();
308 }
309
310 void HTMLTextAreaElement::updateValue() const
311 {
312     if (formControlValueMatchesRenderer())
313         return;
314
315     ASSERT(renderer());
316     m_value = innerTextValue();
317     const_cast<HTMLTextAreaElement*>(this)->setFormControlValueMatchesRenderer(true);
318     const_cast<HTMLTextAreaElement*>(this)->notifyFormStateChanged();
319     m_isDirty = true;
320     m_wasModifiedByUser = true;
321     const_cast<HTMLTextAreaElement*>(this)->updatePlaceholderVisibility(false);
322 }
323
324 String HTMLTextAreaElement::value() const
325 {
326     updateValue();
327     return m_value;
328 }
329
330 void HTMLTextAreaElement::setValue(const String& value)
331 {
332     setValueCommon(value);
333     m_isDirty = true;
334     setNeedsValidityCheck();
335 }
336
337 void HTMLTextAreaElement::setNonDirtyValue(const String& value)
338 {
339     setValueCommon(value);
340     m_isDirty = false;
341     setNeedsValidityCheck();
342 }
343
344 void HTMLTextAreaElement::setValueCommon(const String& newValue)
345 {
346     m_wasModifiedByUser = false;
347     // Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
348     // We normalize line endings coming from JavaScript here.
349     String normalizedValue = newValue.isNull() ? "" : newValue;
350     normalizedValue.replace("\r\n", "\n");
351     normalizedValue.replace('\r', '\n');
352
353     // Return early because we don't want to move the caret or trigger other side effects
354     // when the value isn't changing. This matches Firefox behavior, at least.
355     if (normalizedValue == value())
356         return;
357
358     m_value = normalizedValue;
359     setInnerTextValue(m_value);
360     setLastChangeWasNotUserEdit();
361     updatePlaceholderVisibility(false);
362     setNeedsStyleRecalc();
363     setFormControlValueMatchesRenderer(true);
364
365     // Set the caret to the end of the text value.
366     if (document()->focusedNode() == this) {
367         unsigned endOfString = m_value.length();
368         setSelectionRange(endOfString, endOfString);
369     }
370
371     notifyFormStateChanged();
372     setTextAsOfLastFormControlChangeEvent(normalizedValue);
373 }
374
375 String HTMLTextAreaElement::defaultValue() const
376 {
377     StringBuilder value;
378
379     // Since there may be comments, ignore nodes other than text nodes.
380     for (Node* n = firstChild(); n; n = n->nextSibling()) {
381         if (n->isTextNode())
382             value.append(toText(n)->data());
383     }
384
385     return value.toString();
386 }
387
388 void HTMLTextAreaElement::setDefaultValue(const String& defaultValue)
389 {
390     RefPtr<Node> protectFromMutationEvents(this);
391
392     // To preserve comments, remove only the text nodes, then add a single text node.
393     Vector<RefPtr<Node> > textNodes;
394     for (Node* n = firstChild(); n; n = n->nextSibling()) {
395         if (n->isTextNode())
396             textNodes.append(n);
397     }
398     ExceptionCode ec;
399     size_t size = textNodes.size();
400     for (size_t i = 0; i < size; ++i)
401         removeChild(textNodes[i].get(), ec);
402
403     // Normalize line endings.
404     String value = defaultValue;
405     value.replace("\r\n", "\n");
406     value.replace('\r', '\n');
407
408     insertBefore(document()->createTextNode(value), firstChild(), ec);
409
410     if (!m_isDirty)
411         setNonDirtyValue(value);
412 }
413
414 int HTMLTextAreaElement::maxLength() const
415 {
416     bool ok;
417     int value = getAttribute(maxlengthAttr).string().toInt(&ok);
418     return ok && value >= 0 ? value : -1;
419 }
420
421 void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionCode& ec)
422 {
423     if (newValue < 0)
424         ec = INDEX_SIZE_ERR;
425     else
426         setAttribute(maxlengthAttr, String::number(newValue));
427 }
428
429 String HTMLTextAreaElement::validationMessage() const
430 {
431     if (!willValidate())
432         return String();
433
434     if (customError())
435         return customValidationMessage();
436
437     if (valueMissing())
438         return validationMessageValueMissingText();
439
440     if (tooLong())
441         return validationMessageTooLongText(computeLengthForSubmission(value()), maxLength());
442
443     return String();
444 }
445
446 bool HTMLTextAreaElement::valueMissing() const
447 {
448     return willValidate() && valueMissing(value());
449 }
450
451 bool HTMLTextAreaElement::tooLong() const
452 {
453     return willValidate() && tooLong(value(), CheckDirtyFlag);
454 }
455
456 bool HTMLTextAreaElement::tooLong(const String& value, NeedsToCheckDirtyFlag check) const
457 {
458     // Return false for the default value or value set by script even if it is
459     // longer than maxLength.
460     if (check == CheckDirtyFlag && !m_wasModifiedByUser)
461         return false;
462
463     int max = maxLength();
464     if (max < 0)
465         return false;
466     return computeLengthForSubmission(value) > static_cast<unsigned>(max);
467 }
468
469 bool HTMLTextAreaElement::isValidValue(const String& candidate) const
470 {
471     return !valueMissing(candidate) && !tooLong(candidate, IgnoreDirtyFlag);
472 }
473
474 void HTMLTextAreaElement::accessKeyAction(bool)
475 {
476     focus();
477 }
478
479 void HTMLTextAreaElement::setCols(int cols)
480 {
481     setAttribute(colsAttr, String::number(cols));
482 }
483
484 void HTMLTextAreaElement::setRows(int rows)
485 {
486     setAttribute(rowsAttr, String::number(rows));
487 }
488
489 bool HTMLTextAreaElement::shouldUseInputMethod()
490 {
491     return true;
492 }
493
494 HTMLElement* HTMLTextAreaElement::placeholderElement() const
495 {
496     return m_placeholder.get();
497 }
498
499 void HTMLTextAreaElement::attach()
500 {
501     HTMLTextFormControlElement::attach();
502     fixPlaceholderRenderer(m_placeholder.get(), innerTextElement());
503 }
504
505 void HTMLTextAreaElement::updatePlaceholderText()
506 {
507     ExceptionCode ec = 0;
508     String placeholderText = strippedPlaceholder();
509     if (placeholderText.isEmpty()) {
510         if (m_placeholder) {
511             shadow()->oldestShadowRoot()->removeChild(m_placeholder.get(), ec);
512             ASSERT(!ec);
513             m_placeholder.clear();
514         }
515         return;
516     }
517     if (!m_placeholder) {
518         m_placeholder = HTMLDivElement::create(document());
519         m_placeholder->setShadowPseudoId("-webkit-input-placeholder");
520         shadow()->oldestShadowRoot()->insertBefore(m_placeholder, innerTextElement()->nextSibling(), ec);
521         ASSERT(!ec);
522     }
523     m_placeholder->setInnerText(placeholderText, ec);
524     ASSERT(!ec);
525     fixPlaceholderRenderer(m_placeholder.get(), innerTextElement());
526 }
527
528 }