1/*
2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 * Library General Public License for more details.
15 *
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB.  If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 *
21 */
22
23#include "config.h"
24#include "HTMLCollection.h"
25
26#include "HTMLDocument.h"
27#include "HTMLElement.h"
28#include "HTMLNames.h"
29#include "HTMLObjectElement.h"
30#include "HTMLOptionElement.h"
31#include "NodeList.h"
32
33#include <utility>
34
35namespace WebCore {
36
37using namespace HTMLNames;
38
39HTMLCollection::HTMLCollection(PassRefPtr<Node> base, CollectionType type)
40    : m_idsDone(false)
41    , m_base(base)
42    , m_type(type)
43    , m_info(m_base->isDocumentNode() ? static_cast<Document*>(m_base.get())->collectionInfo(type) : 0)
44    , m_ownsInfo(false)
45{
46}
47
48HTMLCollection::HTMLCollection(PassRefPtr<Node> base, CollectionType type, CollectionCache* info)
49    : m_idsDone(false)
50    , m_base(base)
51    , m_type(type)
52    , m_info(info)
53    , m_ownsInfo(false)
54{
55}
56
57PassRefPtr<HTMLCollection> HTMLCollection::create(PassRefPtr<Node> base, CollectionType type)
58{
59    return adoptRef(new HTMLCollection(base, type));
60}
61
62HTMLCollection::~HTMLCollection()
63{
64    if (m_ownsInfo)
65        delete m_info;
66}
67
68void HTMLCollection::resetCollectionInfo() const
69{
70    uint64_t docversion = static_cast<HTMLDocument*>(m_base->document())->domTreeVersion();
71
72    if (!m_info) {
73        m_info = new CollectionCache;
74        m_ownsInfo = true;
75        m_info->version = docversion;
76        return;
77    }
78
79    if (m_info->version != docversion) {
80        m_info->reset();
81        m_info->version = docversion;
82    }
83}
84
85static Node* nextNodeOrSibling(Node* base, Node* node, bool includeChildren)
86{
87    return includeChildren ? node->traverseNextNode(base) : node->traverseNextSibling(base);
88}
89
90Element* HTMLCollection::itemAfter(Element* previous) const
91{
92    bool deep = true;
93
94    switch (m_type) {
95        case DocAll:
96        case DocAnchors:
97        case DocApplets:
98        case DocEmbeds:
99        case DocForms:
100        case DocImages:
101        case DocLinks:
102        case DocObjects:
103        case DocScripts:
104        case DocumentNamedItems:
105        case MapAreas:
106        case OtherCollection:
107        case SelectOptions:
108        case DataListOptions:
109        case WindowNamedItems:
110            break;
111        case NodeChildren:
112        case TRCells:
113        case TSectionRows:
114        case TableTBodies:
115            deep = false;
116            break;
117    }
118
119    Node* current;
120    if (!previous)
121        current = m_base->firstChild();
122    else
123        current = nextNodeOrSibling(m_base.get(), previous, deep);
124
125    for (; current; current = nextNodeOrSibling(m_base.get(), current, deep)) {
126        if (!current->isElementNode())
127            continue;
128        Element* e = static_cast<Element*>(current);
129        switch (m_type) {
130            case DocImages:
131                if (e->hasLocalName(imgTag))
132                    return e;
133                break;
134            case DocScripts:
135                if (e->hasLocalName(scriptTag))
136                    return e;
137                break;
138            case DocForms:
139                if (e->hasLocalName(formTag))
140                    return e;
141                break;
142            case TableTBodies:
143                if (e->hasLocalName(tbodyTag))
144                    return e;
145                break;
146            case TRCells:
147                if (e->hasLocalName(tdTag) || e->hasLocalName(thTag))
148                    return e;
149                break;
150            case TSectionRows:
151                if (e->hasLocalName(trTag))
152                    return e;
153                break;
154            case SelectOptions:
155                if (e->hasLocalName(optionTag))
156                    return e;
157                break;
158            case DataListOptions:
159                if (e->hasLocalName(optionTag)) {
160                    HTMLOptionElement* option = static_cast<HTMLOptionElement*>(e);
161                    if (!option->disabled() && !option->value().isEmpty())
162                        return e;
163                }
164                break;
165            case MapAreas:
166                if (e->hasLocalName(areaTag))
167                    return e;
168                break;
169            case DocApplets: // all <applet> elements and <object> elements that contain Java Applets
170                if (e->hasLocalName(appletTag))
171                    return e;
172                if (e->hasLocalName(objectTag) && static_cast<HTMLObjectElement*>(e)->containsJavaApplet())
173                    return e;
174                break;
175            case DocEmbeds:
176                if (e->hasLocalName(embedTag))
177                    return e;
178                break;
179            case DocObjects:
180                if (e->hasLocalName(objectTag))
181                    return e;
182                break;
183            case DocLinks: // all <a> and <area> elements with a value for href
184                if ((e->hasLocalName(aTag) || e->hasLocalName(areaTag)) && e->fastHasAttribute(hrefAttr))
185                    return e;
186                break;
187            case DocAnchors: // all <a> elements with a value for name
188                if (e->hasLocalName(aTag) && e->fastHasAttribute(nameAttr))
189                    return e;
190                break;
191            case DocAll:
192            case NodeChildren:
193                return e;
194            case DocumentNamedItems:
195            case OtherCollection:
196            case WindowNamedItems:
197                ASSERT_NOT_REACHED();
198                break;
199        }
200    }
201
202    return 0;
203}
204
205unsigned HTMLCollection::calcLength() const
206{
207    unsigned len = 0;
208    for (Element* current = itemAfter(0); current; current = itemAfter(current))
209        ++len;
210    return len;
211}
212
213// since the collections are to be "live", we have to do the
214// calculation every time if anything has changed
215unsigned HTMLCollection::length() const
216{
217    resetCollectionInfo();
218    if (!m_info->hasLength) {
219        m_info->length = calcLength();
220        m_info->hasLength = true;
221    }
222    return m_info->length;
223}
224
225Node* HTMLCollection::item(unsigned index) const
226{
227     resetCollectionInfo();
228     if (m_info->current && m_info->position == index)
229         return m_info->current;
230     if (m_info->hasLength && m_info->length <= index)
231         return 0;
232     if (!m_info->current || m_info->position > index) {
233         m_info->current = itemAfter(0);
234         m_info->position = 0;
235         if (!m_info->current)
236             return 0;
237     }
238     Element* e = m_info->current;
239     for (unsigned pos = m_info->position; e && pos < index; pos++)
240         e = itemAfter(e);
241     m_info->current = e;
242     m_info->position = index;
243     return m_info->current;
244}
245
246Node* HTMLCollection::firstItem() const
247{
248     return item(0);
249}
250
251Node* HTMLCollection::nextItem() const
252{
253     resetCollectionInfo();
254
255     // Look for the 'second' item. The first one is currentItem, already given back.
256     Element* retval = itemAfter(m_info->current);
257     m_info->current = retval;
258     m_info->position++;
259     return retval;
260}
261
262bool HTMLCollection::checkForNameMatch(Element* element, bool checkName, const AtomicString& name) const
263{
264    if (!element->isHTMLElement())
265        return false;
266
267    HTMLElement* e = toHTMLElement(element);
268    if (!checkName)
269        return e->getIdAttribute() == name;
270
271    // document.all returns only images, forms, applets, objects and embeds
272    // by name (though everything by id)
273    if (m_type == DocAll &&
274        !(e->hasLocalName(imgTag) || e->hasLocalName(formTag) ||
275          e->hasLocalName(appletTag) || e->hasLocalName(objectTag) ||
276          e->hasLocalName(embedTag) || e->hasLocalName(inputTag) ||
277          e->hasLocalName(selectTag)))
278        return false;
279
280    return e->getAttribute(nameAttr) == name && e->getIdAttribute() != name;
281}
282
283Node* HTMLCollection::namedItem(const AtomicString& name) const
284{
285    // http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/nameditem.asp
286    // This method first searches for an object with a matching id
287    // attribute. If a match is not found, the method then searches for an
288    // object with a matching name attribute, but only on those elements
289    // that are allowed a name attribute.
290    resetCollectionInfo();
291    m_idsDone = false;
292
293    for (Element* e = itemAfter(0); e; e = itemAfter(e)) {
294        if (checkForNameMatch(e, m_idsDone, name)) {
295            m_info->current = e;
296            return e;
297        }
298    }
299
300    m_idsDone = true;
301
302    for (Element* e = itemAfter(0); e; e = itemAfter(e)) {
303        if (checkForNameMatch(e, m_idsDone, name)) {
304            m_info->current = e;
305            return e;
306        }
307    }
308
309    m_info->current = 0;
310    return 0;
311}
312
313void HTMLCollection::updateNameCache() const
314{
315    if (m_info->hasNameCache)
316        return;
317
318    for (Element* element = itemAfter(0); element; element = itemAfter(element)) {
319        if (!element->isHTMLElement())
320            continue;
321        HTMLElement* e = toHTMLElement(element);
322        const AtomicString& idAttrVal = e->getIdAttribute();
323        const AtomicString& nameAttrVal = e->getAttribute(nameAttr);
324        if (!idAttrVal.isEmpty()) {
325            // add to id cache
326            Vector<Element*>* idVector = m_info->idCache.get(idAttrVal.impl());
327            if (!idVector) {
328                idVector = new Vector<Element*>;
329                m_info->idCache.add(idAttrVal.impl(), idVector);
330            }
331            idVector->append(e);
332        }
333        if (!nameAttrVal.isEmpty() && idAttrVal != nameAttrVal
334            && (m_type != DocAll ||
335                (e->hasLocalName(imgTag) || e->hasLocalName(formTag) ||
336                 e->hasLocalName(appletTag) || e->hasLocalName(objectTag) ||
337                 e->hasLocalName(embedTag) || e->hasLocalName(inputTag) ||
338                 e->hasLocalName(selectTag)))) {
339            // add to name cache
340            Vector<Element*>* nameVector = m_info->nameCache.get(nameAttrVal.impl());
341            if (!nameVector) {
342                nameVector = new Vector<Element*>;
343                m_info->nameCache.add(nameAttrVal.impl(), nameVector);
344            }
345            nameVector->append(e);
346        }
347    }
348
349    m_info->hasNameCache = true;
350}
351
352void HTMLCollection::namedItems(const AtomicString& name, Vector<RefPtr<Node> >& result) const
353{
354    ASSERT(result.isEmpty());
355
356    if (name.isEmpty())
357        return;
358
359    resetCollectionInfo();
360    updateNameCache();
361    m_info->checkConsistency();
362
363    Vector<Element*>* idResults = m_info->idCache.get(name.impl());
364    Vector<Element*>* nameResults = m_info->nameCache.get(name.impl());
365
366    for (unsigned i = 0; idResults && i < idResults->size(); ++i)
367        result.append(idResults->at(i));
368
369    for (unsigned i = 0; nameResults && i < nameResults->size(); ++i)
370        result.append(nameResults->at(i));
371}
372
373
374Node* HTMLCollection::nextNamedItem(const AtomicString& name) const
375{
376    resetCollectionInfo();
377    m_info->checkConsistency();
378
379    for (Element* e = itemAfter(m_info->current); e; e = itemAfter(e)) {
380        if (checkForNameMatch(e, m_idsDone, name)) {
381            m_info->current = e;
382            return e;
383        }
384    }
385
386    if (m_idsDone) {
387        m_info->current = 0;
388        return 0;
389    }
390    m_idsDone = true;
391
392    for (Element* e = itemAfter(m_info->current); e; e = itemAfter(e)) {
393        if (checkForNameMatch(e, m_idsDone, name)) {
394            m_info->current = e;
395            return e;
396        }
397    }
398
399    return 0;
400}
401
402PassRefPtr<NodeList> HTMLCollection::tags(const String& name)
403{
404    return m_base->getElementsByTagName(name);
405}
406
407} // namespace WebCore
408