Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / HTMLOptionElement.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  *           (C) 2006 Alexey Proskuryakov (ap@nypop.com)
6  * Copyright (C) 2004, 2005, 2006, 2010 Apple Inc. All rights reserved.
7  * Copyright (C) 2010 Google Inc. All rights reserved.
8  * Copyright (C) 2011 Motorola Mobility, Inc.  All rights reserved.
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public License
21  * along with this library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  *
25  */
26
27 #include "config.h"
28 #include "core/html/HTMLOptionElement.h"
29
30 #include "HTMLNames.h"
31 #include "bindings/v8/ExceptionState.h"
32 #include "core/dom/Document.h"
33 #include "core/dom/NodeRenderStyle.h"
34 #include "core/dom/NodeTraversal.h"
35 #include "core/dom/ScriptLoader.h"
36 #include "core/dom/Text.h"
37 #include "core/html/HTMLDataListElement.h"
38 #include "core/html/HTMLSelectElement.h"
39 #include "core/html/parser/HTMLParserIdioms.h"
40 #include "core/rendering/RenderTheme.h"
41 #include "wtf/Vector.h"
42 #include "wtf/text/StringBuilder.h"
43
44 namespace WebCore {
45
46 using namespace HTMLNames;
47
48 HTMLOptionElement::HTMLOptionElement(Document& document)
49     : HTMLElement(optionTag, document)
50     , m_disabled(false)
51     , m_isSelected(false)
52 {
53     setHasCustomStyleCallbacks();
54     ScriptWrappable::init(this);
55 }
56
57 PassRefPtrWillBeRawPtr<HTMLOptionElement> HTMLOptionElement::create(Document& document)
58 {
59     return adoptRefWillBeRefCountedGarbageCollected(new HTMLOptionElement(document));
60 }
61
62 PassRefPtrWillBeRawPtr<HTMLOptionElement> HTMLOptionElement::createForJSConstructor(Document& document, const String& data, const AtomicString& value,
63     bool defaultSelected, bool selected, ExceptionState& exceptionState)
64 {
65     RefPtrWillBeRawPtr<HTMLOptionElement> element = adoptRefWillBeRefCountedGarbageCollected(new HTMLOptionElement(document));
66
67     RefPtr<Text> text = Text::create(document, data.isNull() ? "" : data);
68
69     element->appendChild(text.release(), exceptionState);
70     if (exceptionState.hadException())
71         return nullptr;
72
73     if (!value.isNull())
74         element->setValue(value);
75     if (defaultSelected)
76         element->setAttribute(selectedAttr, emptyAtom);
77     element->setSelected(selected);
78
79     return element.release();
80 }
81
82 void HTMLOptionElement::attach(const AttachContext& context)
83 {
84     AttachContext optionContext(context);
85     if (context.resolvedStyle) {
86         ASSERT(!m_style || m_style == context.resolvedStyle);
87         m_style = context.resolvedStyle;
88     } else {
89         updateNonRenderStyle();
90         optionContext.resolvedStyle = m_style.get();
91     }
92     HTMLElement::attach(optionContext);
93 }
94
95 void HTMLOptionElement::detach(const AttachContext& context)
96 {
97     m_style.clear();
98     HTMLElement::detach(context);
99 }
100
101 bool HTMLOptionElement::rendererIsFocusable() const
102 {
103     // Option elements do not have a renderer so we check the renderStyle instead.
104     return renderStyle() && renderStyle()->display() != NONE;
105 }
106
107 String HTMLOptionElement::text() const
108 {
109     Document& document = this->document();
110     String text;
111
112     // WinIE does not use the label attribute, so as a quirk, we ignore it.
113     if (!document.inQuirksMode())
114         text = fastGetAttribute(labelAttr);
115
116     // FIXME: The following treats an element with the label attribute set to
117     // the empty string the same as an element with no label attribute at all.
118     // Is that correct? If it is, then should the label function work the same way?
119     if (text.isEmpty())
120         text = collectOptionInnerText();
121
122     return text.stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
123 }
124
125 void HTMLOptionElement::setText(const String &text, ExceptionState& exceptionState)
126 {
127     RefPtr<Node> protectFromMutationEvents(this);
128
129     // Changing the text causes a recalc of a select's items, which will reset the selected
130     // index to the first item if the select is single selection with a menu list. We attempt to
131     // preserve the selected item.
132     RefPtrWillBeRawPtr<HTMLSelectElement> select = ownerSelectElement();
133     bool selectIsMenuList = select && select->usesMenuList();
134     int oldSelectedIndex = selectIsMenuList ? select->selectedIndex() : -1;
135
136     // Handle the common special case where there's exactly 1 child node, and it's a text node.
137     Node* child = firstChild();
138     if (child && child->isTextNode() && !child->nextSibling())
139         toText(child)->setData(text);
140     else {
141         removeChildren();
142         appendChild(Text::create(document(), text), exceptionState);
143     }
144
145     if (selectIsMenuList && select->selectedIndex() != oldSelectedIndex)
146         select->setSelectedIndex(oldSelectedIndex);
147 }
148
149 void HTMLOptionElement::accessKeyAction(bool)
150 {
151     if (HTMLSelectElement* select = ownerSelectElement())
152         select->accessKeySetSelectedIndex(index());
153 }
154
155 int HTMLOptionElement::index() const
156 {
157     // It would be faster to cache the index, but harder to get it right in all cases.
158
159     HTMLSelectElement* selectElement = ownerSelectElement();
160     if (!selectElement)
161         return 0;
162
163     int optionIndex = 0;
164
165     const WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >& items = selectElement->listItems();
166     size_t length = items.size();
167     for (size_t i = 0; i < length; ++i) {
168         if (!isHTMLOptionElement(*items[i]))
169             continue;
170         if (items[i].get() == this)
171             return optionIndex;
172         ++optionIndex;
173     }
174
175     return 0;
176 }
177
178 void HTMLOptionElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
179 {
180     if (name == valueAttr) {
181         if (HTMLDataListElement* dataList = ownerDataListElement())
182             dataList->optionElementChildrenChanged();
183     } else if (name == disabledAttr) {
184         bool oldDisabled = m_disabled;
185         m_disabled = !value.isNull();
186         if (oldDisabled != m_disabled) {
187             didAffectSelector(AffectedSelectorDisabled | AffectedSelectorEnabled);
188             if (renderer() && renderer()->style()->hasAppearance())
189                 RenderTheme::theme().stateChanged(renderer(), EnabledState);
190         }
191     } else if (name == selectedAttr) {
192         if (bool willBeSelected = !value.isNull())
193             setSelected(willBeSelected);
194     } else
195         HTMLElement::parseAttribute(name, value);
196 }
197
198 String HTMLOptionElement::value() const
199 {
200     const AtomicString& value = fastGetAttribute(valueAttr);
201     if (!value.isNull())
202         return value;
203     return collectOptionInnerText().stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
204 }
205
206 void HTMLOptionElement::setValue(const AtomicString& value)
207 {
208     setAttribute(valueAttr, value);
209 }
210
211 bool HTMLOptionElement::selected() const
212 {
213     if (HTMLSelectElement* select = ownerSelectElement()) {
214         // If a stylesheet contains option:checked selectors, this function is
215         // called during parsing. updateListItemSelectedStates() is O(N) where N
216         // is the number of option elements, so the <select> parsing would be
217         // O(N^2) without the isFinishedParsingChildren check. Also,
218         // updateListItemSelectedStates() determines default selection, and we'd
219         // like to avoid to determine default selection with incomplete option
220         // list.
221         if (!select->isFinishedParsingChildren())
222             return m_isSelected;
223         select->updateListItemSelectedStates();
224     }
225     return m_isSelected;
226 }
227
228 void HTMLOptionElement::setSelected(bool selected)
229 {
230     if (m_isSelected == selected)
231         return;
232
233     setSelectedState(selected);
234
235     if (HTMLSelectElement* select = ownerSelectElement())
236         select->optionSelectionStateChanged(this, selected);
237 }
238
239 void HTMLOptionElement::setSelectedState(bool selected)
240 {
241     if (m_isSelected == selected)
242         return;
243
244     m_isSelected = selected;
245     didAffectSelector(AffectedSelectorChecked);
246
247     if (HTMLSelectElement* select = ownerSelectElement())
248         select->invalidateSelectedItems();
249 }
250
251 void HTMLOptionElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
252 {
253     if (HTMLDataListElement* dataList = ownerDataListElement())
254         dataList->optionElementChildrenChanged();
255     else if (HTMLSelectElement* select = ownerSelectElement())
256         select->optionElementChildrenChanged();
257     HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
258 }
259
260 HTMLDataListElement* HTMLOptionElement::ownerDataListElement() const
261 {
262     return Traversal<HTMLDataListElement>::firstAncestor(*this);
263 }
264
265 HTMLSelectElement* HTMLOptionElement::ownerSelectElement() const
266 {
267     return Traversal<HTMLSelectElement>::firstAncestor(*this);
268 }
269
270 String HTMLOptionElement::label() const
271 {
272     const AtomicString& label = fastGetAttribute(labelAttr);
273     if (!label.isNull())
274         return label;
275     return collectOptionInnerText().stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
276 }
277
278 void HTMLOptionElement::setLabel(const AtomicString& label)
279 {
280     setAttribute(labelAttr, label);
281 }
282
283 void HTMLOptionElement::updateNonRenderStyle()
284 {
285     bool oldDisplayNoneStatus = isDisplayNone();
286     m_style = originalStyleForRenderer();
287     if (oldDisplayNoneStatus != isDisplayNone()) {
288         if (HTMLSelectElement* select = ownerSelectElement())
289             select->updateListOnRenderer();
290     }
291 }
292
293 RenderStyle* HTMLOptionElement::nonRendererStyle() const
294 {
295     return m_style.get();
296 }
297
298 PassRefPtr<RenderStyle> HTMLOptionElement::customStyleForRenderer()
299 {
300     updateNonRenderStyle();
301     return m_style;
302 }
303
304 void HTMLOptionElement::didRecalcStyle(StyleRecalcChange change)
305 {
306     if (change == NoChange)
307         return;
308
309     // FIXME: We ask our owner select to repaint regardless of which property changed.
310     if (HTMLSelectElement* select = ownerSelectElement()) {
311         if (RenderObject* renderer = select->renderer())
312             renderer->repaint();
313     }
314 }
315
316 String HTMLOptionElement::textIndentedToRespectGroupLabel() const
317 {
318     ContainerNode* parent = parentNode();
319     if (parent && isHTMLOptGroupElement(*parent))
320         return "    " + text();
321     return text();
322 }
323
324 bool HTMLOptionElement::isDisabledFormControl() const
325 {
326     if (ownElementDisabled())
327         return true;
328     if (Element* parent = parentElement())
329         return isHTMLOptGroupElement(*parent) && parent->isDisabledFormControl();
330     return false;
331 }
332
333 Node::InsertionNotificationRequest HTMLOptionElement::insertedInto(ContainerNode* insertionPoint)
334 {
335     if (HTMLSelectElement* select = ownerSelectElement()) {
336         select->setRecalcListItems();
337         // Do not call selected() since calling updateListItemSelectedStates()
338         // at this time won't do the right thing. (Why, exactly?)
339         // FIXME: Might be better to call this unconditionally, always passing m_isSelected,
340         // rather than only calling it if we are selected.
341         if (m_isSelected)
342             select->optionSelectionStateChanged(this, true);
343         select->scrollToSelection();
344     }
345
346     return HTMLElement::insertedInto(insertionPoint);
347 }
348
349 String HTMLOptionElement::collectOptionInnerText() const
350 {
351     StringBuilder text;
352     for (Node* node = firstChild(); node; ) {
353         if (node->isTextNode())
354             text.append(node->nodeValue());
355         // Text nodes inside script elements are not part of the option text.
356         if (node->isElementNode() && toScriptLoaderIfPossible(toElement(node)))
357             node = NodeTraversal::nextSkippingChildren(*node, this);
358         else
359             node = NodeTraversal::next(*node, this);
360     }
361     return text.toString();
362 }
363
364 HTMLFormElement* HTMLOptionElement::form() const
365 {
366     if (HTMLSelectElement* selectElement = ownerSelectElement())
367         return selectElement->formOwner();
368
369     return 0;
370 }
371
372 bool HTMLOptionElement::isDisplayNone() const
373 {
374     ContainerNode* parent = parentNode();
375     // Check for parent optgroup having display NONE
376     if (parent && isHTMLOptGroupElement(*parent)) {
377         if (toHTMLOptGroupElement(*parent).isDisplayNone())
378             return true;
379     }
380     RenderStyle* style = nonRendererStyle();
381     return style && style->display() == NONE;
382 }
383
384 } // namespace WebCore