mshtml: HTMLWindow_item code clean up.
[wine] / dlls / mshtml / htmlelemcol.c
1 /*
2  * Copyright 2006-2008 Jacek Caban for CodeWeavers
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include <stdarg.h>
20
21 #define COBJMACROS
22
23 #include "windef.h"
24 #include "winbase.h"
25 #include "winuser.h"
26 #include "ole2.h"
27
28 #include "wine/debug.h"
29
30 #include "mshtml_private.h"
31
32 WINE_DEFAULT_DEBUG_CHANNEL(mshtml);
33
34 typedef struct {
35     DispatchEx dispex;
36     IHTMLElementCollection IHTMLElementCollection_iface;
37
38     IUnknown *ref_unk;
39     HTMLElement **elems;
40     DWORD len;
41
42     LONG ref;
43 } HTMLElementCollection;
44
45 typedef struct {
46     HTMLElement **buf;
47     DWORD len;
48     DWORD size;
49 } elem_vector_t;
50
51 /* FIXME: Handle it better way */
52 static inline HTMLElement *elem_from_HTMLDOMNode(HTMLDOMNode *iface)
53 {
54     return CONTAINING_RECORD(iface, HTMLElement, node);
55 }
56
57 static IHTMLElementCollection *HTMLElementCollection_Create(IUnknown *ref_unk,
58                                                             HTMLElement **elems, DWORD len);
59
60 static void elem_vector_add(elem_vector_t *buf, HTMLElement *elem)
61 {
62     if(buf->len == buf->size) {
63         buf->size <<= 1;
64         buf->buf = heap_realloc(buf->buf, buf->size*sizeof(HTMLElement*));
65     }
66
67     buf->buf[buf->len++] = elem;
68 }
69
70 static void elem_vector_normalize(elem_vector_t *buf)
71 {
72     if(!buf->len) {
73         heap_free(buf->buf);
74         buf->buf = NULL;
75     }else if(buf->size > buf->len) {
76         buf->buf = heap_realloc(buf->buf, buf->len*sizeof(HTMLElement*));
77     }
78
79     buf->size = buf->len;
80 }
81
82 static inline BOOL is_elem_node(nsIDOMNode *node)
83 {
84     PRUint16 type=0;
85
86     nsIDOMNode_GetNodeType(node, &type);
87
88     return type == ELEMENT_NODE || type == COMMENT_NODE;
89 }
90
91 static inline HTMLElementCollection *impl_from_IHTMLElementCollection(IHTMLElementCollection *iface)
92 {
93     return CONTAINING_RECORD(iface, HTMLElementCollection, IHTMLElementCollection_iface);
94 }
95
96 static HRESULT WINAPI HTMLElementCollection_QueryInterface(IHTMLElementCollection *iface,
97                                                            REFIID riid, void **ppv)
98 {
99     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
100
101     *ppv = NULL;
102
103     if(IsEqualGUID(&IID_IUnknown, riid)) {
104         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
105         *ppv = &This->IHTMLElementCollection_iface;
106     }else if(IsEqualGUID(&IID_IHTMLElementCollection, riid)) {
107         TRACE("(%p)->(IID_IHTMLElementCollection %p)\n", This, ppv);
108         *ppv = &This->IHTMLElementCollection_iface;
109     }else if(dispex_query_interface(&This->dispex, riid, ppv)) {
110         return *ppv ? S_OK : E_NOINTERFACE;
111     }
112
113     if(*ppv) {
114         IHTMLElementCollection_AddRef(&This->IHTMLElementCollection_iface);
115         return S_OK;
116     }
117
118     FIXME("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
119     return E_NOINTERFACE;
120 }
121
122 static ULONG WINAPI HTMLElementCollection_AddRef(IHTMLElementCollection *iface)
123 {
124     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
125     LONG ref = InterlockedIncrement(&This->ref);
126
127     TRACE("(%p) ref=%d\n", This, ref);
128
129     return ref;
130 }
131
132 static ULONG WINAPI HTMLElementCollection_Release(IHTMLElementCollection *iface)
133 {
134     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
135     LONG ref = InterlockedDecrement(&This->ref);
136
137     TRACE("(%p) ref=%d\n", This, ref);
138
139     if(!ref) {
140         IUnknown_Release(This->ref_unk);
141         release_dispex(&This->dispex);
142         heap_free(This->elems);
143         heap_free(This);
144     }
145
146     return ref;
147 }
148
149 static HRESULT WINAPI HTMLElementCollection_GetTypeInfoCount(IHTMLElementCollection *iface,
150                                                              UINT *pctinfo)
151 {
152     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
153     return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
154 }
155
156 static HRESULT WINAPI HTMLElementCollection_GetTypeInfo(IHTMLElementCollection *iface,
157         UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo)
158 {
159     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
160     return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface, iTInfo, lcid, ppTInfo);
161 }
162
163 static HRESULT WINAPI HTMLElementCollection_GetIDsOfNames(IHTMLElementCollection *iface,
164         REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId)
165 {
166     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
167     return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface, riid, rgszNames, cNames,
168             lcid, rgDispId);
169 }
170
171 static HRESULT WINAPI HTMLElementCollection_Invoke(IHTMLElementCollection *iface,
172         DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
173         VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
174 {
175     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
176     return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface, dispIdMember, riid, lcid,
177             wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
178 }
179
180 static HRESULT WINAPI HTMLElementCollection_toString(IHTMLElementCollection *iface,
181                                                      BSTR *String)
182 {
183     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
184     FIXME("(%p)->(%p)\n", This, String);
185     return E_NOTIMPL;
186 }
187
188 static HRESULT WINAPI HTMLElementCollection_put_length(IHTMLElementCollection *iface,
189                                                        LONG v)
190 {
191     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
192     FIXME("(%p)->(%d)\n", This, v);
193     return E_NOTIMPL;
194 }
195
196 static HRESULT WINAPI HTMLElementCollection_get_length(IHTMLElementCollection *iface,
197                                                        LONG *p)
198 {
199     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
200
201     TRACE("(%p)->(%p)\n", This, p);
202
203     *p = This->len;
204     return S_OK;
205 }
206
207 static HRESULT WINAPI HTMLElementCollection_get__newEnum(IHTMLElementCollection *iface,
208                                                          IUnknown **p)
209 {
210     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
211     FIXME("(%p)->(%p)\n", This, p);
212     return E_NOTIMPL;
213 }
214
215 static BOOL is_elem_id(HTMLElement *elem, LPCWSTR name)
216 {
217     BSTR elem_id;
218     HRESULT hres;
219
220     hres = IHTMLElement_get_id(&elem->IHTMLElement_iface, &elem_id);
221     if(FAILED(hres)){
222         WARN("IHTMLElement_get_id failed: 0x%08x\n", hres);
223         return FALSE;
224     }
225
226     if(elem_id && !strcmpW(elem_id, name)) {
227         SysFreeString(elem_id);
228         return TRUE;
229     }
230
231     SysFreeString(elem_id);
232     return FALSE;
233 }
234
235 static BOOL is_elem_name(HTMLElement *elem, LPCWSTR name)
236 {
237     const PRUnichar *str;
238     nsAString nsstr, nsname;
239     BOOL ret = FALSE;
240     nsresult nsres;
241
242     static const PRUnichar nameW[] = {'n','a','m','e',0};
243
244     if(!elem->nselem)
245         return FALSE;
246
247     nsAString_Init(&nsstr, NULL);
248     nsIDOMHTMLElement_GetId(elem->nselem, &nsstr);
249     nsAString_GetData(&nsstr, &str);
250     if(!strcmpiW(str, name)) {
251         nsAString_Finish(&nsstr);
252         return TRUE;
253     }
254
255     nsAString_InitDepend(&nsname, nameW);
256     nsres =  nsIDOMHTMLElement_GetAttribute(elem->nselem, &nsname, &nsstr);
257     nsAString_Finish(&nsname);
258     if(NS_SUCCEEDED(nsres)) {
259         nsAString_GetData(&nsstr, &str);
260         ret = !strcmpiW(str, name);
261     }
262
263     nsAString_Finish(&nsstr);
264     return ret;
265 }
266
267 static HRESULT get_item_idx(HTMLElementCollection *This, UINT idx, IDispatch **ret)
268 {
269     if(idx < This->len) {
270         *ret = (IDispatch*)This->elems[idx];
271         IDispatch_AddRef(*ret);
272     }
273
274     return S_OK;
275 }
276
277 static HRESULT WINAPI HTMLElementCollection_item(IHTMLElementCollection *iface,
278         VARIANT name, VARIANT index, IDispatch **pdisp)
279 {
280     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
281     HRESULT hres = S_OK;
282
283     TRACE("(%p)->(%s %s %p)\n", This, debugstr_variant(&name), debugstr_variant(&index), pdisp);
284
285     *pdisp = NULL;
286
287     switch(V_VT(&name)) {
288     case VT_I4:
289         if(V_I4(&name) < 0)
290             return E_INVALIDARG;
291         hres = get_item_idx(This, V_I4(&name), pdisp);
292         break;
293
294     case VT_UINT:
295         hres = get_item_idx(This, V_UINT(&name), pdisp);
296         break;
297
298     case VT_BSTR: {
299         DWORD i;
300
301         if(V_VT(&index) == VT_I4) {
302             LONG idx = V_I4(&index);
303
304             if(idx < 0)
305                 return E_INVALIDARG;
306
307             for(i=0; i<This->len; i++) {
308                 if(is_elem_name(This->elems[i], V_BSTR(&name)) && !idx--)
309                     break;
310             }
311
312             if(i != This->len) {
313                 *pdisp = (IDispatch*)&This->elems[i]->IHTMLElement_iface;
314                 IDispatch_AddRef(*pdisp);
315             }
316         }else {
317             elem_vector_t buf = {NULL, 0, 8};
318
319             buf.buf = heap_alloc(buf.size*sizeof(HTMLElement*));
320
321             for(i=0; i<This->len; i++) {
322                 if(is_elem_name(This->elems[i], V_BSTR(&name)))
323                     elem_vector_add(&buf, This->elems[i]);
324             }
325
326             if(buf.len > 1) {
327                 elem_vector_normalize(&buf);
328                 *pdisp = (IDispatch*)HTMLElementCollection_Create(This->ref_unk, buf.buf, buf.len);
329             }else {
330                 if(buf.len == 1) {
331                     *pdisp = (IDispatch*)&buf.buf[0]->IHTMLElement_iface;
332                     IDispatch_AddRef(*pdisp);
333                 }
334
335                 heap_free(buf.buf);
336             }
337         }
338         break;
339     }
340
341     default:
342         FIXME("Unsupported name %s\n", debugstr_variant(&name));
343         hres = E_NOTIMPL;
344     }
345
346     if(SUCCEEDED(hres))
347         TRACE("returning %p\n", *pdisp);
348     return hres;
349 }
350
351 static HRESULT WINAPI HTMLElementCollection_tags(IHTMLElementCollection *iface,
352                                                  VARIANT tagName, IDispatch **pdisp)
353 {
354     HTMLElementCollection *This = impl_from_IHTMLElementCollection(iface);
355     DWORD i;
356     nsAString tag_str;
357     const PRUnichar *tag;
358     elem_vector_t buf = {NULL, 0, 8};
359
360     if(V_VT(&tagName) != VT_BSTR) {
361         WARN("Invalid arg\n");
362         return DISP_E_MEMBERNOTFOUND;
363     }
364
365     TRACE("(%p)->(%s %p)\n", This, debugstr_w(V_BSTR(&tagName)), pdisp);
366
367     buf.buf = heap_alloc(buf.size*sizeof(HTMLElement*));
368
369     nsAString_Init(&tag_str, NULL);
370
371     for(i=0; i<This->len; i++) {
372         if(!This->elems[i]->nselem)
373             continue;
374
375         nsIDOMElement_GetTagName(This->elems[i]->nselem, &tag_str);
376         nsAString_GetData(&tag_str, &tag);
377
378         if(CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, tag, -1,
379                           V_BSTR(&tagName), -1) == CSTR_EQUAL)
380             elem_vector_add(&buf, This->elems[i]);
381     }
382
383     nsAString_Finish(&tag_str);
384     elem_vector_normalize(&buf);
385
386     TRACE("fount %d tags\n", buf.len);
387
388     *pdisp = (IDispatch*)HTMLElementCollection_Create(This->ref_unk, buf.buf, buf.len);
389     return S_OK;
390 }
391
392 static const IHTMLElementCollectionVtbl HTMLElementCollectionVtbl = {
393     HTMLElementCollection_QueryInterface,
394     HTMLElementCollection_AddRef,
395     HTMLElementCollection_Release,
396     HTMLElementCollection_GetTypeInfoCount,
397     HTMLElementCollection_GetTypeInfo,
398     HTMLElementCollection_GetIDsOfNames,
399     HTMLElementCollection_Invoke,
400     HTMLElementCollection_toString,
401     HTMLElementCollection_put_length,
402     HTMLElementCollection_get_length,
403     HTMLElementCollection_get__newEnum,
404     HTMLElementCollection_item,
405     HTMLElementCollection_tags
406 };
407
408 static inline HTMLElementCollection *impl_from_DispatchEx(DispatchEx *iface)
409 {
410     return CONTAINING_RECORD(iface, HTMLElementCollection, dispex);
411 }
412
413 #define DISPID_ELEMCOL_0 MSHTML_DISPID_CUSTOM_MIN
414
415 static HRESULT HTMLElementCollection_get_dispid(DispatchEx *dispex, BSTR name, DWORD flags, DISPID *dispid)
416 {
417     HTMLElementCollection *This = impl_from_DispatchEx(dispex);
418     WCHAR *ptr;
419     DWORD idx=0;
420
421     if(!*name)
422         return DISP_E_UNKNOWNNAME;
423
424     for(ptr = name; *ptr && isdigitW(*ptr); ptr++)
425         idx = idx*10 + (*ptr-'0');
426
427     if(*ptr) {
428         /* the name contains alpha characters, so search by name & id */
429         for(idx = 0; idx < This->len; ++idx) {
430             if(is_elem_id(This->elems[idx], name) ||
431                     is_elem_name(This->elems[idx], name))
432                 break;
433         }
434     }
435
436     if(idx >= This->len)
437         return DISP_E_UNKNOWNNAME;
438
439     *dispid = DISPID_ELEMCOL_0 + idx;
440     TRACE("ret %x\n", *dispid);
441     return S_OK;
442 }
443
444 static HRESULT HTMLElementCollection_invoke(DispatchEx *dispex, DISPID id, LCID lcid, WORD flags, DISPPARAMS *params,
445         VARIANT *res, EXCEPINFO *ei, IServiceProvider *caller)
446 {
447     HTMLElementCollection *This = impl_from_DispatchEx(dispex);
448     DWORD idx;
449
450     TRACE("(%p)->(%x %x %x %p %p %p %p)\n", This, id, lcid, flags, params, res, ei, caller);
451
452     idx = id - DISPID_ELEMCOL_0;
453     if(idx >= This->len)
454         return DISP_E_UNKNOWNNAME;
455
456     switch(flags) {
457     case DISPATCH_PROPERTYGET:
458         V_VT(res) = VT_DISPATCH;
459         V_DISPATCH(res) = (IDispatch*)&This->elems[idx]->IHTMLElement_iface;
460         IHTMLElement_AddRef(&This->elems[idx]->IHTMLElement_iface);
461         break;
462     default:
463         FIXME("unimplemented flags %x\n", flags);
464         return E_NOTIMPL;
465     }
466
467     return S_OK;
468 }
469
470 static const dispex_static_data_vtbl_t HTMLElementColection_dispex_vtbl = {
471     NULL,
472     HTMLElementCollection_get_dispid,
473     HTMLElementCollection_invoke,
474     NULL
475 };
476
477 static const tid_t HTMLElementCollection_iface_tids[] = {
478     IHTMLElementCollection_tid,
479     0
480 };
481
482 static dispex_static_data_t HTMLElementCollection_dispex = {
483     &HTMLElementColection_dispex_vtbl,
484     DispHTMLElementCollection_tid,
485     NULL,
486     HTMLElementCollection_iface_tids
487 };
488
489 static void create_all_list(HTMLDocumentNode *doc, HTMLDOMNode *elem, elem_vector_t *buf)
490 {
491     nsIDOMNodeList *nsnode_list;
492     nsIDOMNode *iter;
493     PRUint32 list_len = 0, i;
494     nsresult nsres;
495     HRESULT hres;
496
497     nsres = nsIDOMNode_GetChildNodes(elem->nsnode, &nsnode_list);
498     if(NS_FAILED(nsres)) {
499         ERR("GetChildNodes failed: %08x\n", nsres);
500         return;
501     }
502
503     nsIDOMNodeList_GetLength(nsnode_list, &list_len);
504     if(!list_len)
505         return;
506
507     for(i=0; i<list_len; i++) {
508         nsres = nsIDOMNodeList_Item(nsnode_list, i, &iter);
509         if(NS_FAILED(nsres)) {
510             ERR("Item failed: %08x\n", nsres);
511             continue;
512         }
513
514         if(is_elem_node(iter)) {
515             HTMLDOMNode *node;
516
517             hres = get_node(doc, iter, TRUE, &node);
518             if(FAILED(hres)) {
519                 FIXME("get_node failed: %08x\n", hres);
520                 continue;
521             }
522
523             elem_vector_add(buf, elem_from_HTMLDOMNode(node));
524             create_all_list(doc, node, buf);
525         }
526     }
527 }
528
529 IHTMLElementCollection *create_all_collection(HTMLDOMNode *node, BOOL include_root)
530 {
531     elem_vector_t buf = {NULL, 0, 8};
532
533     buf.buf = heap_alloc(buf.size*sizeof(HTMLElement*));
534
535     if(include_root)
536         elem_vector_add(&buf, elem_from_HTMLDOMNode(node));
537     create_all_list(node->doc, node, &buf);
538     elem_vector_normalize(&buf);
539
540     return HTMLElementCollection_Create((IUnknown*)&node->IHTMLDOMNode_iface, buf.buf, buf.len);
541 }
542
543 IHTMLElementCollection *create_collection_from_nodelist(HTMLDocumentNode *doc, IUnknown *unk, nsIDOMNodeList *nslist)
544 {
545     PRUint32 length = 0, i;
546     HTMLDOMNode *node;
547     elem_vector_t buf;
548     HRESULT hres;
549
550     nsIDOMNodeList_GetLength(nslist, &length);
551
552     buf.len = 0;
553     buf.size = length;
554     if(length) {
555         nsIDOMNode *nsnode;
556
557         buf.buf = heap_alloc(buf.size*sizeof(HTMLElement*));
558
559         for(i=0; i<length; i++) {
560             nsIDOMNodeList_Item(nslist, i, &nsnode);
561             if(is_elem_node(nsnode)) {
562                 hres = get_node(doc, nsnode, TRUE, &node);
563                 if(FAILED(hres))
564                     continue;
565                 buf.buf[buf.len++] = elem_from_HTMLDOMNode(node);
566             }
567             nsIDOMNode_Release(nsnode);
568         }
569
570         elem_vector_normalize(&buf);
571     }else {
572         buf.buf = NULL;
573     }
574
575     return HTMLElementCollection_Create(unk, buf.buf, buf.len);
576 }
577
578 IHTMLElementCollection *create_collection_from_htmlcol(HTMLDocumentNode *doc, IUnknown *unk, nsIDOMHTMLCollection *nscol)
579 {
580     PRUint32 length = 0, i;
581     elem_vector_t buf;
582     HTMLDOMNode *node;
583     HRESULT hres = S_OK;
584
585     nsIDOMHTMLCollection_GetLength(nscol, &length);
586
587     buf.len = buf.size = length;
588     if(buf.len) {
589         nsIDOMNode *nsnode;
590
591         buf.buf = heap_alloc(buf.size*sizeof(HTMLElement*));
592
593         for(i=0; i<length; i++) {
594             nsIDOMHTMLCollection_Item(nscol, i, &nsnode);
595             hres = get_node(doc, nsnode, TRUE, &node);
596             nsIDOMNode_Release(nsnode);
597             if(FAILED(hres))
598                 break;
599             buf.buf[i] = elem_from_HTMLDOMNode(node);
600         }
601     }else {
602         buf.buf = NULL;
603     }
604
605     if(FAILED(hres)) {
606         heap_free(buf.buf);
607         return NULL;
608     }
609
610     return HTMLElementCollection_Create(unk, buf.buf, buf.len);
611 }
612
613 static IHTMLElementCollection *HTMLElementCollection_Create(IUnknown *ref_unk,
614             HTMLElement **elems, DWORD len)
615 {
616     HTMLElementCollection *ret = heap_alloc_zero(sizeof(HTMLElementCollection));
617
618     ret->IHTMLElementCollection_iface.lpVtbl = &HTMLElementCollectionVtbl;
619     ret->ref = 1;
620     ret->elems = elems;
621     ret->len = len;
622
623     init_dispex(&ret->dispex, (IUnknown*)&ret->IHTMLElementCollection_iface,
624             &HTMLElementCollection_dispex);
625
626     IUnknown_AddRef(ref_unk);
627     ret->ref_unk = ref_unk;
628
629     TRACE("ret=%p len=%d\n", ret, len);
630
631     return &ret->IHTMLElementCollection_iface;
632 }