03d1912a59322d9cd1a3befbaa851ac12dc7a83d
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / HTMLFormControlElement.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 Apple Inc. All rights reserved.
6  *           (C) 2006 Alexey Proskuryakov (ap@nypop.com)
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  *
23  */
24
25 #include "config.h"
26 #include "core/html/HTMLFormControlElement.h"
27
28 #include "core/dom/PostAttachCallbacks.h"
29 #include "core/events/Event.h"
30 #include "core/events/ThreadLocalEventNames.h"
31 #include "core/html/HTMLFieldSetElement.h"
32 #include "core/html/HTMLFormElement.h"
33 #include "core/html/HTMLInputElement.h"
34 #include "core/html/HTMLLegendElement.h"
35 #include "core/html/ValidityState.h"
36 #include "core/html/forms/ValidationMessage.h"
37 #include "core/frame/UseCounter.h"
38 #include "core/rendering/RenderBox.h"
39 #include "core/rendering/RenderTheme.h"
40 #include "wtf/Vector.h"
41
42 namespace WebCore {
43
44 using namespace HTMLNames;
45 using namespace std;
46
47 HTMLFormControlElement::HTMLFormControlElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
48     : LabelableElement(tagName, document)
49     , m_disabled(false)
50     , m_isAutofilled(false)
51     , m_isReadOnly(false)
52     , m_isRequired(false)
53     , m_valueMatchesRenderer(false)
54     , m_ancestorDisabledState(AncestorDisabledStateUnknown)
55     , m_dataListAncestorState(Unknown)
56     , m_willValidateInitialized(false)
57     , m_willValidate(true)
58     , m_isValid(true)
59     , m_wasChangedSinceLastFormControlChangeEvent(false)
60     , m_wasFocusedByMouse(false)
61 {
62     setHasCustomStyleCallbacks();
63     associateByParser(form);
64 }
65
66 HTMLFormControlElement::~HTMLFormControlElement()
67 {
68     setForm(0);
69 }
70
71 String HTMLFormControlElement::formEnctype() const
72 {
73     const AtomicString& formEnctypeAttr = fastGetAttribute(formenctypeAttr);
74     if (formEnctypeAttr.isNull())
75         return emptyString();
76     return FormSubmission::Attributes::parseEncodingType(formEnctypeAttr);
77 }
78
79 void HTMLFormControlElement::setFormEnctype(const AtomicString& value)
80 {
81     setAttribute(formenctypeAttr, value);
82 }
83
84 String HTMLFormControlElement::formMethod() const
85 {
86     const AtomicString& formMethodAttr = fastGetAttribute(formmethodAttr);
87     if (formMethodAttr.isNull())
88         return emptyString();
89     return FormSubmission::Attributes::methodString(FormSubmission::Attributes::parseMethodType(formMethodAttr));
90 }
91
92 void HTMLFormControlElement::setFormMethod(const AtomicString& value)
93 {
94     setAttribute(formmethodAttr, value);
95 }
96
97 bool HTMLFormControlElement::formNoValidate() const
98 {
99     return fastHasAttribute(formnovalidateAttr);
100 }
101
102 void HTMLFormControlElement::updateAncestorDisabledState() const
103 {
104     HTMLFieldSetElement* fieldSetAncestor = 0;
105     ContainerNode* legendAncestor = 0;
106     for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
107         if (!legendAncestor && ancestor->hasTagName(legendTag))
108             legendAncestor = ancestor;
109         if (ancestor->hasTagName(fieldsetTag)) {
110             fieldSetAncestor = toHTMLFieldSetElement(ancestor);
111             break;
112         }
113     }
114     m_ancestorDisabledState = (fieldSetAncestor && fieldSetAncestor->isDisabledFormControl() && !(legendAncestor && legendAncestor == fieldSetAncestor->legend())) ? AncestorDisabledStateDisabled : AncestorDisabledStateEnabled;
115 }
116
117 void HTMLFormControlElement::ancestorDisabledStateWasChanged()
118 {
119     m_ancestorDisabledState = AncestorDisabledStateUnknown;
120     disabledAttributeChanged();
121 }
122
123 void HTMLFormControlElement::reset()
124 {
125     setAutofilled(false);
126     resetImpl();
127 }
128
129 void HTMLFormControlElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
130 {
131     if (name == formAttr) {
132         formAttributeChanged();
133         UseCounter::count(document(), UseCounter::FormAttribute);
134     } else if (name == disabledAttr) {
135         bool oldDisabled = m_disabled;
136         m_disabled = !value.isNull();
137         if (oldDisabled != m_disabled)
138             disabledAttributeChanged();
139     } else if (name == readonlyAttr) {
140         bool wasReadOnly = m_isReadOnly;
141         m_isReadOnly = !value.isNull();
142         if (wasReadOnly != m_isReadOnly) {
143             setNeedsWillValidateCheck();
144             setNeedsStyleRecalc();
145             if (renderer() && renderer()->style()->hasAppearance())
146                 RenderTheme::theme().stateChanged(renderer(), ReadOnlyState);
147         }
148     } else if (name == requiredAttr) {
149         bool wasRequired = m_isRequired;
150         m_isRequired = !value.isNull();
151         if (wasRequired != m_isRequired)
152             requiredAttributeChanged();
153         UseCounter::count(document(), UseCounter::RequiredAttribute);
154     } else if (name == autofocusAttr) {
155         HTMLElement::parseAttribute(name, value);
156         UseCounter::count(document(), UseCounter::AutoFocusAttribute);
157     } else
158         HTMLElement::parseAttribute(name, value);
159 }
160
161 void HTMLFormControlElement::disabledAttributeChanged()
162 {
163     setNeedsWillValidateCheck();
164     didAffectSelector(AffectedSelectorDisabled | AffectedSelectorEnabled);
165     if (renderer() && renderer()->style()->hasAppearance())
166         RenderTheme::theme().stateChanged(renderer(), EnabledState);
167     if (isDisabledFormControl() && treeScope().adjustedFocusedElement() == this) {
168         // We might want to call blur(), but it's dangerous to dispatch events
169         // here.
170         document().setNeedsFocusedElementCheck();
171     }
172 }
173
174 void HTMLFormControlElement::requiredAttributeChanged()
175 {
176     setNeedsValidityCheck();
177     // Style recalculation is needed because style selectors may include
178     // :required and :optional pseudo-classes.
179     setNeedsStyleRecalc();
180 }
181
182 bool HTMLFormControlElement::supportsAutofocus() const
183 {
184     return false;
185 }
186
187 bool HTMLFormControlElement::isAutofocusable() const
188 {
189     return fastHasAttribute(autofocusAttr) && supportsAutofocus();
190 }
191
192 void HTMLFormControlElement::setAutofilled(bool autofilled)
193 {
194     if (autofilled == m_isAutofilled)
195         return;
196
197     m_isAutofilled = autofilled;
198     setNeedsStyleRecalc();
199 }
200
201 static bool shouldAutofocusOnAttach(const HTMLFormControlElement* element)
202 {
203     if (!element->isAutofocusable())
204         return false;
205     if (element->document().isSandboxed(SandboxAutomaticFeatures)) {
206         // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
207         element->document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked autofocusing on a form control because the form's frame is sandboxed and the 'allow-scripts' permission is not set.");
208         return false;
209     }
210
211     return true;
212 }
213
214 void HTMLFormControlElement::attach(const AttachContext& context)
215 {
216     HTMLElement::attach(context);
217
218     if (!renderer())
219         return;
220
221     // The call to updateFromElement() needs to go after the call through
222     // to the base class's attach() because that can sometimes do a close
223     // on the renderer.
224     renderer()->updateFromElement();
225
226     // FIXME: Autofocus handling should be moved to insertedInto according to
227     // the standard.
228     if (shouldAutofocusOnAttach(this))
229         document().setAutofocusElement(this);
230 }
231
232 void HTMLFormControlElement::didMoveToNewDocument(Document& oldDocument)
233 {
234     FormAssociatedElement::didMoveToNewDocument(oldDocument);
235     HTMLElement::didMoveToNewDocument(oldDocument);
236 }
237
238 Node::InsertionNotificationRequest HTMLFormControlElement::insertedInto(ContainerNode* insertionPoint)
239 {
240     m_ancestorDisabledState = AncestorDisabledStateUnknown;
241     m_dataListAncestorState = Unknown;
242     setNeedsWillValidateCheck();
243     HTMLElement::insertedInto(insertionPoint);
244     FormAssociatedElement::insertedInto(insertionPoint);
245     return InsertionDone;
246 }
247
248 void HTMLFormControlElement::removedFrom(ContainerNode* insertionPoint)
249 {
250     m_validationMessage = nullptr;
251     m_ancestorDisabledState = AncestorDisabledStateUnknown;
252     m_dataListAncestorState = Unknown;
253     HTMLElement::removedFrom(insertionPoint);
254     FormAssociatedElement::removedFrom(insertionPoint);
255 }
256
257 bool HTMLFormControlElement::wasChangedSinceLastFormControlChangeEvent() const
258 {
259     return m_wasChangedSinceLastFormControlChangeEvent;
260 }
261
262 void HTMLFormControlElement::setChangedSinceLastFormControlChangeEvent(bool changed)
263 {
264     m_wasChangedSinceLastFormControlChangeEvent = changed;
265 }
266
267 void HTMLFormControlElement::dispatchChangeEvent()
268 {
269     dispatchScopedEvent(Event::createBubble(EventTypeNames::change));
270 }
271
272 void HTMLFormControlElement::dispatchFormControlChangeEvent()
273 {
274     dispatchChangeEvent();
275     setChangedSinceLastFormControlChangeEvent(false);
276 }
277
278 void HTMLFormControlElement::dispatchFormControlInputEvent()
279 {
280     setChangedSinceLastFormControlChangeEvent(true);
281     HTMLElement::dispatchInputEvent();
282 }
283
284 HTMLFormElement* HTMLFormControlElement::formOwner() const
285 {
286     return FormAssociatedElement::form();
287 }
288
289 bool HTMLFormControlElement::isDisabledFormControl() const
290 {
291     if (m_disabled)
292         return true;
293
294     if (m_ancestorDisabledState == AncestorDisabledStateUnknown)
295         updateAncestorDisabledState();
296     return m_ancestorDisabledState == AncestorDisabledStateDisabled;
297 }
298
299 bool HTMLFormControlElement::isRequired() const
300 {
301     return m_isRequired;
302 }
303
304 String HTMLFormControlElement::resultForDialogSubmit()
305 {
306     return fastGetAttribute(valueAttr);
307 }
308
309 void HTMLFormControlElement::didRecalcStyle(StyleRecalcChange)
310 {
311     if (RenderObject* renderer = this->renderer())
312         renderer->updateFromElement();
313 }
314
315 bool HTMLFormControlElement::supportsFocus() const
316 {
317     return !isDisabledFormControl();
318 }
319
320 bool HTMLFormControlElement::isKeyboardFocusable() const
321 {
322     // Skip tabIndex check in a parent class.
323     return isFocusable();
324 }
325
326 bool HTMLFormControlElement::shouldShowFocusRingOnMouseFocus() const
327 {
328     return false;
329 }
330
331 void HTMLFormControlElement::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection direction)
332 {
333     if (direction != FocusDirectionPage)
334         m_wasFocusedByMouse = direction == FocusDirectionMouse;
335     HTMLElement::dispatchFocusEvent(oldFocusedElement, direction);
336 }
337
338 bool HTMLFormControlElement::shouldHaveFocusAppearance() const
339 {
340     ASSERT(focused());
341     return shouldShowFocusRingOnMouseFocus() || !m_wasFocusedByMouse;
342 }
343
344 void HTMLFormControlElement::willCallDefaultEventHandler(const Event& event)
345 {
346     if (!event.isKeyboardEvent() || event.type() != EventTypeNames::keydown)
347         return;
348     if (!m_wasFocusedByMouse)
349         return;
350     m_wasFocusedByMouse = false;
351     if (renderer())
352         renderer()->repaint();
353 }
354
355
356 short HTMLFormControlElement::tabIndex() const
357 {
358     // Skip the supportsFocus check in HTMLElement.
359     return Element::tabIndex();
360 }
361
362 bool HTMLFormControlElement::recalcWillValidate() const
363 {
364     if (m_dataListAncestorState == Unknown) {
365         for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
366             if (ancestor->hasTagName(datalistTag)) {
367                 m_dataListAncestorState = InsideDataList;
368                 break;
369             }
370         }
371         if (m_dataListAncestorState == Unknown)
372             m_dataListAncestorState = NotInsideDataList;
373     }
374     return m_dataListAncestorState == NotInsideDataList && !isDisabledOrReadOnly();
375 }
376
377 bool HTMLFormControlElement::willValidate() const
378 {
379     if (!m_willValidateInitialized || m_dataListAncestorState == Unknown) {
380         m_willValidateInitialized = true;
381         bool newWillValidate = recalcWillValidate();
382         if (m_willValidate != newWillValidate) {
383             m_willValidate = newWillValidate;
384             const_cast<HTMLFormControlElement*>(this)->setNeedsValidityCheck();
385         }
386     } else {
387         // If the following assertion fails, setNeedsWillValidateCheck() is not
388         // called correctly when something which changes recalcWillValidate() result
389         // is updated.
390         ASSERT(m_willValidate == recalcWillValidate());
391     }
392     return m_willValidate;
393 }
394
395 void HTMLFormControlElement::setNeedsWillValidateCheck()
396 {
397     // We need to recalculate willValidate immediately because willValidate change can causes style change.
398     bool newWillValidate = recalcWillValidate();
399     if (m_willValidateInitialized && m_willValidate == newWillValidate)
400         return;
401     m_willValidateInitialized = true;
402     m_willValidate = newWillValidate;
403     setNeedsValidityCheck();
404     setNeedsStyleRecalc();
405     if (!m_willValidate)
406         hideVisibleValidationMessage();
407 }
408
409 void HTMLFormControlElement::updateVisibleValidationMessage()
410 {
411     Page* page = document().page();
412     if (!page)
413         return;
414     String message;
415     if (renderer() && willValidate())
416         message = validationMessage().stripWhiteSpace();
417     if (!m_validationMessage)
418         m_validationMessage = ValidationMessage::create(this);
419     m_validationMessage->updateValidationMessage(message);
420 }
421
422 void HTMLFormControlElement::hideVisibleValidationMessage()
423 {
424     if (m_validationMessage)
425         m_validationMessage->requestToHideMessage();
426 }
427
428 bool HTMLFormControlElement::checkValidity(Vector<RefPtr<FormAssociatedElement> >* unhandledInvalidControls, CheckValidityDispatchEvents dispatchEvents)
429 {
430     if (!willValidate() || isValidFormControlElement())
431         return true;
432     if (dispatchEvents == CheckValidityDispatchEventsNone)
433         return false;
434     // An event handler can deref this object.
435     RefPtr<HTMLFormControlElement> protector(this);
436     RefPtr<Document> originalDocument(document());
437     bool needsDefaultAction = dispatchEvent(Event::createCancelable(EventTypeNames::invalid));
438     if (needsDefaultAction && unhandledInvalidControls && inDocument() && originalDocument == document())
439         unhandledInvalidControls->append(this);
440     return false;
441 }
442
443 bool HTMLFormControlElement::isValidFormControlElement()
444 {
445     // If the following assertion fails, setNeedsValidityCheck() is not called
446     // correctly when something which changes validity is updated.
447     ASSERT(m_isValid == valid());
448     return m_isValid;
449 }
450
451 void HTMLFormControlElement::setNeedsValidityCheck()
452 {
453     bool newIsValid = valid();
454     if (willValidate() && newIsValid != m_isValid) {
455         // Update style for pseudo classes such as :valid :invalid.
456         setNeedsStyleRecalc();
457     }
458     m_isValid = newIsValid;
459
460     // Updates only if this control already has a validtion message.
461     if (m_validationMessage && m_validationMessage->isVisible()) {
462         // Calls updateVisibleValidationMessage() even if m_isValid is not
463         // changed because a validation message can be chagned.
464         updateVisibleValidationMessage();
465     }
466 }
467
468 void HTMLFormControlElement::setCustomValidity(const String& error)
469 {
470     FormAssociatedElement::setCustomValidity(error);
471     setNeedsValidityCheck();
472 }
473
474 void HTMLFormControlElement::dispatchBlurEvent(Element* newFocusedElement)
475 {
476     HTMLElement::dispatchBlurEvent(newFocusedElement);
477     hideVisibleValidationMessage();
478 }
479
480 bool HTMLFormControlElement::isSuccessfulSubmitButton() const
481 {
482     return canBeSuccessfulSubmitButton() && !isDisabledFormControl();
483 }
484
485 bool HTMLFormControlElement::isDefaultButtonForForm() const
486 {
487     return isSuccessfulSubmitButton() && form() && form()->defaultButton() == this;
488 }
489
490 HTMLFormControlElement* HTMLFormControlElement::enclosingFormControlElement(Node* node)
491 {
492     for (; node; node = node->parentNode()) {
493         if (node->isElementNode() && toElement(node)->isFormControlElement())
494             return toHTMLFormControlElement(node);
495     }
496     return 0;
497 }
498
499 String HTMLFormControlElement::nameForAutofill() const
500 {
501     String fullName = name();
502     String trimmedName = fullName.stripWhiteSpace();
503     if (!trimmedName.isEmpty())
504         return trimmedName;
505     fullName = getIdAttribute();
506     trimmedName = fullName.stripWhiteSpace();
507     return trimmedName;
508 }
509
510 } // namespace Webcore