Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / HTMLInputElement.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2001 Dirk Mueller (mueller@kde.org)
5  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 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.
11  *
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.
16  *
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.
21  *
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.
26  *
27  */
28
29 #include "config.h"
30 #include "core/html/HTMLInputElement.h"
31
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"
78
79 using namespace std;
80
81 namespace WebCore {
82
83 using namespace HTMLNames;
84
85 class ListAttributeTargetObserver : public IdTargetObserver {
86     WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
87 public:
88     static PassOwnPtrWillBeRawPtr<ListAttributeTargetObserver> create(const AtomicString& id, HTMLInputElement*);
89     virtual void trace(Visitor*) OVERRIDE;
90     virtual void idTargetChanged() OVERRIDE;
91
92 private:
93     ListAttributeTargetObserver(const AtomicString& id, HTMLInputElement*);
94
95     RawPtrWillBeMember<HTMLInputElement> m_element;
96 };
97
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;
105
106 HTMLInputElement::HTMLInputElement(Document& document, HTMLFormElement* form, bool createdByParser)
107     : HTMLTextFormControlElement(inputTag, document, form)
108     , m_size(defaultSize)
109     , m_maxLength(maximumLength)
110     , m_maxResults(-1)
111     , m_isChecked(false)
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)
126 {
127 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
128     setHasCustomStyleCallbacks();
129 #endif
130     ScriptWrappable::init(this);
131 }
132
133 PassRefPtrWillBeRawPtr<HTMLInputElement> HTMLInputElement::create(Document& document, HTMLFormElement* form, bool createdByParser)
134 {
135     RefPtrWillBeRawPtr<HTMLInputElement> inputElement = adoptRefWillBeRefCountedGarbageCollected(new HTMLInputElement(document, form, createdByParser));
136     inputElement->ensureUserAgentShadowRoot();
137     return inputElement.release();
138 }
139
140 void HTMLInputElement::trace(Visitor* visitor)
141 {
142     visitor->trace(m_inputType);
143     visitor->trace(m_inputTypeView);
144     visitor->trace(m_listAttributeTargetObserver);
145     HTMLTextFormControlElement::trace(visitor);
146 }
147
148 HTMLImageLoader* HTMLInputElement::imageLoader()
149 {
150     if (!m_imageLoader)
151         m_imageLoader = adoptPtr(new HTMLImageLoader(this));
152     return m_imageLoader.get();
153 }
154
155 void HTMLInputElement::didAddUserAgentShadowRoot(ShadowRoot&)
156 {
157     m_inputTypeView->createShadowSubtree();
158 }
159
160 void HTMLInputElement::willAddFirstAuthorShadowRoot()
161 {
162     m_inputTypeView->destroyShadowSubtree();
163     m_inputTypeView = InputTypeView::create(*this);
164     lazyReattachIfAttached();
165 }
166
167 HTMLInputElement::~HTMLInputElement()
168 {
169 #if !ENABLE(OILPAN)
170     // Need to remove form association while this is still an HTMLInputElement
171     // so that virtual functions are called correctly.
172     setForm(0);
173     // setForm(0) may register this to a document-level radio button group.
174     // We should unregister it to avoid accessing a deleted object.
175     if (isRadioButton())
176         document().formController().radioButtonGroupScope().removeButton(this);
177     if (m_hasTouchEventHandler)
178         document().didRemoveTouchEventHandler(this);
179 #endif
180 }
181
182 const AtomicString& HTMLInputElement::name() const
183 {
184     return m_name.isNull() ? emptyAtom : m_name;
185 }
186
187 Vector<FileChooserFileInfo> HTMLInputElement::filesFromFileInputFormControlState(const FormControlState& state)
188 {
189     return FileInputType::filesFromFormControlState(state);
190 }
191
192 HTMLElement* HTMLInputElement::passwordGeneratorButtonElement() const
193 {
194     return toHTMLElement(userAgentShadowRoot()->getElementById(ShadowElementNames::passwordGenerator()));
195 }
196
197 bool HTMLInputElement::shouldAutocomplete() const
198 {
199     if (m_autocomplete != Uninitialized)
200         return m_autocomplete == On;
201     return HTMLTextFormControlElement::shouldAutocomplete();
202 }
203
204 bool HTMLInputElement::isValidValue(const String& value) const
205 {
206     if (!m_inputType->canSetStringValue()) {
207         ASSERT_NOT_REACHED();
208         return false;
209     }
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);
217 }
218
219 bool HTMLInputElement::tooLong() const
220 {
221     return willValidate() && tooLong(value(), CheckDirtyFlag);
222 }
223
224 bool HTMLInputElement::typeMismatch() const
225 {
226     return willValidate() && m_inputType->typeMismatch();
227 }
228
229 bool HTMLInputElement::valueMissing() const
230 {
231     return willValidate() && m_inputType->valueMissing(value());
232 }
233
234 bool HTMLInputElement::hasBadInput() const
235 {
236     return willValidate() && m_inputType->hasBadInput();
237 }
238
239 bool HTMLInputElement::patternMismatch() const
240 {
241     return willValidate() && m_inputType->patternMismatch(value());
242 }
243
244 bool HTMLInputElement::tooLong(const String& value, NeedsToCheckDirtyFlag check) const
245 {
246     // We use isTextType() instead of supportsMaxLength() because of the
247     // 'virtual' overhead.
248     if (!isTextType())
249         return false;
250     int max = maxLength();
251     if (max < 0)
252         return false;
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())
257             return false;
258     }
259     return value.length() > static_cast<unsigned>(max);
260 }
261
262 bool HTMLInputElement::rangeUnderflow() const
263 {
264     return willValidate() && m_inputType->rangeUnderflow(value());
265 }
266
267 bool HTMLInputElement::rangeOverflow() const
268 {
269     return willValidate() && m_inputType->rangeOverflow(value());
270 }
271
272 String HTMLInputElement::validationMessage() const
273 {
274     if (!willValidate())
275         return String();
276
277     if (customError())
278         return customValidationMessage();
279
280     return m_inputType->validationMessage();
281 }
282
283 double HTMLInputElement::minimum() const
284 {
285     return m_inputType->minimum();
286 }
287
288 double HTMLInputElement::maximum() const
289 {
290     return m_inputType->maximum();
291 }
292
293 bool HTMLInputElement::stepMismatch() const
294 {
295     return willValidate() && m_inputType->stepMismatch(value());
296 }
297
298 bool HTMLInputElement::getAllowedValueStep(Decimal* step) const
299 {
300     return m_inputType->getAllowedValueStep(step);
301 }
302
303 StepRange HTMLInputElement::createStepRange(AnyStepHandling anyStepHandling) const
304 {
305     return m_inputType->createStepRange(anyStepHandling);
306 }
307
308 Decimal HTMLInputElement::findClosestTickMarkValue(const Decimal& value)
309 {
310     return m_inputType->findClosestTickMarkValue(value);
311 }
312
313 void HTMLInputElement::stepUp(int n, ExceptionState& exceptionState)
314 {
315     m_inputType->stepUp(n, exceptionState);
316 }
317
318 void HTMLInputElement::stepDown(int n, ExceptionState& exceptionState)
319 {
320     m_inputType->stepUp(-n, exceptionState);
321 }
322
323 void HTMLInputElement::blur()
324 {
325     m_inputTypeView->blur();
326 }
327
328 void HTMLInputElement::defaultBlur()
329 {
330     HTMLTextFormControlElement::blur();
331 }
332
333 bool HTMLInputElement::hasCustomFocusLogic() const
334 {
335     return m_inputTypeView->hasCustomFocusLogic();
336 }
337
338 bool HTMLInputElement::isKeyboardFocusable() const
339 {
340     return m_inputType->isKeyboardFocusable();
341 }
342
343 bool HTMLInputElement::shouldShowFocusRingOnMouseFocus() const
344 {
345     return m_inputType->shouldShowFocusRingOnMouseFocus();
346 }
347
348 void HTMLInputElement::updateFocusAppearance(bool restorePreviousSelection)
349 {
350     if (isTextField()) {
351         if (!restorePreviousSelection)
352             select();
353         else
354             restoreCachedSelection();
355         if (document().frame())
356             document().frame()->selection().revealSelection();
357     } else
358         HTMLTextFormControlElement::updateFocusAppearance(restorePreviousSelection);
359 }
360
361 void HTMLInputElement::beginEditing()
362 {
363     ASSERT(document().isActive());
364     if (!document().isActive())
365         return;
366
367     if (!isTextField())
368         return;
369
370     document().frame()->spellChecker().didBeginEditing(this);
371 }
372
373 void HTMLInputElement::endEditing()
374 {
375     ASSERT(document().isActive());
376     if (!document().isActive())
377         return;
378
379     if (!isTextField())
380         return;
381
382     LocalFrame* frame = document().frame();
383     frame->spellChecker().didEndEditingOnTextField(this);
384     frame->host()->chrome().client().didEndEditingOnTextField(*this);
385 }
386
387 bool HTMLInputElement::shouldUseInputMethod()
388 {
389     return m_inputType->shouldUseInputMethod();
390 }
391
392 void HTMLInputElement::handleFocusEvent(Element* oldFocusedElement, FocusType type)
393 {
394     m_inputTypeView->handleFocusEvent(oldFocusedElement, type);
395     m_inputType->enableSecureTextInput();
396 }
397
398 void HTMLInputElement::handleBlurEvent()
399 {
400     m_inputType->disableSecureTextInput();
401     m_inputTypeView->handleBlurEvent();
402 }
403
404 void HTMLInputElement::setType(const AtomicString& type)
405 {
406     setAttribute(typeAttr, type);
407 }
408
409 void HTMLInputElement::updateType()
410 {
411     const AtomicString& newTypeName = InputType::normalizeTypeName(fastGetAttribute(typeAttr));
412
413     if (m_inputType->formControlType() == newTypeName)
414         return;
415
416     RefPtrWillBeRawPtr<InputType> newType = InputType::create(*this, newTypeName);
417     removeFromRadioButtonGroup();
418
419     bool didStoreValue = m_inputType->storesValueSeparateFromAttribute();
420     bool didRespectHeightAndWidth = m_inputType->shouldRespectHeightAndWidthAttributes();
421
422     m_inputTypeView->destroyShadowSubtree();
423     lazyReattachIfAttached();
424
425     m_inputType = newType.release();
426     if (hasAuthorShadowRoot())
427         m_inputTypeView = InputTypeView::create(*this);
428     else
429         m_inputTypeView = m_inputType;
430     m_inputTypeView->createShadowSubtree();
431
432     bool hasTouchEventHandler = m_inputTypeView->hasTouchEventHandler();
433     if (hasTouchEventHandler != m_hasTouchEventHandler) {
434         if (hasTouchEventHandler)
435             document().didAddTouchEventHandler(this);
436         else
437             document().didRemoveTouchEventHandler(this);
438         m_hasTouchEventHandler = hasTouchEventHandler;
439     }
440
441     setNeedsWillValidateCheck();
442
443     bool willStoreValue = m_inputType->storesValueSeparateFromAttribute();
444
445     if (didStoreValue && !willStoreValue && hasDirtyValue()) {
446         setAttribute(valueAttr, AtomicString(m_valueIfDirty));
447         m_valueIfDirty = String();
448     }
449     if (!didStoreValue && willStoreValue) {
450         AtomicString valueString = fastGetAttribute(valueAttr);
451         m_valueIfDirty = sanitizeValue(valueString);
452     } else
453         updateValueIfNeeded();
454
455     m_needsToUpdateViewValue = true;
456     m_inputTypeView->updateView();
457
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());
466     }
467
468     if (document().focusedElement() == this)
469         document().updateFocusAppearanceSoon(true /* restore selection */);
470
471     setChangedSinceLastFormControlChangeEvent(false);
472
473     addToRadioButtonGroup();
474
475     setNeedsValidityCheck();
476     notifyFormStateChanged();
477 }
478
479 void HTMLInputElement::subtreeHasChanged()
480 {
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();
484 }
485
486 const AtomicString& HTMLInputElement::formControlType() const
487 {
488     return m_inputType->formControlType();
489 }
490
491 bool HTMLInputElement::shouldSaveAndRestoreFormControlState() const
492 {
493     if (!m_inputType->shouldSaveAndRestoreFormControlState())
494         return false;
495     return HTMLTextFormControlElement::shouldSaveAndRestoreFormControlState();
496 }
497
498 FormControlState HTMLInputElement::saveFormControlState() const
499 {
500     return m_inputType->saveFormControlState();
501 }
502
503 void HTMLInputElement::restoreFormControlState(const FormControlState& state)
504 {
505     m_inputType->restoreFormControlState(state);
506     m_stateRestored = true;
507 }
508
509 bool HTMLInputElement::canStartSelection() const
510 {
511     if (!isTextField())
512         return false;
513     return HTMLTextFormControlElement::canStartSelection();
514 }
515
516 int HTMLInputElement::selectionStartForBinding(ExceptionState& exceptionState) const
517 {
518     if (!m_inputType->supportsSelectionAPI()) {
519         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
520         return 0;
521     }
522     return HTMLTextFormControlElement::selectionStart();
523 }
524
525 int HTMLInputElement::selectionEndForBinding(ExceptionState& exceptionState) const
526 {
527     if (!m_inputType->supportsSelectionAPI()) {
528         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
529         return 0;
530     }
531     return HTMLTextFormControlElement::selectionEnd();
532 }
533
534 String HTMLInputElement::selectionDirectionForBinding(ExceptionState& exceptionState) const
535 {
536     if (!m_inputType->supportsSelectionAPI()) {
537         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
538         return String();
539     }
540     return HTMLTextFormControlElement::selectionDirection();
541 }
542
543 void HTMLInputElement::setSelectionStartForBinding(int start, ExceptionState& exceptionState)
544 {
545     if (!m_inputType->supportsSelectionAPI()) {
546         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
547         return;
548     }
549     HTMLTextFormControlElement::setSelectionStart(start);
550 }
551
552 void HTMLInputElement::setSelectionEndForBinding(int end, ExceptionState& exceptionState)
553 {
554     if (!m_inputType->supportsSelectionAPI()) {
555         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
556         return;
557     }
558     HTMLTextFormControlElement::setSelectionEnd(end);
559 }
560
561 void HTMLInputElement::setSelectionDirectionForBinding(const String& direction, ExceptionState& exceptionState)
562 {
563     if (!m_inputType->supportsSelectionAPI()) {
564         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
565         return;
566     }
567     HTMLTextFormControlElement::setSelectionDirection(direction);
568 }
569
570 void HTMLInputElement::setSelectionRangeForBinding(int start, int end, ExceptionState& exceptionState)
571 {
572     if (!m_inputType->supportsSelectionAPI()) {
573         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
574         return;
575     }
576     HTMLTextFormControlElement::setSelectionRange(start, end);
577 }
578
579 void HTMLInputElement::setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionState& exceptionState)
580 {
581     if (!m_inputType->supportsSelectionAPI()) {
582         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
583         return;
584     }
585     HTMLTextFormControlElement::setSelectionRange(start, end, direction);
586 }
587
588 void HTMLInputElement::accessKeyAction(bool sendMouseEvents)
589 {
590     m_inputType->accessKeyAction(sendMouseEvents);
591 }
592
593 bool HTMLInputElement::isPresentationAttribute(const QualifiedName& name) const
594 {
595     if (name == vspaceAttr || name == hspaceAttr || name == alignAttr || name == widthAttr || name == heightAttr || (name == borderAttr && isImageButton()))
596         return true;
597     return HTMLTextFormControlElement::isPresentationAttribute(name);
598 }
599
600 void HTMLInputElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
601 {
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);
619     else
620         HTMLTextFormControlElement::collectStyleForPresentationAttribute(name, value, style);
621 }
622
623 void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
624 {
625     if (name == nameAttr) {
626         removeFromRadioButtonGroup();
627         m_name = value;
628         addToRadioButtonGroup();
629         HTMLTextFormControlElement::parseAttribute(name, value);
630     } else if (name == autocompleteAttr) {
631         if (equalIgnoringCase(value, "off"))
632             m_autocomplete = Off;
633         else {
634             if (value.isEmpty())
635                 m_autocomplete = Uninitialized;
636             else
637                 m_autocomplete = On;
638         }
639     } else if (name == typeAttr)
640         updateType();
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);
646         }
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;
659         }
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();
722         }
723         UseCounter::count(document(), UseCounter::ListAttribute);
724     } else if (name == webkitdirectoryAttr) {
725         HTMLTextFormControlElement::parseAttribute(name, value);
726         UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute);
727     }
728     else
729         HTMLTextFormControlElement::parseAttribute(name, value);
730     m_inputTypeView->attributeChanged();
731 }
732
733 void HTMLInputElement::finishParsingChildren()
734 {
735     m_parsingInProgress = false;
736     HTMLTextFormControlElement::finishParsingChildren();
737     if (!m_stateRestored) {
738         bool checked = hasAttribute(checkedAttr);
739         if (checked)
740             setChecked(checked);
741         m_reflectsCheckedAttribute = true;
742     }
743 }
744
745 bool HTMLInputElement::rendererIsNeeded(const RenderStyle& style)
746 {
747     return m_inputType->rendererIsNeeded() && HTMLTextFormControlElement::rendererIsNeeded(style);
748 }
749
750 RenderObject* HTMLInputElement::createRenderer(RenderStyle* style)
751 {
752     return m_inputTypeView->createRenderer(style);
753 }
754
755 void HTMLInputElement::attach(const AttachContext& context)
756 {
757     HTMLTextFormControlElement::attach(context);
758
759     m_inputTypeView->startResourceLoading();
760     m_inputType->countUsage();
761
762     if (document().focusedElement() == this)
763         document().updateFocusAppearanceSoon(true /* restore selection */);
764 }
765
766 void HTMLInputElement::detach(const AttachContext& context)
767 {
768     HTMLTextFormControlElement::detach(context);
769     m_needsToUpdateViewValue = true;
770     m_inputTypeView->closePopupView();
771 }
772
773 String HTMLInputElement::altText() const
774 {
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
780     if (alt.isNull())
781         alt = fastGetAttribute(titleAttr);
782     if (alt.isNull())
783         alt = fastGetAttribute(valueAttr);
784     if (alt.isEmpty())
785         alt = locale().queryString(blink::WebLocalizedString::InputElementAltText);
786     return alt;
787 }
788
789 bool HTMLInputElement::canBeSuccessfulSubmitButton() const
790 {
791     return m_inputType->canBeSuccessfulSubmitButton();
792 }
793
794 bool HTMLInputElement::isActivatedSubmit() const
795 {
796     return m_isActivatedSubmit;
797 }
798
799 void HTMLInputElement::setActivatedSubmit(bool flag)
800 {
801     m_isActivatedSubmit = flag;
802 }
803
804 bool HTMLInputElement::appendFormData(FormDataList& encoding, bool multipart)
805 {
806     return m_inputType->isFormDataAppendable() && m_inputType->appendFormData(encoding, multipart);
807 }
808
809 String HTMLInputElement::resultForDialogSubmit()
810 {
811     return m_inputType->resultForDialogSubmit();
812 }
813
814 void HTMLInputElement::resetImpl()
815 {
816     if (m_inputType->storesValueSeparateFromAttribute()) {
817         setValue(String());
818         setNeedsValidityCheck();
819     }
820
821     setChecked(hasAttribute(checkedAttr));
822     m_reflectsCheckedAttribute = true;
823 }
824
825 bool HTMLInputElement::isTextField() const
826 {
827     return m_inputType->isTextField();
828 }
829
830 bool HTMLInputElement::isTextType() const
831 {
832     return m_inputType->isTextType();
833 }
834
835 void HTMLInputElement::setChecked(bool nowChecked, TextFieldEventBehavior eventBehavior)
836 {
837     if (checked() == nowChecked)
838         return;
839
840     RefPtrWillBeRawPtr<HTMLInputElement> protector(this);
841     m_reflectsCheckedAttribute = false;
842     m_isChecked = nowChecked;
843     setNeedsStyleRecalc(SubtreeStyleChange);
844
845     if (RadioButtonGroupScope* scope = radioButtonGroupScope())
846         scope->updateCheckedState(this);
847     if (renderer() && renderer()->style()->hasAppearance())
848         RenderTheme::theme().stateChanged(renderer(), CheckedState);
849
850     setNeedsValidityCheck();
851
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.
855     if (renderer()) {
856         if (AXObjectCache* cache = renderer()->document().existingAXObjectCache())
857             cache->checkedStateChanged(this);
858     }
859
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();
870     }
871
872     didAffectSelector(AffectedSelectorChecked);
873 }
874
875 void HTMLInputElement::setIndeterminate(bool newValue)
876 {
877     if (indeterminate() == newValue)
878         return;
879
880     m_isIndeterminate = newValue;
881
882     didAffectSelector(AffectedSelectorIndeterminate);
883
884     if (renderer() && renderer()->style()->hasAppearance())
885         RenderTheme::theme().stateChanged(renderer(), CheckedState);
886 }
887
888 int HTMLInputElement::size() const
889 {
890     return m_size;
891 }
892
893 bool HTMLInputElement::sizeShouldIncludeDecoration(int& preferredSize) const
894 {
895     return m_inputTypeView->sizeShouldIncludeDecoration(defaultSize, preferredSize);
896 }
897
898 void HTMLInputElement::copyNonAttributePropertiesFromElement(const Element& source)
899 {
900     const HTMLInputElement& sourceElement = static_cast<const HTMLInputElement&>(source);
901
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);
907
908     HTMLTextFormControlElement::copyNonAttributePropertiesFromElement(source);
909
910     m_needsToUpdateViewValue = true;
911     m_inputTypeView->updateView();
912 }
913
914 String HTMLInputElement::value() const
915 {
916     String value;
917     if (m_inputType->getTypeSpecificValue(value))
918         return value;
919
920     value = m_valueIfDirty;
921     if (!value.isNull())
922         return value;
923
924     AtomicString valueString = fastGetAttribute(valueAttr);
925     value = sanitizeValue(valueString);
926     if (!value.isNull())
927         return value;
928
929     return m_inputType->fallbackValue();
930 }
931
932 String HTMLInputElement::valueWithDefault() const
933 {
934     String value = this->value();
935     if (!value.isNull())
936         return value;
937
938     return m_inputType->defaultValue();
939 }
940
941 void HTMLInputElement::setValueForUser(const String& value)
942 {
943     // Call setValue and make it send a change event.
944     setValue(value, DispatchChangeEvent);
945 }
946
947 const String& HTMLInputElement::suggestedValue() const
948 {
949     return m_suggestedValue;
950 }
951
952 void HTMLInputElement::setSuggestedValue(const String& value)
953 {
954     if (!m_inputType->canSetSuggestedValue())
955         return;
956     m_needsToUpdateViewValue = true;
957     m_suggestedValue = sanitizeValue(value);
958     setNeedsStyleRecalc(SubtreeStyleChange);
959     m_inputTypeView->updateView();
960 }
961
962 void HTMLInputElement::setEditingValue(const String& value)
963 {
964     if (!renderer() || !isTextField())
965         return;
966     setInnerTextValue(value);
967     subtreeHasChanged();
968
969     unsigned max = value.length();
970     if (focused())
971         setSelectionRange(max, max);
972     else
973         cacheSelectionInResponseToSetValue(max);
974
975     dispatchInputEvent();
976 }
977
978 void HTMLInputElement::setInnerTextValue(const String& value)
979 {
980     HTMLTextFormControlElement::setInnerTextValue(value);
981     m_needsToUpdateViewValue = false;
982 }
983
984 void HTMLInputElement::setValue(const String& value, ExceptionState& exceptionState, TextFieldEventBehavior eventBehavior)
985 {
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.");
988         return;
989     }
990     setValue(value, eventBehavior);
991 }
992
993 void HTMLInputElement::setValue(const String& value, TextFieldEventBehavior eventBehavior)
994 {
995     if (!m_inputType->canSetValue(value))
996         return;
997
998     RefPtrWillBeRawPtr<HTMLInputElement> protector(this);
999     EventQueueScope scope;
1000     String sanitizedValue = sanitizeValue(value);
1001     bool valueChanged = sanitizedValue != this->value();
1002
1003     setLastChangeWasNotUserEdit();
1004     m_needsToUpdateViewValue = true;
1005     m_suggestedValue = String(); // Prevent TextFieldInputType::setValue from using the suggested value.
1006
1007     m_inputType->setValue(sanitizedValue, valueChanged, eventBehavior);
1008
1009     if (valueChanged && eventBehavior == DispatchNoEvent)
1010         setTextAsOfLastFormControlChangeEvent(sanitizedValue);
1011
1012     if (!valueChanged)
1013         return;
1014
1015     notifyFormStateChanged();
1016 }
1017
1018 void HTMLInputElement::setValueInternal(const String& sanitizedValue, TextFieldEventBehavior eventBehavior)
1019 {
1020     m_valueIfDirty = sanitizedValue;
1021     setNeedsValidityCheck();
1022     if (document().focusedElement() == this)
1023         document().frameHost()->chrome().client().didUpdateTextOfFocusedElementByNonUserInput();
1024 }
1025
1026 void HTMLInputElement::updateView()
1027 {
1028     m_inputTypeView->updateView();
1029 }
1030
1031 double HTMLInputElement::valueAsDate(bool& isNull) const
1032 {
1033     double date =  m_inputType->valueAsDate();
1034     isNull = !std::isfinite(date);
1035     return date;
1036 }
1037
1038 void HTMLInputElement::setValueAsDate(double value, ExceptionState& exceptionState)
1039 {
1040     m_inputType->setValueAsDate(value, exceptionState);
1041 }
1042
1043 double HTMLInputElement::valueAsNumber() const
1044 {
1045     return m_inputType->valueAsDouble();
1046 }
1047
1048 void HTMLInputElement::setValueAsNumber(double newValue, ExceptionState& exceptionState, TextFieldEventBehavior eventBehavior)
1049 {
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));
1054         return;
1055     }
1056     m_inputType->setValueAsDouble(newValue, eventBehavior, exceptionState);
1057 }
1058
1059 void HTMLInputElement::setValueFromRenderer(const String& value)
1060 {
1061     // File upload controls will never use this.
1062     ASSERT(!isFileUpload());
1063
1064     m_suggestedValue = String();
1065
1066     // Renderer and our event handler are responsible for sanitizing values.
1067     ASSERT(value == sanitizeValue(value) || sanitizeValue(value).isEmpty());
1068
1069     m_valueIfDirty = value;
1070     m_needsToUpdateViewValue = false;
1071
1072     // Input event is fired by the Node::defaultEventHandler for editable controls.
1073     if (!isTextField())
1074         dispatchInputEvent();
1075     notifyFormStateChanged();
1076
1077     setNeedsValidityCheck();
1078
1079     // Clear autofill flag (and yellow background) on user edit.
1080     setAutofilled(false);
1081 }
1082
1083 void* HTMLInputElement::preDispatchEventHandler(Event* event)
1084 {
1085     if (event->type() == EventTypeNames::textInput && m_inputTypeView->shouldSubmitImplicitly(event)) {
1086         event->stopPropagation();
1087         return 0;
1088     }
1089     if (event->type() != EventTypeNames::click)
1090         return 0;
1091     if (!event->isMouseEvent() || toMouseEvent(event)->button() != LeftButton)
1092         return 0;
1093     // FIXME: Check whether there are any cases where this actually ends up leaking.
1094     return m_inputTypeView->willDispatchClick().leakPtr();
1095 }
1096
1097 void HTMLInputElement::postDispatchEventHandler(Event* event, void* dataFromPreDispatch)
1098 {
1099     OwnPtr<ClickHandlingState> state = adoptPtr(static_cast<ClickHandlingState*>(dataFromPreDispatch));
1100     if (!state)
1101         return;
1102     m_inputTypeView->didDispatchClick(event, *state);
1103 }
1104
1105 void HTMLInputElement::defaultEventHandler(Event* evt)
1106 {
1107     if (evt->isMouseEvent() && evt->type() == EventTypeNames::click && toMouseEvent(evt)->button() == LeftButton) {
1108         m_inputTypeView->handleClickEvent(toMouseEvent(evt));
1109         if (evt->defaultHandled())
1110             return;
1111     }
1112
1113     if (evt->isTouchEvent() && m_inputTypeView->hasTouchEventHandler()) {
1114         m_inputTypeView->handleTouchEvent(toTouchEvent(evt));
1115         if (evt->defaultHandled())
1116             return;
1117     }
1118
1119     if (evt->isKeyboardEvent() && evt->type() == EventTypeNames::keydown) {
1120         m_inputTypeView->handleKeydownEvent(toKeyboardEvent(evt));
1121         if (evt->defaultHandled())
1122             return;
1123     }
1124
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())
1131             return;
1132     }
1133
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())
1141             return;
1142     }
1143
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())
1149             return;
1150     }
1151
1152     if (evt->isKeyboardEvent() && evt->type() == EventTypeNames::keyup) {
1153         m_inputTypeView->handleKeyupEvent(toKeyboardEvent(evt));
1154         if (evt->defaultHandled())
1155             return;
1156     }
1157
1158     if (m_inputTypeView->shouldSubmitImplicitly(evt)) {
1159         if (isSearchField())
1160             onSearch();
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();
1165
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());
1170
1171         evt->setDefaultHandled();
1172         return;
1173     }
1174
1175     if (evt->isBeforeTextInsertedEvent())
1176         m_inputTypeView->handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(evt));
1177
1178     if (evt->isMouseEvent() && evt->type() == EventTypeNames::mousedown) {
1179         m_inputTypeView->handleMouseDownEvent(toMouseEvent(evt));
1180         if (evt->defaultHandled())
1181             return;
1182     }
1183
1184     m_inputTypeView->forwardEvent(evt);
1185
1186     if (!callBaseClassEarly && !evt->defaultHandled())
1187         HTMLTextFormControlElement::defaultEventHandler(evt);
1188 }
1189
1190 bool HTMLInputElement::willRespondToMouseClickEvents()
1191 {
1192     // FIXME: Consider implementing willRespondToMouseClickEvents() in InputType if more accurate results are necessary.
1193     if (!isDisabledFormControl())
1194         return true;
1195
1196     return HTMLTextFormControlElement::willRespondToMouseClickEvents();
1197 }
1198
1199 bool HTMLInputElement::isURLAttribute(const Attribute& attribute) const
1200 {
1201     return attribute.name() == srcAttr || attribute.name() == formactionAttr || HTMLTextFormControlElement::isURLAttribute(attribute);
1202 }
1203
1204 bool HTMLInputElement::hasLegalLinkAttribute(const QualifiedName& name) const
1205 {
1206     return m_inputType->hasLegalLinkAttribute(name) || HTMLTextFormControlElement::hasLegalLinkAttribute(name);
1207 }
1208
1209 const QualifiedName& HTMLInputElement::subResourceAttributeName() const
1210 {
1211     return m_inputType->subResourceAttributeName();
1212 }
1213
1214 const AtomicString& HTMLInputElement::defaultValue() const
1215 {
1216     return fastGetAttribute(valueAttr);
1217 }
1218
1219 void HTMLInputElement::setDefaultValue(const AtomicString& value)
1220 {
1221     setAttribute(valueAttr, value);
1222 }
1223
1224 static inline bool isRFC2616TokenCharacter(UChar ch)
1225 {
1226     return isASCII(ch) && ch > ' ' && ch != '"' && ch != '(' && ch != ')' && ch != ',' && ch != '/' && (ch < ':' || ch > '@') && (ch < '[' || ch > ']') && ch != '{' && ch != '}' && ch != 0x7f;
1227 }
1228
1229 static bool isValidMIMEType(const String& type)
1230 {
1231     size_t slashPosition = type.find('/');
1232     if (slashPosition == kNotFound || !slashPosition || slashPosition == type.length() - 1)
1233         return false;
1234     for (size_t i = 0; i < type.length(); ++i) {
1235         if (!isRFC2616TokenCharacter(type[i]) && i != slashPosition)
1236             return false;
1237     }
1238     return true;
1239 }
1240
1241 static bool isValidFileExtension(const String& type)
1242 {
1243     if (type.length() < 2)
1244         return false;
1245     return type[0] == '.';
1246 }
1247
1248 static Vector<String> parseAcceptAttribute(const String& acceptString, bool (*predicate)(const String&))
1249 {
1250     Vector<String> types;
1251     if (acceptString.isEmpty())
1252         return types;
1253
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())
1259             continue;
1260         if (!predicate(trimmedType))
1261             continue;
1262         types.append(trimmedType.lower());
1263     }
1264
1265     return types;
1266 }
1267
1268 Vector<String> HTMLInputElement::acceptMIMETypes()
1269 {
1270     return parseAcceptAttribute(fastGetAttribute(acceptAttr), isValidMIMEType);
1271 }
1272
1273 Vector<String> HTMLInputElement::acceptFileExtensions()
1274 {
1275     return parseAcceptAttribute(fastGetAttribute(acceptAttr), isValidFileExtension);
1276 }
1277
1278 const AtomicString& HTMLInputElement::alt() const
1279 {
1280     return fastGetAttribute(altAttr);
1281 }
1282
1283 int HTMLInputElement::maxLength() const
1284 {
1285     return m_maxLength;
1286 }
1287
1288 void HTMLInputElement::setMaxLength(int maxLength, ExceptionState& exceptionState)
1289 {
1290     if (maxLength < 0)
1291         exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(maxLength) + ") is negative.");
1292     else
1293         setIntegralAttribute(maxlengthAttr, maxLength);
1294 }
1295
1296 bool HTMLInputElement::multiple() const
1297 {
1298     return fastHasAttribute(multipleAttr);
1299 }
1300
1301 void HTMLInputElement::setSize(unsigned size)
1302 {
1303     setUnsignedIntegralAttribute(sizeAttr, size);
1304 }
1305
1306 void HTMLInputElement::setSize(unsigned size, ExceptionState& exceptionState)
1307 {
1308     if (!size)
1309         exceptionState.throwDOMException(IndexSizeError, "The value provided is 0, which is an invalid size.");
1310     else
1311         setSize(size);
1312 }
1313
1314 KURL HTMLInputElement::src() const
1315 {
1316     return document().completeURL(fastGetAttribute(srcAttr));
1317 }
1318
1319 FileList* HTMLInputElement::files() const
1320 {
1321     return m_inputType->files();
1322 }
1323
1324 void HTMLInputElement::setFiles(PassRefPtrWillBeRawPtr<FileList> files)
1325 {
1326     m_inputType->setFiles(files);
1327 }
1328
1329 bool HTMLInputElement::receiveDroppedFiles(const DragData* dragData)
1330 {
1331     return m_inputType->receiveDroppedFiles(dragData);
1332 }
1333
1334 String HTMLInputElement::droppedFileSystemId()
1335 {
1336     return m_inputType->droppedFileSystemId();
1337 }
1338
1339 bool HTMLInputElement::canReceiveDroppedFiles() const
1340 {
1341     return m_canReceiveDroppedFiles;
1342 }
1343
1344 void HTMLInputElement::setCanReceiveDroppedFiles(bool canReceiveDroppedFiles)
1345 {
1346     if (m_canReceiveDroppedFiles == canReceiveDroppedFiles)
1347         return;
1348     m_canReceiveDroppedFiles = canReceiveDroppedFiles;
1349     if (renderer())
1350         renderer()->updateFromElement();
1351 }
1352
1353 String HTMLInputElement::sanitizeValue(const String& proposedValue) const
1354 {
1355     if (proposedValue.isNull())
1356         return proposedValue;
1357     return m_inputType->sanitizeValue(proposedValue);
1358 }
1359
1360 String HTMLInputElement::localizeValue(const String& proposedValue) const
1361 {
1362     if (proposedValue.isNull())
1363         return proposedValue;
1364     return m_inputType->localizeValue(proposedValue);
1365 }
1366
1367 bool HTMLInputElement::isInRange() const
1368 {
1369     return m_inputType->isInRange(value());
1370 }
1371
1372 bool HTMLInputElement::isOutOfRange() const
1373 {
1374     return m_inputType->isOutOfRange(value());
1375 }
1376
1377 bool HTMLInputElement::isRequiredFormControl() const
1378 {
1379     return m_inputType->supportsRequired() && isRequired();
1380 }
1381
1382 bool HTMLInputElement::matchesReadOnlyPseudoClass() const
1383 {
1384     return m_inputType->supportsReadOnly() && isReadOnly();
1385 }
1386
1387 bool HTMLInputElement::matchesReadWritePseudoClass() const
1388 {
1389     return m_inputType->supportsReadOnly() && !isReadOnly();
1390 }
1391
1392 void HTMLInputElement::onSearch()
1393 {
1394     ASSERT(isSearchField());
1395     if (m_inputType)
1396         static_cast<SearchInputType*>(m_inputType.get())->stopSearchEventTimer();
1397     dispatchEvent(Event::createBubble(EventTypeNames::search));
1398 }
1399
1400 void HTMLInputElement::updateClearButtonVisibility()
1401 {
1402     m_inputTypeView->updateClearButtonVisibility();
1403 }
1404
1405 void HTMLInputElement::willChangeForm()
1406 {
1407     removeFromRadioButtonGroup();
1408     HTMLTextFormControlElement::willChangeForm();
1409 }
1410
1411 void HTMLInputElement::didChangeForm()
1412 {
1413     HTMLTextFormControlElement::didChangeForm();
1414     addToRadioButtonGroup();
1415 }
1416
1417 Node::InsertionNotificationRequest HTMLInputElement::insertedInto(ContainerNode* insertionPoint)
1418 {
1419     HTMLTextFormControlElement::insertedInto(insertionPoint);
1420     if (insertionPoint->inDocument() && !form())
1421         addToRadioButtonGroup();
1422     resetListAttributeTargetObserver();
1423     return InsertionDone;
1424 }
1425
1426 void HTMLInputElement::removedFrom(ContainerNode* insertionPoint)
1427 {
1428     if (insertionPoint->inDocument() && !form())
1429         removeFromRadioButtonGroup();
1430     HTMLTextFormControlElement::removedFrom(insertionPoint);
1431     ASSERT(!inDocument());
1432     resetListAttributeTargetObserver();
1433 }
1434
1435 void HTMLInputElement::didMoveToNewDocument(Document& oldDocument)
1436 {
1437     if (hasImageLoader())
1438         imageLoader()->elementDidMoveToNewDocument();
1439
1440     if (isRadioButton())
1441         oldDocument.formController().radioButtonGroupScope().removeButton(this);
1442     if (m_hasTouchEventHandler)
1443         oldDocument.didRemoveTouchEventHandler(this);
1444
1445     if (m_hasTouchEventHandler)
1446         document().didAddTouchEventHandler(this);
1447
1448     HTMLTextFormControlElement::didMoveToNewDocument(oldDocument);
1449 }
1450
1451 void HTMLInputElement::removeAllEventListeners()
1452 {
1453     HTMLTextFormControlElement::removeAllEventListeners();
1454     m_hasTouchEventHandler = false;
1455 }
1456
1457 bool HTMLInputElement::recalcWillValidate() const
1458 {
1459     return m_inputType->supportsValidation() && HTMLTextFormControlElement::recalcWillValidate();
1460 }
1461
1462 void HTMLInputElement::requiredAttributeChanged()
1463 {
1464     HTMLTextFormControlElement::requiredAttributeChanged();
1465     if (RadioButtonGroupScope* scope = radioButtonGroupScope())
1466         scope->requiredAttributeChanged(this);
1467     m_inputTypeView->requiredAttributeChanged();
1468 }
1469
1470 void HTMLInputElement::selectColorInColorChooser(const Color& color)
1471 {
1472     if (!m_inputType->isColorControl())
1473         return;
1474     static_cast<ColorInputType*>(m_inputType.get())->didChooseColor(color);
1475 }
1476
1477 HTMLElement* HTMLInputElement::list() const
1478 {
1479     return dataList();
1480 }
1481
1482 HTMLDataListElement* HTMLInputElement::dataList() const
1483 {
1484     if (!m_hasNonEmptyList)
1485         return 0;
1486
1487     if (!m_inputType->shouldRespectListAttribute())
1488         return 0;
1489
1490     Element* element = treeScope().getElementById(fastGetAttribute(listAttr));
1491     if (!element)
1492         return 0;
1493     if (!isHTMLDataListElement(*element))
1494         return 0;
1495
1496     return toHTMLDataListElement(element);
1497 }
1498
1499 bool HTMLInputElement::hasValidDataListOptions() const
1500 {
1501     HTMLDataListElement* dataList = this->dataList();
1502     if (!dataList)
1503         return false;
1504     RefPtr<HTMLCollection> options = dataList->options();
1505     for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) {
1506         if (isValidValue(option->value()))
1507             return true;
1508     }
1509     return false;
1510 }
1511
1512 void HTMLInputElement::setListAttributeTargetObserver(PassOwnPtrWillBeRawPtr<ListAttributeTargetObserver> newObserver)
1513 {
1514     if (m_listAttributeTargetObserver)
1515         m_listAttributeTargetObserver->unregister();
1516     m_listAttributeTargetObserver = newObserver;
1517 }
1518
1519 void HTMLInputElement::resetListAttributeTargetObserver()
1520 {
1521     if (inDocument())
1522         setListAttributeTargetObserver(ListAttributeTargetObserver::create(fastGetAttribute(listAttr), this));
1523     else
1524         setListAttributeTargetObserver(nullptr);
1525 }
1526
1527 void HTMLInputElement::listAttributeTargetChanged()
1528 {
1529     m_inputTypeView->listAttributeTargetChanged();
1530 }
1531
1532 bool HTMLInputElement::isSteppable() const
1533 {
1534     return m_inputType->isSteppable();
1535 }
1536
1537 bool HTMLInputElement::isTextButton() const
1538 {
1539     return m_inputType->isTextButton();
1540 }
1541
1542 bool HTMLInputElement::isRadioButton() const
1543 {
1544     return m_inputType->isRadioButton();
1545 }
1546
1547 bool HTMLInputElement::isSearchField() const
1548 {
1549     return m_inputType->isSearchField();
1550 }
1551
1552 bool HTMLInputElement::isInputTypeHidden() const
1553 {
1554     return m_inputType->isHiddenType();
1555 }
1556
1557 bool HTMLInputElement::isPasswordField() const
1558 {
1559     return m_inputType->isPasswordField();
1560 }
1561
1562 bool HTMLInputElement::isCheckbox() const
1563 {
1564     return m_inputType->isCheckbox();
1565 }
1566
1567 bool HTMLInputElement::isRangeControl() const
1568 {
1569     return m_inputType->isRangeControl();
1570 }
1571
1572 bool HTMLInputElement::isText() const
1573 {
1574     return m_inputType->isTextType();
1575 }
1576
1577 bool HTMLInputElement::isEmailField() const
1578 {
1579     return m_inputType->isEmailField();
1580 }
1581
1582 bool HTMLInputElement::isFileUpload() const
1583 {
1584     return m_inputType->isFileUpload();
1585 }
1586
1587 bool HTMLInputElement::isImageButton() const
1588 {
1589     return m_inputType->isImageButton();
1590 }
1591
1592 bool HTMLInputElement::isNumberField() const
1593 {
1594     return m_inputType->isNumberField();
1595 }
1596
1597 bool HTMLInputElement::isTelephoneField() const
1598 {
1599     return m_inputType->isTelephoneField();
1600 }
1601
1602 bool HTMLInputElement::isURLField() const
1603 {
1604     return m_inputType->isURLField();
1605 }
1606
1607 bool HTMLInputElement::isDateField() const
1608 {
1609     return m_inputType->isDateField();
1610 }
1611
1612 bool HTMLInputElement::isDateTimeLocalField() const
1613 {
1614     return m_inputType->isDateTimeLocalField();
1615 }
1616
1617 bool HTMLInputElement::isMonthField() const
1618 {
1619     return m_inputType->isMonthField();
1620 }
1621
1622 bool HTMLInputElement::isTimeField() const
1623 {
1624     return m_inputType->isTimeField();
1625 }
1626
1627 bool HTMLInputElement::isWeekField() const
1628 {
1629     return m_inputType->isWeekField();
1630 }
1631
1632 bool HTMLInputElement::isEnumeratable() const
1633 {
1634     return m_inputType->isEnumeratable();
1635 }
1636
1637 bool HTMLInputElement::supportLabels() const
1638 {
1639     return m_inputType->isInteractiveContent();
1640 }
1641
1642 bool HTMLInputElement::shouldAppearChecked() const
1643 {
1644     return checked() && m_inputType->isCheckable();
1645 }
1646
1647 bool HTMLInputElement::supportsPlaceholder() const
1648 {
1649     return m_inputType->supportsPlaceholder();
1650 }
1651
1652 void HTMLInputElement::updatePlaceholderText()
1653 {
1654     return m_inputTypeView->updatePlaceholderText();
1655 }
1656
1657 void HTMLInputElement::parseMaxLengthAttribute(const AtomicString& value)
1658 {
1659     int maxLength;
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();
1670 }
1671
1672 void HTMLInputElement::updateValueIfNeeded()
1673 {
1674     String newValue = sanitizeValue(m_valueIfDirty);
1675     ASSERT(!m_valueIfDirty.isNull() || newValue.isNull());
1676     if (newValue != m_valueIfDirty)
1677         setValue(newValue);
1678 }
1679
1680 String HTMLInputElement::defaultToolTip() const
1681 {
1682     return m_inputType->defaultToolTip();
1683 }
1684
1685 bool HTMLInputElement::shouldAppearIndeterminate() const
1686 {
1687     return m_inputType->supportsIndeterminateAppearance() && indeterminate();
1688 }
1689
1690 #if ENABLE(MEDIA_CAPTURE)
1691 bool HTMLInputElement::capture() const
1692 {
1693     if (!isFileUpload() || !fastHasAttribute(captureAttr))
1694         return false;
1695
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);
1702     else
1703         UseCounter::count(document(), UseCounter::CaptureAttributeAsBoolean);
1704
1705     return true;
1706 }
1707 #endif
1708
1709 bool HTMLInputElement::isInRequiredRadioButtonGroup()
1710 {
1711     ASSERT(isRadioButton());
1712     if (RadioButtonGroupScope* scope = radioButtonGroupScope())
1713         return scope->isInRequiredGroup(this);
1714     return false;
1715 }
1716
1717 HTMLInputElement* HTMLInputElement::checkedRadioButtonForGroup() const
1718 {
1719     if (RadioButtonGroupScope* scope = radioButtonGroupScope())
1720         return scope->checkedButtonForGroup(name());
1721     return 0;
1722 }
1723
1724 RadioButtonGroupScope* HTMLInputElement::radioButtonGroupScope() const
1725 {
1726     if (!isRadioButton())
1727         return 0;
1728     if (HTMLFormElement* formElement = form())
1729         return &formElement->radioButtonGroupScope();
1730     if (inDocument())
1731         return &document().formController().radioButtonGroupScope();
1732     return 0;
1733 }
1734
1735 inline void HTMLInputElement::addToRadioButtonGroup()
1736 {
1737     if (RadioButtonGroupScope* scope = radioButtonGroupScope())
1738         scope->addButton(this);
1739 }
1740
1741 inline void HTMLInputElement::removeFromRadioButtonGroup()
1742 {
1743     if (RadioButtonGroupScope* scope = radioButtonGroupScope())
1744         scope->removeButton(this);
1745 }
1746
1747 unsigned HTMLInputElement::height() const
1748 {
1749     return m_inputType->height();
1750 }
1751
1752 unsigned HTMLInputElement::width() const
1753 {
1754     return m_inputType->width();
1755 }
1756
1757 void HTMLInputElement::setHeight(unsigned height)
1758 {
1759     setUnsignedIntegralAttribute(heightAttr, height);
1760 }
1761
1762 void HTMLInputElement::setWidth(unsigned width)
1763 {
1764     setUnsignedIntegralAttribute(widthAttr, width);
1765 }
1766
1767 PassOwnPtrWillBeRawPtr<ListAttributeTargetObserver> ListAttributeTargetObserver::create(const AtomicString& id, HTMLInputElement* element)
1768 {
1769     return adoptPtrWillBeNoop(new ListAttributeTargetObserver(id, element));
1770 }
1771
1772 ListAttributeTargetObserver::ListAttributeTargetObserver(const AtomicString& id, HTMLInputElement* element)
1773     : IdTargetObserver(element->treeScope().idTargetObserverRegistry(), id)
1774     , m_element(element)
1775 {
1776 }
1777
1778 void ListAttributeTargetObserver::trace(Visitor* visitor)
1779 {
1780     visitor->trace(m_element);
1781     IdTargetObserver::trace(visitor);
1782 }
1783
1784 void ListAttributeTargetObserver::idTargetChanged()
1785 {
1786     m_element->listAttributeTargetChanged();
1787 }
1788
1789 void HTMLInputElement::setRangeText(const String& replacement, ExceptionState& exceptionState)
1790 {
1791     if (!m_inputType->supportsSelectionAPI()) {
1792         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
1793         return;
1794     }
1795
1796     HTMLTextFormControlElement::setRangeText(replacement, exceptionState);
1797 }
1798
1799 void HTMLInputElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& exceptionState)
1800 {
1801     if (!m_inputType->supportsSelectionAPI()) {
1802         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
1803         return;
1804     }
1805
1806     HTMLTextFormControlElement::setRangeText(replacement, start, end, selectionMode, exceptionState);
1807 }
1808
1809 bool HTMLInputElement::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
1810 {
1811     if (!document().view())
1812         return false;
1813
1814     parameters.type = type();
1815     parameters.minimum = minimum();
1816     parameters.maximum = maximum();
1817     parameters.required = isRequired();
1818     if (!RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
1819         parameters.locale = defaultLanguage();
1820     else {
1821         AtomicString computedLocale = computeInheritedLanguage();
1822         parameters.locale = computedLocale.isEmpty() ? defaultLanguage() : computedLocale;
1823     }
1824
1825     StepRange stepRange = createStepRange(RejectAny);
1826     if (stepRange.hasStep()) {
1827         parameters.step = stepRange.step().toDouble();
1828         parameters.stepBase = stepRange.stepBase().toDouble();
1829     } else {
1830         parameters.step = 1.0;
1831         parameters.stepBase = 0;
1832     }
1833
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()))
1842                 continue;
1843             DateTimeSuggestion suggestion;
1844             suggestion.value = m_inputType->parseToNumber(option->value(), Decimal::nan()).toDouble();
1845             if (std::isnan(suggestion.value))
1846                 continue;
1847             suggestion.localizedValue = localizeValue(option->value());
1848             suggestion.label = option->value() == option->label() ? String() : option->label();
1849             parameters.suggestions.append(suggestion);
1850         }
1851     }
1852     return true;
1853 }
1854
1855 bool HTMLInputElement::supportsInputModeAttribute() const
1856 {
1857     return m_inputType->supportsInputModeAttribute();
1858 }
1859
1860 void HTMLInputElement::setShouldRevealPassword(bool value)
1861 {
1862     if (m_shouldRevealPassword == value)
1863         return;
1864     m_shouldRevealPassword = value;
1865     lazyReattachIfAttached();
1866 }
1867
1868 bool HTMLInputElement::isInteractiveContent() const
1869 {
1870     return m_inputType->isInteractiveContent();
1871 }
1872
1873 bool HTMLInputElement::supportsAutofocus() const
1874 {
1875     return m_inputType->isInteractiveContent();
1876 }
1877
1878 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
1879 PassRefPtr<RenderStyle> HTMLInputElement::customStyleForRenderer()
1880 {
1881     return m_inputTypeView->customStyleForRenderer(originalStyleForRenderer());
1882 }
1883 #endif
1884
1885 bool HTMLInputElement::shouldDispatchFormControlChangeEvent(String& oldValue, String& newValue)
1886 {
1887     return m_inputType->shouldDispatchFormControlChangeEvent(oldValue, newValue);
1888 }
1889
1890 } // namespace