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)
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 "ChromeClient.h"
30 #include "CSSValueKeywords.h"
31 #include "Document.h"
32 #include "Event.h"
33 #include "EventNames.h"
34 #include "FocusController.h"
35 #include "FormDataList.h"
36 #include "Frame.h"
37 #include "HTMLNames.h"
38 #include "MappedAttribute.h"
39 #include "Page.h"
40 #include "RenderStyle.h"
41 #include "RenderTextControlMultiLine.h"
42 #include "ScriptEventListener.h"
43 #include "Text.h"
44 #include "VisibleSelection.h"
45 #include <wtf/StdLibExtras.h>
46
47 #ifdef ANDROID_ACCEPT_CHANGES_TO_FOCUSED_TEXTFIELDS
48 #include "WebViewCore.h"
49 #endif
50
51 namespace WebCore {
52
53 using namespace HTMLNames;
54
55 static const int defaultRows = 2;
56 static const int defaultCols = 20;
57
notifyFormStateChanged(const HTMLTextAreaElement * element)58 static inline void notifyFormStateChanged(const HTMLTextAreaElement* element)
59 {
60 Frame* frame = element->document()->frame();
61 if (!frame)
62 return;
63 frame->page()->chrome()->client()->formStateDidChange(element);
64 }
65
HTMLTextAreaElement(const QualifiedName & tagName,Document * document,HTMLFormElement * form)66 HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
67 : HTMLFormControlElementWithState(tagName, document, form)
68 , m_rows(defaultRows)
69 , m_cols(defaultCols)
70 , m_wrap(SoftWrap)
71 , m_cachedSelectionStart(-1)
72 , m_cachedSelectionEnd(-1)
73 {
74 ASSERT(hasTagName(textareaTag));
75 setFormControlValueMatchesRenderer(true);
76 notifyFormStateChanged(this);
77 }
78
formControlType() const79 const AtomicString& HTMLTextAreaElement::formControlType() const
80 {
81 DEFINE_STATIC_LOCAL(const AtomicString, textarea, ("textarea"));
82 return textarea;
83 }
84
saveFormControlState(String & result) const85 bool HTMLTextAreaElement::saveFormControlState(String& result) const
86 {
87 result = value();
88 return true;
89 }
90
restoreFormControlState(const String & state)91 void HTMLTextAreaElement::restoreFormControlState(const String& state)
92 {
93 setDefaultValue(state);
94 }
95
selectionStart()96 int HTMLTextAreaElement::selectionStart()
97 {
98 if (!renderer())
99 return 0;
100 if (document()->focusedNode() != this && m_cachedSelectionStart >= 0)
101 return m_cachedSelectionStart;
102 return toRenderTextControl(renderer())->selectionStart();
103 }
104
selectionEnd()105 int HTMLTextAreaElement::selectionEnd()
106 {
107 if (!renderer())
108 return 0;
109 if (document()->focusedNode() != this && m_cachedSelectionEnd >= 0)
110 return m_cachedSelectionEnd;
111 return toRenderTextControl(renderer())->selectionEnd();
112 }
113
rendererAfterUpdateLayout(HTMLTextAreaElement * element)114 static RenderTextControl* rendererAfterUpdateLayout(HTMLTextAreaElement* element)
115 {
116 element->document()->updateLayoutIgnorePendingStylesheets();
117 return toRenderTextControl(element->renderer());
118 }
119
setSelectionStart(int start)120 void HTMLTextAreaElement::setSelectionStart(int start)
121 {
122 if (RenderTextControl* renderer = rendererAfterUpdateLayout(this))
123 renderer->setSelectionStart(start);
124 }
125
setSelectionEnd(int end)126 void HTMLTextAreaElement::setSelectionEnd(int end)
127 {
128 if (RenderTextControl* renderer = rendererAfterUpdateLayout(this))
129 renderer->setSelectionEnd(end);
130 }
131
select()132 void HTMLTextAreaElement::select()
133 {
134 if (RenderTextControl* renderer = rendererAfterUpdateLayout(this))
135 renderer->select();
136 }
137
setSelectionRange(int start,int end)138 void HTMLTextAreaElement::setSelectionRange(int start, int end)
139 {
140 if (RenderTextControl* renderer = rendererAfterUpdateLayout(this))
141 renderer->setSelectionRange(start, end);
142 }
143
childrenChanged(bool changedByParser,Node * beforeChange,Node * afterChange,int childCountDelta)144 void HTMLTextAreaElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
145 {
146 setValue(defaultValue());
147 HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
148 }
149
parseMappedAttribute(MappedAttribute * attr)150 void HTMLTextAreaElement::parseMappedAttribute(MappedAttribute* attr)
151 {
152 if (attr->name() == rowsAttr) {
153 int rows = attr->value().toInt();
154 if (rows <= 0)
155 rows = defaultRows;
156 if (m_rows != rows) {
157 m_rows = rows;
158 if (renderer())
159 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
160 }
161 } else if (attr->name() == colsAttr) {
162 int cols = attr->value().toInt();
163 if (cols <= 0)
164 cols = defaultCols;
165 if (m_cols != cols) {
166 m_cols = cols;
167 if (renderer())
168 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
169 }
170 } else if (attr->name() == wrapAttr) {
171 // The virtual/physical values were a Netscape extension of HTML 3.0, now deprecated.
172 // The soft/hard /off values are a recommendation for HTML 4 extension by IE and NS 4.
173 WrapMethod wrap;
174 if (equalIgnoringCase(attr->value(), "physical") || equalIgnoringCase(attr->value(), "hard") || equalIgnoringCase(attr->value(), "on"))
175 wrap = HardWrap;
176 else if (equalIgnoringCase(attr->value(), "off"))
177 wrap = NoWrap;
178 else
179 wrap = SoftWrap;
180 if (wrap != m_wrap) {
181 m_wrap = wrap;
182
183 if (shouldWrapText()) {
184 addCSSProperty(attr, CSSPropertyWhiteSpace, CSSValuePreWrap);
185 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
186 } else {
187 addCSSProperty(attr, CSSPropertyWhiteSpace, CSSValuePre);
188 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueNormal);
189 }
190
191 if (renderer())
192 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
193 }
194 } else if (attr->name() == accesskeyAttr) {
195 // ignore for the moment
196 } else if (attr->name() == alignAttr) {
197 // Don't map 'align' attribute. This matches what Firefox, Opera and IE do.
198 // See http://bugs.webkit.org/show_bug.cgi?id=7075
199 } else if (attr->name() == onfocusAttr)
200 setAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(this, attr));
201 else if (attr->name() == onblurAttr)
202 setAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(this, attr));
203 else if (attr->name() == onselectAttr)
204 setAttributeEventListener(eventNames().selectEvent, createAttributeEventListener(this, attr));
205 else if (attr->name() == onchangeAttr)
206 setAttributeEventListener(eventNames().changeEvent, createAttributeEventListener(this, attr));
207 else
208 HTMLFormControlElementWithState::parseMappedAttribute(attr);
209 }
210
createRenderer(RenderArena * arena,RenderStyle *)211 RenderObject* HTMLTextAreaElement::createRenderer(RenderArena* arena, RenderStyle*)
212 {
213 return new (arena) RenderTextControlMultiLine(this);
214 }
215
appendFormData(FormDataList & encoding,bool)216 bool HTMLTextAreaElement::appendFormData(FormDataList& encoding, bool)
217 {
218 if (name().isEmpty())
219 return false;
220
221 // FIXME: It's not acceptable to ignore the HardWrap setting when there is no renderer.
222 // While we have no evidence this has ever been a practical problem, it would be best to fix it some day.
223 RenderTextControl* control = toRenderTextControl(renderer());
224 const String& text = (m_wrap == HardWrap && control) ? control->textWithHardLineBreaks() : value();
225 encoding.appendData(name(), text);
226 return true;
227 }
228
reset()229 void HTMLTextAreaElement::reset()
230 {
231 setValue(defaultValue());
232 }
233
isKeyboardFocusable(KeyboardEvent *) const234 bool HTMLTextAreaElement::isKeyboardFocusable(KeyboardEvent*) const
235 {
236 // If a given text area can be focused at all, then it will always be keyboard focusable.
237 return isFocusable();
238 }
239
isMouseFocusable() const240 bool HTMLTextAreaElement::isMouseFocusable() const
241 {
242 return isFocusable();
243 }
244
updateFocusAppearance(bool restorePreviousSelection)245 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
246 {
247 ASSERT(renderer());
248 ASSERT(!document()->childNeedsAndNotInStyleRecalc());
249
250 if (!restorePreviousSelection || m_cachedSelectionStart < 0) {
251 #if ENABLE(ON_FIRST_TEXTAREA_FOCUS_SELECT_ALL)
252 // Devices with trackballs or d-pads may focus on a textarea in route
253 // to another focusable node. By selecting all text, the next movement
254 // can more readily be interpreted as moving to the next node.
255 select();
256 #else
257 // If this is the first focus, set a caret at the beginning of the text.
258 // This matches some browsers' behavior; see bug 11746 Comment #15.
259 // http://bugs.webkit.org/show_bug.cgi?id=11746#c15
260 setSelectionRange(0, 0);
261 #endif
262 } else {
263 // Restore the cached selection. This matches other browsers' behavior.
264 setSelectionRange(m_cachedSelectionStart, m_cachedSelectionEnd);
265 }
266
267 if (document()->frame())
268 document()->frame()->revealSelection();
269 }
270
defaultEventHandler(Event * event)271 void HTMLTextAreaElement::defaultEventHandler(Event* event)
272 {
273 if (renderer() && (event->isMouseEvent() || event->isDragEvent() || event->isWheelEvent() || event->type() == eventNames().blurEvent))
274 toRenderTextControlMultiLine(renderer())->forwardEvent(event);
275
276 HTMLFormControlElementWithState::defaultEventHandler(event);
277 }
278
rendererWillBeDestroyed()279 void HTMLTextAreaElement::rendererWillBeDestroyed()
280 {
281 updateValue();
282 }
283
updateValue() const284 void HTMLTextAreaElement::updateValue() const
285 {
286 if (formControlValueMatchesRenderer())
287 return;
288
289 ASSERT(renderer());
290 m_value = toRenderTextControl(renderer())->text();
291 const_cast<HTMLTextAreaElement*>(this)->setFormControlValueMatchesRenderer(true);
292 notifyFormStateChanged(this);
293 }
294
value() const295 String HTMLTextAreaElement::value() const
296 {
297 updateValue();
298 return m_value;
299 }
300
setValue(const String & value)301 void HTMLTextAreaElement::setValue(const String& value)
302 {
303 // Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
304 // We normalize line endings coming from JavaScript here.
305 String normalizedValue = value.isNull() ? "" : value;
306 normalizedValue.replace("\r\n", "\n");
307 normalizedValue.replace('\r', '\n');
308
309 // Return early because we don't want to move the caret or trigger other side effects
310 // when the value isn't changing. This matches Firefox behavior, at least.
311 if (normalizedValue == this->value())
312 return;
313
314 m_value = normalizedValue;
315 setFormControlValueMatchesRenderer(true);
316 if (inDocument())
317 document()->updateStyleIfNeeded();
318 if (renderer())
319 renderer()->updateFromElement();
320
321 // Set the caret to the end of the text value.
322 if (document()->focusedNode() == this) {
323 #ifdef ANDROID_ACCEPT_CHANGES_TO_FOCUSED_TEXTFIELDS
324 // Make sure our UI side textfield changes to match the RenderTextControl
325 android::WebViewCore::getWebViewCore(document()->view())->updateTextfield(this, false, value);
326 #endif
327 unsigned endOfString = m_value.length();
328 setSelectionRange(endOfString, endOfString);
329 }
330
331 setNeedsStyleRecalc();
332 notifyFormStateChanged(this);
333 }
334
defaultValue() const335 String HTMLTextAreaElement::defaultValue() const
336 {
337 String value = "";
338
339 // Since there may be comments, ignore nodes other than text nodes.
340 for (Node* n = firstChild(); n; n = n->nextSibling()) {
341 if (n->isTextNode())
342 value += static_cast<Text*>(n)->data();
343 }
344
345 UChar firstCharacter = value[0];
346 if (firstCharacter == '\r' && value[1] == '\n')
347 value.remove(0, 2);
348 else if (firstCharacter == '\r' || firstCharacter == '\n')
349 value.remove(0, 1);
350
351 return value;
352 }
353
setDefaultValue(const String & defaultValue)354 void HTMLTextAreaElement::setDefaultValue(const String& defaultValue)
355 {
356 // To preserve comments, remove only the text nodes, then add a single text node.
357
358 Vector<RefPtr<Node> > textNodes;
359 for (Node* n = firstChild(); n; n = n->nextSibling()) {
360 if (n->isTextNode())
361 textNodes.append(n);
362 }
363 ExceptionCode ec;
364 size_t size = textNodes.size();
365 for (size_t i = 0; i < size; ++i)
366 removeChild(textNodes[i].get(), ec);
367
368 // Normalize line endings.
369 // Add an extra line break if the string starts with one, since
370 // the code to read default values from the DOM strips the leading one.
371 String value = defaultValue;
372 value.replace("\r\n", "\n");
373 value.replace('\r', '\n');
374 if (value[0] == '\n')
375 value = "\n" + value;
376
377 insertBefore(document()->createTextNode(value), firstChild(), ec);
378
379 setValue(value);
380 }
381
accessKeyAction(bool)382 void HTMLTextAreaElement::accessKeyAction(bool)
383 {
384 focus();
385 }
386
accessKey() const387 const AtomicString& HTMLTextAreaElement::accessKey() const
388 {
389 return getAttribute(accesskeyAttr);
390 }
391
setAccessKey(const String & value)392 void HTMLTextAreaElement::setAccessKey(const String& value)
393 {
394 setAttribute(accesskeyAttr, value);
395 }
396
setCols(int cols)397 void HTMLTextAreaElement::setCols(int cols)
398 {
399 setAttribute(colsAttr, String::number(cols));
400 }
401
setRows(int rows)402 void HTMLTextAreaElement::setRows(int rows)
403 {
404 setAttribute(rowsAttr, String::number(rows));
405 }
406
selection() const407 VisibleSelection HTMLTextAreaElement::selection() const
408 {
409 if (!renderer() || m_cachedSelectionStart < 0 || m_cachedSelectionEnd < 0)
410 return VisibleSelection();
411 return toRenderTextControl(renderer())->selection(m_cachedSelectionStart, m_cachedSelectionEnd);
412 }
413
shouldUseInputMethod() const414 bool HTMLTextAreaElement::shouldUseInputMethod() const
415 {
416 return true;
417 }
418
419 } // namespace
420