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, 2009, 2010, 2011 Apple Inc. All rights reserved.
6 * (C) 2006 Alexey Proskuryakov (ap@nypop.com)
7 * Copyright (C) 2007 Samuel Weinig (sam@webkit.org)
8 * Copyright (C) 2010 Google Inc. All rights reserved.
9 * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
10 * Copyright (C) 2012 Samsung Electronics. All rights reserved.
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 * Boston, MA 02110-1301, USA.
30 #include "core/html/HTMLInputElement.h"
32 #include "CSSPropertyNames.h"
33 #include "HTMLNames.h"
34 #include "RuntimeEnabledFeatures.h"
35 #include "bindings/v8/ExceptionMessages.h"
36 #include "bindings/v8/ExceptionState.h"
37 #include "bindings/v8/ScriptEventListener.h"
38 #include "core/accessibility/AXObjectCache.h"
39 #include "core/dom/Document.h"
40 #include "core/dom/ExceptionCode.h"
41 #include "core/dom/IdTargetObserver.h"
42 #include "core/dom/shadow/ElementShadow.h"
43 #include "core/dom/shadow/InsertionPoint.h"
44 #include "core/dom/shadow/ShadowRoot.h"
45 #include "core/editing/FrameSelection.h"
46 #include "core/editing/SpellChecker.h"
47 #include "core/events/BeforeTextInsertedEvent.h"
48 #include "core/events/KeyboardEvent.h"
49 #include "core/events/MouseEvent.h"
50 #include "core/events/ScopedEventQueue.h"
51 #include "core/events/TouchEvent.h"
52 #include "core/fileapi/FileList.h"
53 #include "core/frame/FrameHost.h"
54 #include "core/frame/FrameView.h"
55 #include "core/frame/LocalFrame.h"
56 #include "core/frame/UseCounter.h"
57 #include "core/html/HTMLCollection.h"
58 #include "core/html/HTMLDataListElement.h"
59 #include "core/html/HTMLFormElement.h"
60 #include "core/html/HTMLImageLoader.h"
61 #include "core/html/HTMLOptionElement.h"
62 #include "core/html/forms/ColorInputType.h"
63 #include "core/html/forms/FileInputType.h"
64 #include "core/html/forms/FormController.h"
65 #include "core/html/forms/InputType.h"
66 #include "core/html/forms/SearchInputType.h"
67 #include "core/html/parser/HTMLParserIdioms.h"
68 #include "core/html/shadow/ShadowElementNames.h"
69 #include "core/page/Chrome.h"
70 #include "core/page/ChromeClient.h"
71 #include "core/rendering/RenderTextControlSingleLine.h"
72 #include "core/rendering/RenderTheme.h"
73 #include "platform/DateTimeChooser.h"
74 #include "platform/Language.h"
75 #include "platform/PlatformMouseEvent.h"
76 #include "platform/text/PlatformLocale.h"
77 #include "wtf/MathExtras.h"
83 using namespace HTMLNames;
85 class ListAttributeTargetObserver : public IdTargetObserver {
86 WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
88 static PassOwnPtrWillBeRawPtr<ListAttributeTargetObserver> create(const AtomicString& id, HTMLInputElement*);
89 virtual void trace(Visitor*) OVERRIDE;
90 virtual void idTargetChanged() OVERRIDE;
93 ListAttributeTargetObserver(const AtomicString& id, HTMLInputElement*);
95 RawPtrWillBeMember<HTMLInputElement> m_element;
98 // FIXME: According to HTML4, the length attribute's value can be arbitrarily
99 // large. However, due to https://bugs.webkit.org/show_bug.cgi?id=14536 things
100 // get rather sluggish when a text field has a larger number of characters than
101 // this, even when just clicking in the text field.
102 const int HTMLInputElement::maximumLength = 524288;
103 const int defaultSize = 20;
104 const int maxSavedResults = 256;
106 HTMLInputElement::HTMLInputElement(Document& document, HTMLFormElement* form, bool createdByParser)
107 : HTMLTextFormControlElement(inputTag, document, form)
108 , m_size(defaultSize)
109 , m_maxLength(maximumLength)
112 , m_reflectsCheckedAttribute(true)
113 , m_isIndeterminate(false)
114 , m_isActivatedSubmit(false)
115 , m_autocomplete(Uninitialized)
116 , m_hasNonEmptyList(false)
117 , m_stateRestored(false)
118 , m_parsingInProgress(createdByParser)
119 , m_valueAttributeWasUpdatedAfterParsing(false)
120 , m_canReceiveDroppedFiles(false)
121 , m_hasTouchEventHandler(false)
122 , m_shouldRevealPassword(false)
123 , m_needsToUpdateViewValue(true)
124 , m_inputType(InputType::createText(*this))
125 , m_inputTypeView(m_inputType)
127 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
128 setHasCustomStyleCallbacks();
130 ScriptWrappable::init(this);
133 PassRefPtrWillBeRawPtr<HTMLInputElement> HTMLInputElement::create(Document& document, HTMLFormElement* form, bool createdByParser)
135 RefPtrWillBeRawPtr<HTMLInputElement> inputElement = adoptRefWillBeRefCountedGarbageCollected(new HTMLInputElement(document, form, createdByParser));
136 inputElement->ensureUserAgentShadowRoot();
137 return inputElement.release();
140 void HTMLInputElement::trace(Visitor* visitor)
142 visitor->trace(m_inputType);
143 visitor->trace(m_inputTypeView);
144 visitor->trace(m_listAttributeTargetObserver);
145 HTMLTextFormControlElement::trace(visitor);
148 HTMLImageLoader* HTMLInputElement::imageLoader()
151 m_imageLoader = adoptPtr(new HTMLImageLoader(this));
152 return m_imageLoader.get();
155 void HTMLInputElement::didAddUserAgentShadowRoot(ShadowRoot&)
157 m_inputTypeView->createShadowSubtree();
160 void HTMLInputElement::willAddFirstAuthorShadowRoot()
162 m_inputTypeView->destroyShadowSubtree();
163 m_inputTypeView = InputTypeView::create(*this);
164 lazyReattachIfAttached();
167 HTMLInputElement::~HTMLInputElement()
170 // Need to remove form association while this is still an HTMLInputElement
171 // so that virtual functions are called correctly.
173 // setForm(0) may register this to a document-level radio button group.
174 // We should unregister it to avoid accessing a deleted object.
176 document().formController().radioButtonGroupScope().removeButton(this);
177 if (m_hasTouchEventHandler)
178 document().didRemoveTouchEventHandler(this);
182 const AtomicString& HTMLInputElement::name() const
184 return m_name.isNull() ? emptyAtom : m_name;
187 Vector<FileChooserFileInfo> HTMLInputElement::filesFromFileInputFormControlState(const FormControlState& state)
189 return FileInputType::filesFromFormControlState(state);
192 HTMLElement* HTMLInputElement::passwordGeneratorButtonElement() const
194 return toHTMLElement(userAgentShadowRoot()->getElementById(ShadowElementNames::passwordGenerator()));
197 bool HTMLInputElement::shouldAutocomplete() const
199 if (m_autocomplete != Uninitialized)
200 return m_autocomplete == On;
201 return HTMLTextFormControlElement::shouldAutocomplete();
204 bool HTMLInputElement::isValidValue(const String& value) const
206 if (!m_inputType->canSetStringValue()) {
207 ASSERT_NOT_REACHED();
210 return !m_inputType->typeMismatchFor(value)
211 && !m_inputType->stepMismatch(value)
212 && !m_inputType->rangeUnderflow(value)
213 && !m_inputType->rangeOverflow(value)
214 && !tooLong(value, IgnoreDirtyFlag)
215 && !m_inputType->patternMismatch(value)
216 && !m_inputType->valueMissing(value);
219 bool HTMLInputElement::tooLong() const
221 return willValidate() && tooLong(value(), CheckDirtyFlag);
224 bool HTMLInputElement::typeMismatch() const
226 return willValidate() && m_inputType->typeMismatch();
229 bool HTMLInputElement::valueMissing() const
231 return willValidate() && m_inputType->valueMissing(value());
234 bool HTMLInputElement::hasBadInput() const
236 return willValidate() && m_inputType->hasBadInput();
239 bool HTMLInputElement::patternMismatch() const
241 return willValidate() && m_inputType->patternMismatch(value());
244 bool HTMLInputElement::tooLong(const String& value, NeedsToCheckDirtyFlag check) const
246 // We use isTextType() instead of supportsMaxLength() because of the
247 // 'virtual' overhead.
250 int max = maxLength();
253 if (check == CheckDirtyFlag) {
254 // Return false for the default value or a value set by a script even if
255 // it is longer than maxLength.
256 if (!hasDirtyValue() || !lastChangeWasUserEdit())
259 return value.length() > static_cast<unsigned>(max);
262 bool HTMLInputElement::rangeUnderflow() const
264 return willValidate() && m_inputType->rangeUnderflow(value());
267 bool HTMLInputElement::rangeOverflow() const
269 return willValidate() && m_inputType->rangeOverflow(value());
272 String HTMLInputElement::validationMessage() const
278 return customValidationMessage();
280 return m_inputType->validationMessage();
283 double HTMLInputElement::minimum() const
285 return m_inputType->minimum();
288 double HTMLInputElement::maximum() const
290 return m_inputType->maximum();
293 bool HTMLInputElement::stepMismatch() const
295 return willValidate() && m_inputType->stepMismatch(value());
298 bool HTMLInputElement::getAllowedValueStep(Decimal* step) const
300 return m_inputType->getAllowedValueStep(step);
303 StepRange HTMLInputElement::createStepRange(AnyStepHandling anyStepHandling) const
305 return m_inputType->createStepRange(anyStepHandling);
308 Decimal HTMLInputElement::findClosestTickMarkValue(const Decimal& value)
310 return m_inputType->findClosestTickMarkValue(value);
313 void HTMLInputElement::stepUp(int n, ExceptionState& exceptionState)
315 m_inputType->stepUp(n, exceptionState);
318 void HTMLInputElement::stepDown(int n, ExceptionState& exceptionState)
320 m_inputType->stepUp(-n, exceptionState);
323 void HTMLInputElement::blur()
325 m_inputTypeView->blur();
328 void HTMLInputElement::defaultBlur()
330 HTMLTextFormControlElement::blur();
333 bool HTMLInputElement::hasCustomFocusLogic() const
335 return m_inputTypeView->hasCustomFocusLogic();
338 bool HTMLInputElement::isKeyboardFocusable() const
340 return m_inputType->isKeyboardFocusable();
343 bool HTMLInputElement::shouldShowFocusRingOnMouseFocus() const
345 return m_inputType->shouldShowFocusRingOnMouseFocus();
348 void HTMLInputElement::updateFocusAppearance(bool restorePreviousSelection)
351 if (!restorePreviousSelection)
354 restoreCachedSelection();
355 if (document().frame())
356 document().frame()->selection().revealSelection();
358 HTMLTextFormControlElement::updateFocusAppearance(restorePreviousSelection);
361 void HTMLInputElement::beginEditing()
363 ASSERT(document().isActive());
364 if (!document().isActive())
370 document().frame()->spellChecker().didBeginEditing(this);
373 void HTMLInputElement::endEditing()
375 ASSERT(document().isActive());
376 if (!document().isActive())
382 LocalFrame* frame = document().frame();
383 frame->spellChecker().didEndEditingOnTextField(this);
384 frame->host()->chrome().client().didEndEditingOnTextField(*this);
387 bool HTMLInputElement::shouldUseInputMethod()
389 return m_inputType->shouldUseInputMethod();
392 void HTMLInputElement::handleFocusEvent(Element* oldFocusedElement, FocusType type)
394 m_inputTypeView->handleFocusEvent(oldFocusedElement, type);
395 m_inputType->enableSecureTextInput();
398 void HTMLInputElement::handleBlurEvent()
400 m_inputType->disableSecureTextInput();
401 m_inputTypeView->handleBlurEvent();
404 void HTMLInputElement::setType(const AtomicString& type)
406 setAttribute(typeAttr, type);
409 void HTMLInputElement::updateType()
411 const AtomicString& newTypeName = InputType::normalizeTypeName(fastGetAttribute(typeAttr));
413 if (m_inputType->formControlType() == newTypeName)
416 RefPtrWillBeRawPtr<InputType> newType = InputType::create(*this, newTypeName);
417 removeFromRadioButtonGroup();
419 bool didStoreValue = m_inputType->storesValueSeparateFromAttribute();
420 bool didRespectHeightAndWidth = m_inputType->shouldRespectHeightAndWidthAttributes();
422 m_inputTypeView->destroyShadowSubtree();
423 lazyReattachIfAttached();
425 m_inputType = newType.release();
426 if (hasAuthorShadowRoot())
427 m_inputTypeView = InputTypeView::create(*this);
429 m_inputTypeView = m_inputType;
430 m_inputTypeView->createShadowSubtree();
432 bool hasTouchEventHandler = m_inputTypeView->hasTouchEventHandler();
433 if (hasTouchEventHandler != m_hasTouchEventHandler) {
434 if (hasTouchEventHandler)
435 document().didAddTouchEventHandler(this);
437 document().didRemoveTouchEventHandler(this);
438 m_hasTouchEventHandler = hasTouchEventHandler;
441 setNeedsWillValidateCheck();
443 bool willStoreValue = m_inputType->storesValueSeparateFromAttribute();
445 if (didStoreValue && !willStoreValue && hasDirtyValue()) {
446 setAttribute(valueAttr, AtomicString(m_valueIfDirty));
447 m_valueIfDirty = String();
449 if (!didStoreValue && willStoreValue) {
450 AtomicString valueString = fastGetAttribute(valueAttr);
451 m_valueIfDirty = sanitizeValue(valueString);
453 updateValueIfNeeded();
455 m_needsToUpdateViewValue = true;
456 m_inputTypeView->updateView();
458 if (didRespectHeightAndWidth != m_inputType->shouldRespectHeightAndWidthAttributes()) {
459 ASSERT(elementData());
460 if (const Attribute* height = getAttributeItem(heightAttr))
461 attributeChanged(heightAttr, height->value());
462 if (const Attribute* width = getAttributeItem(widthAttr))
463 attributeChanged(widthAttr, width->value());
464 if (const Attribute* align = getAttributeItem(alignAttr))
465 attributeChanged(alignAttr, align->value());
468 if (document().focusedElement() == this)
469 document().updateFocusAppearanceSoon(true /* restore selection */);
471 setChangedSinceLastFormControlChangeEvent(false);
473 addToRadioButtonGroup();
475 setNeedsValidityCheck();
476 notifyFormStateChanged();
479 void HTMLInputElement::subtreeHasChanged()
481 m_inputTypeView->subtreeHasChanged();
482 // When typing in an input field, childrenChanged is not called, so we need to force the directionality check.
483 calculateAndAdjustDirectionality();
486 const AtomicString& HTMLInputElement::formControlType() const
488 return m_inputType->formControlType();
491 bool HTMLInputElement::shouldSaveAndRestoreFormControlState() const
493 if (!m_inputType->shouldSaveAndRestoreFormControlState())
495 return HTMLTextFormControlElement::shouldSaveAndRestoreFormControlState();
498 FormControlState HTMLInputElement::saveFormControlState() const
500 return m_inputType->saveFormControlState();
503 void HTMLInputElement::restoreFormControlState(const FormControlState& state)
505 m_inputType->restoreFormControlState(state);
506 m_stateRestored = true;
509 bool HTMLInputElement::canStartSelection() const
513 return HTMLTextFormControlElement::canStartSelection();
516 int HTMLInputElement::selectionStartForBinding(ExceptionState& exceptionState) const
518 if (!m_inputType->supportsSelectionAPI()) {
519 exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
522 return HTMLTextFormControlElement::selectionStart();
525 int HTMLInputElement::selectionEndForBinding(ExceptionState& exceptionState) const
527 if (!m_inputType->supportsSelectionAPI()) {
528 exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
531 return HTMLTextFormControlElement::selectionEnd();
534 String HTMLInputElement::selectionDirectionForBinding(ExceptionState& exceptionState) const
536 if (!m_inputType->supportsSelectionAPI()) {
537 exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
540 return HTMLTextFormControlElement::selectionDirection();
543 void HTMLInputElement::setSelectionStartForBinding(int start, ExceptionState& exceptionState)
545 if (!m_inputType->supportsSelectionAPI()) {
546 exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
549 HTMLTextFormControlElement::setSelectionStart(start);
552 void HTMLInputElement::setSelectionEndForBinding(int end, ExceptionState& exceptionState)
554 if (!m_inputType->supportsSelectionAPI()) {
555 exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
558 HTMLTextFormControlElement::setSelectionEnd(end);
561 void HTMLInputElement::setSelectionDirectionForBinding(const String& direction, ExceptionState& exceptionState)
563 if (!m_inputType->supportsSelectionAPI()) {
564 exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
567 HTMLTextFormControlElement::setSelectionDirection(direction);
570 void HTMLInputElement::setSelectionRangeForBinding(int start, int end, ExceptionState& exceptionState)
572 if (!m_inputType->supportsSelectionAPI()) {
573 exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
576 HTMLTextFormControlElement::setSelectionRange(start, end);
579 void HTMLInputElement::setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionState& exceptionState)
581 if (!m_inputType->supportsSelectionAPI()) {
582 exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
585 HTMLTextFormControlElement::setSelectionRange(start, end, direction);
588 void HTMLInputElement::accessKeyAction(bool sendMouseEvents)
590 m_inputType->accessKeyAction(sendMouseEvents);
593 bool HTMLInputElement::isPresentationAttribute(const QualifiedName& name) const
595 if (name == vspaceAttr || name == hspaceAttr || name == alignAttr || name == widthAttr || name == heightAttr || (name == borderAttr && isImageButton()))
597 return HTMLTextFormControlElement::isPresentationAttribute(name);
600 void HTMLInputElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
602 if (name == vspaceAttr) {
603 addHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
604 addHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
605 } else if (name == hspaceAttr) {
606 addHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
607 addHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
608 } else if (name == alignAttr) {
609 if (m_inputType->shouldRespectAlignAttribute())
610 applyAlignmentAttributeToStyle(value, style);
611 } else if (name == widthAttr) {
612 if (m_inputType->shouldRespectHeightAndWidthAttributes())
613 addHTMLLengthToStyle(style, CSSPropertyWidth, value);
614 } else if (name == heightAttr) {
615 if (m_inputType->shouldRespectHeightAndWidthAttributes())
616 addHTMLLengthToStyle(style, CSSPropertyHeight, value);
617 } else if (name == borderAttr && isImageButton())
618 applyBorderAttributeToStyle(value, style);
620 HTMLTextFormControlElement::collectStyleForPresentationAttribute(name, value, style);
623 void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
625 if (name == nameAttr) {
626 removeFromRadioButtonGroup();
628 addToRadioButtonGroup();
629 HTMLTextFormControlElement::parseAttribute(name, value);
630 } else if (name == autocompleteAttr) {
631 if (equalIgnoringCase(value, "off"))
632 m_autocomplete = Off;
635 m_autocomplete = Uninitialized;
639 } else if (name == typeAttr)
641 else if (name == valueAttr) {
642 // We only need to setChanged if the form is looking at the default value right now.
643 if (!hasDirtyValue()) {
644 updatePlaceholderVisibility(false);
645 setNeedsStyleRecalc(SubtreeStyleChange);
647 m_needsToUpdateViewValue = true;
648 setNeedsValidityCheck();
649 m_valueAttributeWasUpdatedAfterParsing = !m_parsingInProgress;
650 m_inputTypeView->valueAttributeChanged();
651 } else if (name == checkedAttr) {
652 // Another radio button in the same group might be checked by state
653 // restore. We shouldn't call setChecked() even if this has the checked
654 // attribute. So, delay the setChecked() call until
655 // finishParsingChildren() is called if parsing is in progress.
656 if (!m_parsingInProgress && m_reflectsCheckedAttribute) {
657 setChecked(!value.isNull());
658 m_reflectsCheckedAttribute = true;
660 } else if (name == maxlengthAttr)
661 parseMaxLengthAttribute(value);
662 else if (name == sizeAttr) {
663 int oldSize = m_size;
664 int valueAsInteger = value.toInt();
665 m_size = valueAsInteger > 0 ? valueAsInteger : defaultSize;
666 if (m_size != oldSize && renderer())
667 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
668 } else if (name == altAttr)
669 m_inputTypeView->altAttributeChanged();
670 else if (name == srcAttr)
671 m_inputTypeView->srcAttributeChanged();
672 else if (name == usemapAttr || name == accesskeyAttr) {
673 // FIXME: ignore for the moment
674 } else if (name == onsearchAttr) {
675 // Search field and slider attributes all just cause updateFromElement to be called through style recalcing.
676 setAttributeEventListener(EventTypeNames::search, createAttributeEventListener(this, name, value));
677 } else if (name == resultsAttr) {
678 int oldResults = m_maxResults;
679 m_maxResults = !value.isNull() ? std::min(value.toInt(), maxSavedResults) : -1;
680 // FIXME: Detaching just for maxResults change is not ideal. We should figure out the right
681 // time to relayout for this change.
682 if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0))
683 lazyReattachIfAttached();
684 setNeedsStyleRecalc(SubtreeStyleChange);
685 UseCounter::count(document(), UseCounter::ResultsAttribute);
686 } else if (name == incrementalAttr) {
687 setNeedsStyleRecalc(SubtreeStyleChange);
688 UseCounter::count(document(), UseCounter::IncrementalAttribute);
689 } else if (name == minAttr) {
690 m_inputTypeView->minOrMaxAttributeChanged();
691 m_inputType->sanitizeValueInResponseToMinOrMaxAttributeChange();
692 setNeedsValidityCheck();
693 UseCounter::count(document(), UseCounter::MinAttribute);
694 } else if (name == maxAttr) {
695 m_inputTypeView->minOrMaxAttributeChanged();
696 setNeedsValidityCheck();
697 UseCounter::count(document(), UseCounter::MaxAttribute);
698 } else if (name == multipleAttr) {
699 m_inputTypeView->multipleAttributeChanged();
700 setNeedsValidityCheck();
701 } else if (name == stepAttr) {
702 m_inputTypeView->stepAttributeChanged();
703 setNeedsValidityCheck();
704 UseCounter::count(document(), UseCounter::StepAttribute);
705 } else if (name == patternAttr) {
706 setNeedsValidityCheck();
707 UseCounter::count(document(), UseCounter::PatternAttribute);
708 } else if (name == precisionAttr) {
709 setNeedsValidityCheck();
710 UseCounter::count(document(), UseCounter::PrecisionAttribute);
711 } else if (name == disabledAttr) {
712 HTMLTextFormControlElement::parseAttribute(name, value);
713 m_inputTypeView->disabledAttributeChanged();
714 } else if (name == readonlyAttr) {
715 HTMLTextFormControlElement::parseAttribute(name, value);
716 m_inputTypeView->readonlyAttributeChanged();
717 } else if (name == listAttr) {
718 m_hasNonEmptyList = !value.isEmpty();
719 if (m_hasNonEmptyList) {
720 resetListAttributeTargetObserver();
721 listAttributeTargetChanged();
723 UseCounter::count(document(), UseCounter::ListAttribute);
724 } else if (name == webkitdirectoryAttr) {
725 HTMLTextFormControlElement::parseAttribute(name, value);
726 UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute);
729 HTMLTextFormControlElement::parseAttribute(name, value);
730 m_inputTypeView->attributeChanged();
733 void HTMLInputElement::finishParsingChildren()
735 m_parsingInProgress = false;
736 HTMLTextFormControlElement::finishParsingChildren();
737 if (!m_stateRestored) {
738 bool checked = hasAttribute(checkedAttr);
741 m_reflectsCheckedAttribute = true;
745 bool HTMLInputElement::rendererIsNeeded(const RenderStyle& style)
747 return m_inputType->rendererIsNeeded() && HTMLTextFormControlElement::rendererIsNeeded(style);
750 RenderObject* HTMLInputElement::createRenderer(RenderStyle* style)
752 return m_inputTypeView->createRenderer(style);
755 void HTMLInputElement::attach(const AttachContext& context)
757 HTMLTextFormControlElement::attach(context);
759 m_inputTypeView->startResourceLoading();
760 m_inputType->countUsage();
762 if (document().focusedElement() == this)
763 document().updateFocusAppearanceSoon(true /* restore selection */);
766 void HTMLInputElement::detach(const AttachContext& context)
768 HTMLTextFormControlElement::detach(context);
769 m_needsToUpdateViewValue = true;
770 m_inputTypeView->closePopupView();
773 String HTMLInputElement::altText() const
775 // http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen
776 // also heavily discussed by Hixie on bugzilla
777 // note this is intentionally different to HTMLImageElement::altText()
778 String alt = fastGetAttribute(altAttr);
779 // fall back to title attribute
781 alt = fastGetAttribute(titleAttr);
783 alt = fastGetAttribute(valueAttr);
785 alt = locale().queryString(blink::WebLocalizedString::InputElementAltText);
789 bool HTMLInputElement::canBeSuccessfulSubmitButton() const
791 return m_inputType->canBeSuccessfulSubmitButton();
794 bool HTMLInputElement::isActivatedSubmit() const
796 return m_isActivatedSubmit;
799 void HTMLInputElement::setActivatedSubmit(bool flag)
801 m_isActivatedSubmit = flag;
804 bool HTMLInputElement::appendFormData(FormDataList& encoding, bool multipart)
806 return m_inputType->isFormDataAppendable() && m_inputType->appendFormData(encoding, multipart);
809 String HTMLInputElement::resultForDialogSubmit()
811 return m_inputType->resultForDialogSubmit();
814 void HTMLInputElement::resetImpl()
816 if (m_inputType->storesValueSeparateFromAttribute()) {
818 setNeedsValidityCheck();
821 setChecked(hasAttribute(checkedAttr));
822 m_reflectsCheckedAttribute = true;
825 bool HTMLInputElement::isTextField() const
827 return m_inputType->isTextField();
830 bool HTMLInputElement::isTextType() const
832 return m_inputType->isTextType();
835 void HTMLInputElement::setChecked(bool nowChecked, TextFieldEventBehavior eventBehavior)
837 if (checked() == nowChecked)
840 RefPtrWillBeRawPtr<HTMLInputElement> protector(this);
841 m_reflectsCheckedAttribute = false;
842 m_isChecked = nowChecked;
843 setNeedsStyleRecalc(SubtreeStyleChange);
845 if (RadioButtonGroupScope* scope = radioButtonGroupScope())
846 scope->updateCheckedState(this);
847 if (renderer() && renderer()->style()->hasAppearance())
848 RenderTheme::theme().stateChanged(renderer(), CheckedState);
850 setNeedsValidityCheck();
852 // Ideally we'd do this from the render tree (matching
853 // RenderTextView), but it's not possible to do it at the moment
854 // because of the way the code is structured.
856 if (AXObjectCache* cache = renderer()->document().existingAXObjectCache())
857 cache->checkedStateChanged(this);
860 // Only send a change event for items in the document (avoid firing during
861 // parsing) and don't send a change event for a radio button that's getting
862 // unchecked to match other browsers. DOM is not a useful standard for this
863 // because it says only to fire change events at "lose focus" time, which is
864 // definitely wrong in practice for these types of elements.
865 if (eventBehavior != DispatchNoEvent && inDocument() && m_inputType->shouldSendChangeEventAfterCheckedChanged()) {
866 setTextAsOfLastFormControlChangeEvent(String());
867 if (eventBehavior == DispatchInputAndChangeEvent)
868 dispatchFormControlInputEvent();
869 dispatchFormControlChangeEvent();
872 didAffectSelector(AffectedSelectorChecked);
875 void HTMLInputElement::setIndeterminate(bool newValue)
877 if (indeterminate() == newValue)
880 m_isIndeterminate = newValue;
882 didAffectSelector(AffectedSelectorIndeterminate);
884 if (renderer() && renderer()->style()->hasAppearance())
885 RenderTheme::theme().stateChanged(renderer(), CheckedState);
888 int HTMLInputElement::size() const
893 bool HTMLInputElement::sizeShouldIncludeDecoration(int& preferredSize) const
895 return m_inputTypeView->sizeShouldIncludeDecoration(defaultSize, preferredSize);
898 void HTMLInputElement::copyNonAttributePropertiesFromElement(const Element& source)
900 const HTMLInputElement& sourceElement = static_cast<const HTMLInputElement&>(source);
902 m_valueIfDirty = sourceElement.m_valueIfDirty;
903 setChecked(sourceElement.m_isChecked);
904 m_reflectsCheckedAttribute = sourceElement.m_reflectsCheckedAttribute;
905 m_isIndeterminate = sourceElement.m_isIndeterminate;
906 m_inputType->copyNonAttributeProperties(sourceElement);
908 HTMLTextFormControlElement::copyNonAttributePropertiesFromElement(source);
910 m_needsToUpdateViewValue = true;
911 m_inputTypeView->updateView();
914 String HTMLInputElement::value() const
917 if (m_inputType->getTypeSpecificValue(value))
920 value = m_valueIfDirty;
924 AtomicString valueString = fastGetAttribute(valueAttr);
925 value = sanitizeValue(valueString);
929 return m_inputType->fallbackValue();
932 String HTMLInputElement::valueWithDefault() const
934 String value = this->value();
938 return m_inputType->defaultValue();
941 void HTMLInputElement::setValueForUser(const String& value)
943 // Call setValue and make it send a change event.
944 setValue(value, DispatchChangeEvent);
947 const String& HTMLInputElement::suggestedValue() const
949 return m_suggestedValue;
952 void HTMLInputElement::setSuggestedValue(const String& value)
954 if (!m_inputType->canSetSuggestedValue())
956 m_needsToUpdateViewValue = true;
957 m_suggestedValue = sanitizeValue(value);
958 setNeedsStyleRecalc(SubtreeStyleChange);
959 m_inputTypeView->updateView();
962 void HTMLInputElement::setEditingValue(const String& value)
964 if (!renderer() || !isTextField())
966 setInnerTextValue(value);
969 unsigned max = value.length();
971 setSelectionRange(max, max);
973 cacheSelectionInResponseToSetValue(max);
975 dispatchInputEvent();
978 void HTMLInputElement::setInnerTextValue(const String& value)
980 HTMLTextFormControlElement::setInnerTextValue(value);
981 m_needsToUpdateViewValue = false;
984 void HTMLInputElement::setValue(const String& value, ExceptionState& exceptionState, TextFieldEventBehavior eventBehavior)
986 if (isFileUpload() && !value.isEmpty()) {
987 exceptionState.throwDOMException(InvalidStateError, "This input element accepts a filename, which may only be programmatically set to the empty string.");
990 setValue(value, eventBehavior);
993 void HTMLInputElement::setValue(const String& value, TextFieldEventBehavior eventBehavior)
995 if (!m_inputType->canSetValue(value))
998 RefPtrWillBeRawPtr<HTMLInputElement> protector(this);
999 EventQueueScope scope;
1000 String sanitizedValue = sanitizeValue(value);
1001 bool valueChanged = sanitizedValue != this->value();
1003 setLastChangeWasNotUserEdit();
1004 m_needsToUpdateViewValue = true;
1005 m_suggestedValue = String(); // Prevent TextFieldInputType::setValue from using the suggested value.
1007 m_inputType->setValue(sanitizedValue, valueChanged, eventBehavior);
1009 if (valueChanged && eventBehavior == DispatchNoEvent)
1010 setTextAsOfLastFormControlChangeEvent(sanitizedValue);
1015 notifyFormStateChanged();
1018 void HTMLInputElement::setValueInternal(const String& sanitizedValue, TextFieldEventBehavior eventBehavior)
1020 m_valueIfDirty = sanitizedValue;
1021 setNeedsValidityCheck();
1022 if (document().focusedElement() == this)
1023 document().frameHost()->chrome().client().didUpdateTextOfFocusedElementByNonUserInput();
1026 void HTMLInputElement::updateView()
1028 m_inputTypeView->updateView();
1031 double HTMLInputElement::valueAsDate(bool& isNull) const
1033 double date = m_inputType->valueAsDate();
1034 isNull = !std::isfinite(date);
1038 void HTMLInputElement::setValueAsDate(double value, ExceptionState& exceptionState)
1040 m_inputType->setValueAsDate(value, exceptionState);
1043 double HTMLInputElement::valueAsNumber() const
1045 return m_inputType->valueAsDouble();
1048 void HTMLInputElement::setValueAsNumber(double newValue, ExceptionState& exceptionState, TextFieldEventBehavior eventBehavior)
1050 // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#dom-input-valueasnumber
1051 // On setting, if the new value is infinite, then throw a TypeError exception.
1052 if (std::isinf(newValue)) {
1053 exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(newValue));
1056 m_inputType->setValueAsDouble(newValue, eventBehavior, exceptionState);
1059 void HTMLInputElement::setValueFromRenderer(const String& value)
1061 // File upload controls will never use this.
1062 ASSERT(!isFileUpload());
1064 m_suggestedValue = String();
1066 // Renderer and our event handler are responsible for sanitizing values.
1067 ASSERT(value == sanitizeValue(value) || sanitizeValue(value).isEmpty());
1069 m_valueIfDirty = value;
1070 m_needsToUpdateViewValue = false;
1072 // Input event is fired by the Node::defaultEventHandler for editable controls.
1074 dispatchInputEvent();
1075 notifyFormStateChanged();
1077 setNeedsValidityCheck();
1079 // Clear autofill flag (and yellow background) on user edit.
1080 setAutofilled(false);
1083 void* HTMLInputElement::preDispatchEventHandler(Event* event)
1085 if (event->type() == EventTypeNames::textInput && m_inputTypeView->shouldSubmitImplicitly(event)) {
1086 event->stopPropagation();
1089 if (event->type() != EventTypeNames::click)
1091 if (!event->isMouseEvent() || toMouseEvent(event)->button() != LeftButton)
1093 // FIXME: Check whether there are any cases where this actually ends up leaking.
1094 return m_inputTypeView->willDispatchClick().leakPtr();
1097 void HTMLInputElement::postDispatchEventHandler(Event* event, void* dataFromPreDispatch)
1099 OwnPtr<ClickHandlingState> state = adoptPtr(static_cast<ClickHandlingState*>(dataFromPreDispatch));
1102 m_inputTypeView->didDispatchClick(event, *state);
1105 void HTMLInputElement::defaultEventHandler(Event* evt)
1107 if (evt->isMouseEvent() && evt->type() == EventTypeNames::click && toMouseEvent(evt)->button() == LeftButton) {
1108 m_inputTypeView->handleClickEvent(toMouseEvent(evt));
1109 if (evt->defaultHandled())
1113 if (evt->isTouchEvent() && m_inputTypeView->hasTouchEventHandler()) {
1114 m_inputTypeView->handleTouchEvent(toTouchEvent(evt));
1115 if (evt->defaultHandled())
1119 if (evt->isKeyboardEvent() && evt->type() == EventTypeNames::keydown) {
1120 m_inputTypeView->handleKeydownEvent(toKeyboardEvent(evt));
1121 if (evt->defaultHandled())
1125 // Call the base event handler before any of our own event handling for almost all events in text fields.
1126 // Makes editing keyboard handling take precedence over the keydown and keypress handling in this function.
1127 bool callBaseClassEarly = isTextField() && (evt->type() == EventTypeNames::keydown || evt->type() == EventTypeNames::keypress);
1128 if (callBaseClassEarly) {
1129 HTMLTextFormControlElement::defaultEventHandler(evt);
1130 if (evt->defaultHandled())
1134 // DOMActivate events cause the input to be "activated" - in the case of image and submit inputs, this means
1135 // actually submitting the form. For reset inputs, the form is reset. These events are sent when the user clicks
1136 // on the element, or presses enter while it is the active element. JavaScript code wishing to activate the element
1137 // must dispatch a DOMActivate event - a click event will not do the job.
1138 if (evt->type() == EventTypeNames::DOMActivate) {
1139 m_inputType->handleDOMActivateEvent(evt);
1140 if (evt->defaultHandled())
1144 // Use key press event here since sending simulated mouse events
1145 // on key down blocks the proper sending of the key press event.
1146 if (evt->isKeyboardEvent() && evt->type() == EventTypeNames::keypress) {
1147 m_inputTypeView->handleKeypressEvent(toKeyboardEvent(evt));
1148 if (evt->defaultHandled())
1152 if (evt->isKeyboardEvent() && evt->type() == EventTypeNames::keyup) {
1153 m_inputTypeView->handleKeyupEvent(toKeyboardEvent(evt));
1154 if (evt->defaultHandled())
1158 if (m_inputTypeView->shouldSubmitImplicitly(evt)) {
1159 if (isSearchField())
1161 // Form submission finishes editing, just as loss of focus does.
1162 // If there was a change, send the event now.
1163 if (wasChangedSinceLastFormControlChangeEvent())
1164 dispatchFormControlChangeEvent();
1166 RefPtrWillBeRawPtr<HTMLFormElement> formForSubmission = m_inputTypeView->formForSubmission();
1167 // Form may never have been present, or may have been destroyed by code responding to the change event.
1168 if (formForSubmission)
1169 formForSubmission->submitImplicitly(evt, canTriggerImplicitSubmission());
1171 evt->setDefaultHandled();
1175 if (evt->isBeforeTextInsertedEvent())
1176 m_inputTypeView->handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(evt));
1178 if (evt->isMouseEvent() && evt->type() == EventTypeNames::mousedown) {
1179 m_inputTypeView->handleMouseDownEvent(toMouseEvent(evt));
1180 if (evt->defaultHandled())
1184 m_inputTypeView->forwardEvent(evt);
1186 if (!callBaseClassEarly && !evt->defaultHandled())
1187 HTMLTextFormControlElement::defaultEventHandler(evt);
1190 bool HTMLInputElement::willRespondToMouseClickEvents()
1192 // FIXME: Consider implementing willRespondToMouseClickEvents() in InputType if more accurate results are necessary.
1193 if (!isDisabledFormControl())
1196 return HTMLTextFormControlElement::willRespondToMouseClickEvents();
1199 bool HTMLInputElement::isURLAttribute(const Attribute& attribute) const
1201 return attribute.name() == srcAttr || attribute.name() == formactionAttr || HTMLTextFormControlElement::isURLAttribute(attribute);
1204 bool HTMLInputElement::hasLegalLinkAttribute(const QualifiedName& name) const
1206 return m_inputType->hasLegalLinkAttribute(name) || HTMLTextFormControlElement::hasLegalLinkAttribute(name);
1209 const QualifiedName& HTMLInputElement::subResourceAttributeName() const
1211 return m_inputType->subResourceAttributeName();
1214 const AtomicString& HTMLInputElement::defaultValue() const
1216 return fastGetAttribute(valueAttr);
1219 void HTMLInputElement::setDefaultValue(const AtomicString& value)
1221 setAttribute(valueAttr, value);
1224 static inline bool isRFC2616TokenCharacter(UChar ch)
1226 return isASCII(ch) && ch > ' ' && ch != '"' && ch != '(' && ch != ')' && ch != ',' && ch != '/' && (ch < ':' || ch > '@') && (ch < '[' || ch > ']') && ch != '{' && ch != '}' && ch != 0x7f;
1229 static bool isValidMIMEType(const String& type)
1231 size_t slashPosition = type.find('/');
1232 if (slashPosition == kNotFound || !slashPosition || slashPosition == type.length() - 1)
1234 for (size_t i = 0; i < type.length(); ++i) {
1235 if (!isRFC2616TokenCharacter(type[i]) && i != slashPosition)
1241 static bool isValidFileExtension(const String& type)
1243 if (type.length() < 2)
1245 return type[0] == '.';
1248 static Vector<String> parseAcceptAttribute(const String& acceptString, bool (*predicate)(const String&))
1250 Vector<String> types;
1251 if (acceptString.isEmpty())
1254 Vector<String> splitTypes;
1255 acceptString.split(',', false, splitTypes);
1256 for (size_t i = 0; i < splitTypes.size(); ++i) {
1257 String trimmedType = stripLeadingAndTrailingHTMLSpaces(splitTypes[i]);
1258 if (trimmedType.isEmpty())
1260 if (!predicate(trimmedType))
1262 types.append(trimmedType.lower());
1268 Vector<String> HTMLInputElement::acceptMIMETypes()
1270 return parseAcceptAttribute(fastGetAttribute(acceptAttr), isValidMIMEType);
1273 Vector<String> HTMLInputElement::acceptFileExtensions()
1275 return parseAcceptAttribute(fastGetAttribute(acceptAttr), isValidFileExtension);
1278 const AtomicString& HTMLInputElement::alt() const
1280 return fastGetAttribute(altAttr);
1283 int HTMLInputElement::maxLength() const
1288 void HTMLInputElement::setMaxLength(int maxLength, ExceptionState& exceptionState)
1291 exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(maxLength) + ") is negative.");
1293 setIntegralAttribute(maxlengthAttr, maxLength);
1296 bool HTMLInputElement::multiple() const
1298 return fastHasAttribute(multipleAttr);
1301 void HTMLInputElement::setSize(unsigned size)
1303 setUnsignedIntegralAttribute(sizeAttr, size);
1306 void HTMLInputElement::setSize(unsigned size, ExceptionState& exceptionState)
1309 exceptionState.throwDOMException(IndexSizeError, "The value provided is 0, which is an invalid size.");
1314 KURL HTMLInputElement::src() const
1316 return document().completeURL(fastGetAttribute(srcAttr));
1319 FileList* HTMLInputElement::files() const
1321 return m_inputType->files();
1324 void HTMLInputElement::setFiles(PassRefPtrWillBeRawPtr<FileList> files)
1326 m_inputType->setFiles(files);
1329 bool HTMLInputElement::receiveDroppedFiles(const DragData* dragData)
1331 return m_inputType->receiveDroppedFiles(dragData);
1334 String HTMLInputElement::droppedFileSystemId()
1336 return m_inputType->droppedFileSystemId();
1339 bool HTMLInputElement::canReceiveDroppedFiles() const
1341 return m_canReceiveDroppedFiles;
1344 void HTMLInputElement::setCanReceiveDroppedFiles(bool canReceiveDroppedFiles)
1346 if (m_canReceiveDroppedFiles == canReceiveDroppedFiles)
1348 m_canReceiveDroppedFiles = canReceiveDroppedFiles;
1350 renderer()->updateFromElement();
1353 String HTMLInputElement::sanitizeValue(const String& proposedValue) const
1355 if (proposedValue.isNull())
1356 return proposedValue;
1357 return m_inputType->sanitizeValue(proposedValue);
1360 String HTMLInputElement::localizeValue(const String& proposedValue) const
1362 if (proposedValue.isNull())
1363 return proposedValue;
1364 return m_inputType->localizeValue(proposedValue);
1367 bool HTMLInputElement::isInRange() const
1369 return m_inputType->isInRange(value());
1372 bool HTMLInputElement::isOutOfRange() const
1374 return m_inputType->isOutOfRange(value());
1377 bool HTMLInputElement::isRequiredFormControl() const
1379 return m_inputType->supportsRequired() && isRequired();
1382 bool HTMLInputElement::matchesReadOnlyPseudoClass() const
1384 return m_inputType->supportsReadOnly() && isReadOnly();
1387 bool HTMLInputElement::matchesReadWritePseudoClass() const
1389 return m_inputType->supportsReadOnly() && !isReadOnly();
1392 void HTMLInputElement::onSearch()
1394 ASSERT(isSearchField());
1396 static_cast<SearchInputType*>(m_inputType.get())->stopSearchEventTimer();
1397 dispatchEvent(Event::createBubble(EventTypeNames::search));
1400 void HTMLInputElement::updateClearButtonVisibility()
1402 m_inputTypeView->updateClearButtonVisibility();
1405 void HTMLInputElement::willChangeForm()
1407 removeFromRadioButtonGroup();
1408 HTMLTextFormControlElement::willChangeForm();
1411 void HTMLInputElement::didChangeForm()
1413 HTMLTextFormControlElement::didChangeForm();
1414 addToRadioButtonGroup();
1417 Node::InsertionNotificationRequest HTMLInputElement::insertedInto(ContainerNode* insertionPoint)
1419 HTMLTextFormControlElement::insertedInto(insertionPoint);
1420 if (insertionPoint->inDocument() && !form())
1421 addToRadioButtonGroup();
1422 resetListAttributeTargetObserver();
1423 return InsertionDone;
1426 void HTMLInputElement::removedFrom(ContainerNode* insertionPoint)
1428 if (insertionPoint->inDocument() && !form())
1429 removeFromRadioButtonGroup();
1430 HTMLTextFormControlElement::removedFrom(insertionPoint);
1431 ASSERT(!inDocument());
1432 resetListAttributeTargetObserver();
1435 void HTMLInputElement::didMoveToNewDocument(Document& oldDocument)
1437 if (hasImageLoader())
1438 imageLoader()->elementDidMoveToNewDocument();
1440 if (isRadioButton())
1441 oldDocument.formController().radioButtonGroupScope().removeButton(this);
1442 if (m_hasTouchEventHandler)
1443 oldDocument.didRemoveTouchEventHandler(this);
1445 if (m_hasTouchEventHandler)
1446 document().didAddTouchEventHandler(this);
1448 HTMLTextFormControlElement::didMoveToNewDocument(oldDocument);
1451 void HTMLInputElement::removeAllEventListeners()
1453 HTMLTextFormControlElement::removeAllEventListeners();
1454 m_hasTouchEventHandler = false;
1457 bool HTMLInputElement::recalcWillValidate() const
1459 return m_inputType->supportsValidation() && HTMLTextFormControlElement::recalcWillValidate();
1462 void HTMLInputElement::requiredAttributeChanged()
1464 HTMLTextFormControlElement::requiredAttributeChanged();
1465 if (RadioButtonGroupScope* scope = radioButtonGroupScope())
1466 scope->requiredAttributeChanged(this);
1467 m_inputTypeView->requiredAttributeChanged();
1470 void HTMLInputElement::selectColorInColorChooser(const Color& color)
1472 if (!m_inputType->isColorControl())
1474 static_cast<ColorInputType*>(m_inputType.get())->didChooseColor(color);
1477 HTMLElement* HTMLInputElement::list() const
1482 HTMLDataListElement* HTMLInputElement::dataList() const
1484 if (!m_hasNonEmptyList)
1487 if (!m_inputType->shouldRespectListAttribute())
1490 Element* element = treeScope().getElementById(fastGetAttribute(listAttr));
1493 if (!isHTMLDataListElement(*element))
1496 return toHTMLDataListElement(element);
1499 bool HTMLInputElement::hasValidDataListOptions() const
1501 HTMLDataListElement* dataList = this->dataList();
1504 RefPtr<HTMLCollection> options = dataList->options();
1505 for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) {
1506 if (isValidValue(option->value()))
1512 void HTMLInputElement::setListAttributeTargetObserver(PassOwnPtrWillBeRawPtr<ListAttributeTargetObserver> newObserver)
1514 if (m_listAttributeTargetObserver)
1515 m_listAttributeTargetObserver->unregister();
1516 m_listAttributeTargetObserver = newObserver;
1519 void HTMLInputElement::resetListAttributeTargetObserver()
1522 setListAttributeTargetObserver(ListAttributeTargetObserver::create(fastGetAttribute(listAttr), this));
1524 setListAttributeTargetObserver(nullptr);
1527 void HTMLInputElement::listAttributeTargetChanged()
1529 m_inputTypeView->listAttributeTargetChanged();
1532 bool HTMLInputElement::isSteppable() const
1534 return m_inputType->isSteppable();
1537 bool HTMLInputElement::isTextButton() const
1539 return m_inputType->isTextButton();
1542 bool HTMLInputElement::isRadioButton() const
1544 return m_inputType->isRadioButton();
1547 bool HTMLInputElement::isSearchField() const
1549 return m_inputType->isSearchField();
1552 bool HTMLInputElement::isInputTypeHidden() const
1554 return m_inputType->isHiddenType();
1557 bool HTMLInputElement::isPasswordField() const
1559 return m_inputType->isPasswordField();
1562 bool HTMLInputElement::isCheckbox() const
1564 return m_inputType->isCheckbox();
1567 bool HTMLInputElement::isRangeControl() const
1569 return m_inputType->isRangeControl();
1572 bool HTMLInputElement::isText() const
1574 return m_inputType->isTextType();
1577 bool HTMLInputElement::isEmailField() const
1579 return m_inputType->isEmailField();
1582 bool HTMLInputElement::isFileUpload() const
1584 return m_inputType->isFileUpload();
1587 bool HTMLInputElement::isImageButton() const
1589 return m_inputType->isImageButton();
1592 bool HTMLInputElement::isNumberField() const
1594 return m_inputType->isNumberField();
1597 bool HTMLInputElement::isTelephoneField() const
1599 return m_inputType->isTelephoneField();
1602 bool HTMLInputElement::isURLField() const
1604 return m_inputType->isURLField();
1607 bool HTMLInputElement::isDateField() const
1609 return m_inputType->isDateField();
1612 bool HTMLInputElement::isDateTimeLocalField() const
1614 return m_inputType->isDateTimeLocalField();
1617 bool HTMLInputElement::isMonthField() const
1619 return m_inputType->isMonthField();
1622 bool HTMLInputElement::isTimeField() const
1624 return m_inputType->isTimeField();
1627 bool HTMLInputElement::isWeekField() const
1629 return m_inputType->isWeekField();
1632 bool HTMLInputElement::isEnumeratable() const
1634 return m_inputType->isEnumeratable();
1637 bool HTMLInputElement::supportLabels() const
1639 return m_inputType->isInteractiveContent();
1642 bool HTMLInputElement::shouldAppearChecked() const
1644 return checked() && m_inputType->isCheckable();
1647 bool HTMLInputElement::supportsPlaceholder() const
1649 return m_inputType->supportsPlaceholder();
1652 void HTMLInputElement::updatePlaceholderText()
1654 return m_inputTypeView->updatePlaceholderText();
1657 void HTMLInputElement::parseMaxLengthAttribute(const AtomicString& value)
1660 if (!parseHTMLInteger(value, maxLength))
1661 maxLength = maximumLength;
1662 if (maxLength < 0 || maxLength > maximumLength)
1663 maxLength = maximumLength;
1664 int oldMaxLength = m_maxLength;
1665 m_maxLength = maxLength;
1666 if (oldMaxLength != maxLength)
1667 updateValueIfNeeded();
1668 setNeedsStyleRecalc(SubtreeStyleChange);
1669 setNeedsValidityCheck();
1672 void HTMLInputElement::updateValueIfNeeded()
1674 String newValue = sanitizeValue(m_valueIfDirty);
1675 ASSERT(!m_valueIfDirty.isNull() || newValue.isNull());
1676 if (newValue != m_valueIfDirty)
1680 String HTMLInputElement::defaultToolTip() const
1682 return m_inputType->defaultToolTip();
1685 bool HTMLInputElement::shouldAppearIndeterminate() const
1687 return m_inputType->supportsIndeterminateAppearance() && indeterminate();
1690 #if ENABLE(MEDIA_CAPTURE)
1691 bool HTMLInputElement::capture() const
1693 if (!isFileUpload() || !fastHasAttribute(captureAttr))
1696 // As per crbug.com/240252, emit a deprecation warning when the "capture"
1697 // attribute is used as an enum. The spec has been updated and "capture" is
1698 // supposed to be used as a boolean.
1699 bool hasDeprecatedUsage = !fastGetAttribute(captureAttr).isEmpty();
1700 if (hasDeprecatedUsage)
1701 UseCounter::countDeprecation(document(), UseCounter::CaptureAttributeAsEnum);
1703 UseCounter::count(document(), UseCounter::CaptureAttributeAsBoolean);
1709 bool HTMLInputElement::isInRequiredRadioButtonGroup()
1711 ASSERT(isRadioButton());
1712 if (RadioButtonGroupScope* scope = radioButtonGroupScope())
1713 return scope->isInRequiredGroup(this);
1717 HTMLInputElement* HTMLInputElement::checkedRadioButtonForGroup() const
1719 if (RadioButtonGroupScope* scope = radioButtonGroupScope())
1720 return scope->checkedButtonForGroup(name());
1724 RadioButtonGroupScope* HTMLInputElement::radioButtonGroupScope() const
1726 if (!isRadioButton())
1728 if (HTMLFormElement* formElement = form())
1729 return &formElement->radioButtonGroupScope();
1731 return &document().formController().radioButtonGroupScope();
1735 inline void HTMLInputElement::addToRadioButtonGroup()
1737 if (RadioButtonGroupScope* scope = radioButtonGroupScope())
1738 scope->addButton(this);
1741 inline void HTMLInputElement::removeFromRadioButtonGroup()
1743 if (RadioButtonGroupScope* scope = radioButtonGroupScope())
1744 scope->removeButton(this);
1747 unsigned HTMLInputElement::height() const
1749 return m_inputType->height();
1752 unsigned HTMLInputElement::width() const
1754 return m_inputType->width();
1757 void HTMLInputElement::setHeight(unsigned height)
1759 setUnsignedIntegralAttribute(heightAttr, height);
1762 void HTMLInputElement::setWidth(unsigned width)
1764 setUnsignedIntegralAttribute(widthAttr, width);
1767 PassOwnPtrWillBeRawPtr<ListAttributeTargetObserver> ListAttributeTargetObserver::create(const AtomicString& id, HTMLInputElement* element)
1769 return adoptPtrWillBeNoop(new ListAttributeTargetObserver(id, element));
1772 ListAttributeTargetObserver::ListAttributeTargetObserver(const AtomicString& id, HTMLInputElement* element)
1773 : IdTargetObserver(element->treeScope().idTargetObserverRegistry(), id)
1774 , m_element(element)
1778 void ListAttributeTargetObserver::trace(Visitor* visitor)
1780 visitor->trace(m_element);
1781 IdTargetObserver::trace(visitor);
1784 void ListAttributeTargetObserver::idTargetChanged()
1786 m_element->listAttributeTargetChanged();
1789 void HTMLInputElement::setRangeText(const String& replacement, ExceptionState& exceptionState)
1791 if (!m_inputType->supportsSelectionAPI()) {
1792 exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
1796 HTMLTextFormControlElement::setRangeText(replacement, exceptionState);
1799 void HTMLInputElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& exceptionState)
1801 if (!m_inputType->supportsSelectionAPI()) {
1802 exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
1806 HTMLTextFormControlElement::setRangeText(replacement, start, end, selectionMode, exceptionState);
1809 bool HTMLInputElement::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
1811 if (!document().view())
1814 parameters.type = type();
1815 parameters.minimum = minimum();
1816 parameters.maximum = maximum();
1817 parameters.required = isRequired();
1818 if (!RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
1819 parameters.locale = defaultLanguage();
1821 AtomicString computedLocale = computeInheritedLanguage();
1822 parameters.locale = computedLocale.isEmpty() ? defaultLanguage() : computedLocale;
1825 StepRange stepRange = createStepRange(RejectAny);
1826 if (stepRange.hasStep()) {
1827 parameters.step = stepRange.step().toDouble();
1828 parameters.stepBase = stepRange.stepBase().toDouble();
1830 parameters.step = 1.0;
1831 parameters.stepBase = 0;
1834 parameters.anchorRectInRootView = document().view()->contentsToRootView(pixelSnappedBoundingBox());
1835 parameters.currentValue = value();
1836 parameters.doubleValue = m_inputType->valueAsDouble();
1837 parameters.isAnchorElementRTL = computedStyle()->direction() == RTL;
1838 if (HTMLDataListElement* dataList = this->dataList()) {
1839 RefPtr<HTMLCollection> options = dataList->options();
1840 for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) {
1841 if (!isValidValue(option->value()))
1843 DateTimeSuggestion suggestion;
1844 suggestion.value = m_inputType->parseToNumber(option->value(), Decimal::nan()).toDouble();
1845 if (std::isnan(suggestion.value))
1847 suggestion.localizedValue = localizeValue(option->value());
1848 suggestion.label = option->value() == option->label() ? String() : option->label();
1849 parameters.suggestions.append(suggestion);
1855 bool HTMLInputElement::supportsInputModeAttribute() const
1857 return m_inputType->supportsInputModeAttribute();
1860 void HTMLInputElement::setShouldRevealPassword(bool value)
1862 if (m_shouldRevealPassword == value)
1864 m_shouldRevealPassword = value;
1865 lazyReattachIfAttached();
1868 bool HTMLInputElement::isInteractiveContent() const
1870 return m_inputType->isInteractiveContent();
1873 bool HTMLInputElement::supportsAutofocus() const
1875 return m_inputType->isInteractiveContent();
1878 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
1879 PassRefPtr<RenderStyle> HTMLInputElement::customStyleForRenderer()
1881 return m_inputTypeView->customStyleForRenderer(originalStyleForRenderer());
1885 bool HTMLInputElement::shouldDispatchFormControlChangeEvent(String& oldValue, String& newValue)
1887 return m_inputType->shouldDispatchFormControlChangeEvent(oldValue, newValue);