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)
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.
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.
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.
26 #include "core/html/HTMLFormControlElement.h"
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"
44 using namespace HTMLNames;
47 HTMLFormControlElement::HTMLFormControlElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
48 : LabelableElement(tagName, document)
50 , m_isAutofilled(false)
53 , m_valueMatchesRenderer(false)
54 , m_ancestorDisabledState(AncestorDisabledStateUnknown)
55 , m_dataListAncestorState(Unknown)
56 , m_willValidateInitialized(false)
57 , m_willValidate(true)
59 , m_wasChangedSinceLastFormControlChangeEvent(false)
60 , m_wasFocusedByMouse(false)
62 setHasCustomStyleCallbacks();
63 associateByParser(form);
66 HTMLFormControlElement::~HTMLFormControlElement()
71 String HTMLFormControlElement::formEnctype() const
73 const AtomicString& formEnctypeAttr = fastGetAttribute(formenctypeAttr);
74 if (formEnctypeAttr.isNull())
76 return FormSubmission::Attributes::parseEncodingType(formEnctypeAttr);
79 void HTMLFormControlElement::setFormEnctype(const AtomicString& value)
81 setAttribute(formenctypeAttr, value);
84 String HTMLFormControlElement::formMethod() const
86 const AtomicString& formMethodAttr = fastGetAttribute(formmethodAttr);
87 if (formMethodAttr.isNull())
89 return FormSubmission::Attributes::methodString(FormSubmission::Attributes::parseMethodType(formMethodAttr));
92 void HTMLFormControlElement::setFormMethod(const AtomicString& value)
94 setAttribute(formmethodAttr, value);
97 bool HTMLFormControlElement::formNoValidate() const
99 return fastHasAttribute(formnovalidateAttr);
102 void HTMLFormControlElement::updateAncestorDisabledState() const
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);
114 m_ancestorDisabledState = (fieldSetAncestor && fieldSetAncestor->isDisabledFormControl() && !(legendAncestor && legendAncestor == fieldSetAncestor->legend())) ? AncestorDisabledStateDisabled : AncestorDisabledStateEnabled;
117 void HTMLFormControlElement::ancestorDisabledStateWasChanged()
119 m_ancestorDisabledState = AncestorDisabledStateUnknown;
120 disabledAttributeChanged();
123 void HTMLFormControlElement::reset()
125 setAutofilled(false);
129 void HTMLFormControlElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
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);
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);
158 HTMLElement::parseAttribute(name, value);
161 void HTMLFormControlElement::disabledAttributeChanged()
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
170 document().setNeedsFocusedElementCheck();
174 void HTMLFormControlElement::requiredAttributeChanged()
176 setNeedsValidityCheck();
177 // Style recalculation is needed because style selectors may include
178 // :required and :optional pseudo-classes.
179 setNeedsStyleRecalc();
182 bool HTMLFormControlElement::supportsAutofocus() const
187 bool HTMLFormControlElement::isAutofocusable() const
189 return fastHasAttribute(autofocusAttr) && supportsAutofocus();
192 void HTMLFormControlElement::setAutofilled(bool autofilled)
194 if (autofilled == m_isAutofilled)
197 m_isAutofilled = autofilled;
198 setNeedsStyleRecalc();
201 static bool shouldAutofocusOnAttach(const HTMLFormControlElement* element)
203 if (!element->isAutofocusable())
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.");
214 void HTMLFormControlElement::attach(const AttachContext& context)
216 HTMLElement::attach(context);
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
224 renderer()->updateFromElement();
226 // FIXME: Autofocus handling should be moved to insertedInto according to
228 if (shouldAutofocusOnAttach(this))
229 document().setAutofocusElement(this);
232 void HTMLFormControlElement::didMoveToNewDocument(Document& oldDocument)
234 FormAssociatedElement::didMoveToNewDocument(oldDocument);
235 HTMLElement::didMoveToNewDocument(oldDocument);
238 Node::InsertionNotificationRequest HTMLFormControlElement::insertedInto(ContainerNode* insertionPoint)
240 m_ancestorDisabledState = AncestorDisabledStateUnknown;
241 m_dataListAncestorState = Unknown;
242 setNeedsWillValidateCheck();
243 HTMLElement::insertedInto(insertionPoint);
244 FormAssociatedElement::insertedInto(insertionPoint);
245 return InsertionDone;
248 void HTMLFormControlElement::removedFrom(ContainerNode* insertionPoint)
250 m_validationMessage = nullptr;
251 m_ancestorDisabledState = AncestorDisabledStateUnknown;
252 m_dataListAncestorState = Unknown;
253 HTMLElement::removedFrom(insertionPoint);
254 FormAssociatedElement::removedFrom(insertionPoint);
257 bool HTMLFormControlElement::wasChangedSinceLastFormControlChangeEvent() const
259 return m_wasChangedSinceLastFormControlChangeEvent;
262 void HTMLFormControlElement::setChangedSinceLastFormControlChangeEvent(bool changed)
264 m_wasChangedSinceLastFormControlChangeEvent = changed;
267 void HTMLFormControlElement::dispatchChangeEvent()
269 dispatchScopedEvent(Event::createBubble(EventTypeNames::change));
272 void HTMLFormControlElement::dispatchFormControlChangeEvent()
274 dispatchChangeEvent();
275 setChangedSinceLastFormControlChangeEvent(false);
278 void HTMLFormControlElement::dispatchFormControlInputEvent()
280 setChangedSinceLastFormControlChangeEvent(true);
281 HTMLElement::dispatchInputEvent();
284 HTMLFormElement* HTMLFormControlElement::formOwner() const
286 return FormAssociatedElement::form();
289 bool HTMLFormControlElement::isDisabledFormControl() const
294 if (m_ancestorDisabledState == AncestorDisabledStateUnknown)
295 updateAncestorDisabledState();
296 return m_ancestorDisabledState == AncestorDisabledStateDisabled;
299 bool HTMLFormControlElement::isRequired() const
304 String HTMLFormControlElement::resultForDialogSubmit()
306 return fastGetAttribute(valueAttr);
309 void HTMLFormControlElement::didRecalcStyle(StyleRecalcChange)
311 if (RenderObject* renderer = this->renderer())
312 renderer->updateFromElement();
315 bool HTMLFormControlElement::supportsFocus() const
317 return !isDisabledFormControl();
320 bool HTMLFormControlElement::isKeyboardFocusable() const
322 // Skip tabIndex check in a parent class.
323 return isFocusable();
326 bool HTMLFormControlElement::shouldShowFocusRingOnMouseFocus() const
331 void HTMLFormControlElement::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection direction)
333 if (direction != FocusDirectionPage)
334 m_wasFocusedByMouse = direction == FocusDirectionMouse;
335 HTMLElement::dispatchFocusEvent(oldFocusedElement, direction);
338 bool HTMLFormControlElement::shouldHaveFocusAppearance() const
341 return shouldShowFocusRingOnMouseFocus() || !m_wasFocusedByMouse;
344 void HTMLFormControlElement::willCallDefaultEventHandler(const Event& event)
346 if (!event.isKeyboardEvent() || event.type() != EventTypeNames::keydown)
348 if (!m_wasFocusedByMouse)
350 m_wasFocusedByMouse = false;
352 renderer()->repaint();
356 short HTMLFormControlElement::tabIndex() const
358 // Skip the supportsFocus check in HTMLElement.
359 return Element::tabIndex();
362 bool HTMLFormControlElement::recalcWillValidate() const
364 if (m_dataListAncestorState == Unknown) {
365 for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
366 if (ancestor->hasTagName(datalistTag)) {
367 m_dataListAncestorState = InsideDataList;
371 if (m_dataListAncestorState == Unknown)
372 m_dataListAncestorState = NotInsideDataList;
374 return m_dataListAncestorState == NotInsideDataList && !isDisabledOrReadOnly();
377 bool HTMLFormControlElement::willValidate() const
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();
387 // If the following assertion fails, setNeedsWillValidateCheck() is not
388 // called correctly when something which changes recalcWillValidate() result
390 ASSERT(m_willValidate == recalcWillValidate());
392 return m_willValidate;
395 void HTMLFormControlElement::setNeedsWillValidateCheck()
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)
401 m_willValidateInitialized = true;
402 m_willValidate = newWillValidate;
403 setNeedsValidityCheck();
404 setNeedsStyleRecalc();
406 hideVisibleValidationMessage();
409 void HTMLFormControlElement::updateVisibleValidationMessage()
411 Page* page = document().page();
415 if (renderer() && willValidate())
416 message = validationMessage().stripWhiteSpace();
417 if (!m_validationMessage)
418 m_validationMessage = ValidationMessage::create(this);
419 m_validationMessage->updateValidationMessage(message);
422 void HTMLFormControlElement::hideVisibleValidationMessage()
424 if (m_validationMessage)
425 m_validationMessage->requestToHideMessage();
428 bool HTMLFormControlElement::checkValidity(Vector<RefPtr<FormAssociatedElement> >* unhandledInvalidControls, CheckValidityDispatchEvents dispatchEvents)
430 if (!willValidate() || isValidFormControlElement())
432 if (dispatchEvents == CheckValidityDispatchEventsNone)
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);
443 bool HTMLFormControlElement::isValidFormControlElement()
445 // If the following assertion fails, setNeedsValidityCheck() is not called
446 // correctly when something which changes validity is updated.
447 ASSERT(m_isValid == valid());
451 void HTMLFormControlElement::setNeedsValidityCheck()
453 bool newIsValid = valid();
454 if (willValidate() && newIsValid != m_isValid) {
455 // Update style for pseudo classes such as :valid :invalid.
456 setNeedsStyleRecalc();
458 m_isValid = newIsValid;
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();
468 void HTMLFormControlElement::setCustomValidity(const String& error)
470 FormAssociatedElement::setCustomValidity(error);
471 setNeedsValidityCheck();
474 void HTMLFormControlElement::dispatchBlurEvent(Element* newFocusedElement)
476 HTMLElement::dispatchBlurEvent(newFocusedElement);
477 hideVisibleValidationMessage();
480 bool HTMLFormControlElement::isSuccessfulSubmitButton() const
482 return canBeSuccessfulSubmitButton() && !isDisabledFormControl();
485 bool HTMLFormControlElement::isDefaultButtonForForm() const
487 return isSuccessfulSubmitButton() && form() && form()->defaultButton() == this;
490 HTMLFormControlElement* HTMLFormControlElement::enclosingFormControlElement(Node* node)
492 for (; node; node = node->parentNode()) {
493 if (node->isElementNode() && toElement(node)->isFormControlElement())
494 return toHTMLFormControlElement(node);
499 String HTMLFormControlElement::nameForAutofill() const
501 String fullName = name();
502 String trimmedName = fullName.stripWhiteSpace();
503 if (!trimmedName.isEmpty())
505 fullName = getIdAttribute();
506 trimmedName = fullName.stripWhiteSpace();
510 } // namespace Webcore