mshtml: Improved focus handling.
[wine] / dlls / mshtml / nsembed.c
1 /*
2  * Copyright 2005-2007 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 "config.h"
20
21 #include <stdarg.h>
22
23 #define COBJMACROS
24
25 #include "windef.h"
26 #include "winbase.h"
27 #include "winuser.h"
28 #include "winreg.h"
29 #include "ole2.h"
30
31 #include "wine/debug.h"
32 #include "wine/unicode.h"
33
34 #include "mshtml_private.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(mshtml);
37 WINE_DECLARE_DEBUG_CHANNEL(gecko);
38
39 #define NS_APPSTARTUPNOTIFIER_CONTRACTID "@mozilla.org/embedcomp/appstartup-notifier;1"
40 #define NS_WEBBROWSER_CONTRACTID "@mozilla.org/embedding/browser/nsWebBrowser;1"
41 #define NS_MEMORY_CONTRACTID "@mozilla.org/xpcom/memory-service;1"
42 #define NS_COMMANDPARAMS_CONTRACTID "@mozilla.org/embedcomp/command-params;1"
43 #define NS_HTMLSERIALIZER_CONTRACTID "@mozilla.org/layout/contentserializer;1?mimetype=text/html"
44 #define NS_EDITORCONTROLLER_CONTRACTID "@mozilla.org/editor/editorcontroller;1"
45 #define NS_PREFERENCES_CONTRACTID "@mozilla.org/preferences;1"
46
47 #define APPSTARTUP_TOPIC "app-startup"
48
49 #define PR_UINT32_MAX 0xffffffff
50
51 struct nsCStringContainer {
52     void *v;
53     void *d1;
54     PRUint32 d2;
55     PRUint32 d3;
56 };
57
58 #define NS_STRING_CONTAINER_INIT_DEPEND  0x0002
59
60 static nsresult (*NS_InitXPCOM2)(nsIServiceManager**,void*,void*);
61 static nsresult (*NS_ShutdownXPCOM)(nsIServiceManager*);
62 static nsresult (*NS_GetComponentRegistrar)(nsIComponentRegistrar**);
63 static nsresult (*NS_StringContainerInit2)(nsStringContainer*,const PRUnichar*,PRUint32,PRUint32);
64 static nsresult (*NS_CStringContainerInit)(nsCStringContainer*);
65 static nsresult (*NS_StringContainerFinish)(nsStringContainer*);
66 static nsresult (*NS_CStringContainerFinish)(nsCStringContainer*);
67 static nsresult (*NS_StringSetData)(nsAString*,const PRUnichar*,PRUint32);
68 static nsresult (*NS_CStringSetData)(nsACString*,const char*,PRUint32);
69 static nsresult (*NS_NewLocalFile)(const nsAString*,PRBool,nsIFile**);
70 static PRUint32 (*NS_StringGetData)(const nsAString*,const PRUnichar **,PRBool*);
71 static PRUint32 (*NS_CStringGetData)(const nsACString*,const char**,PRBool*);
72
73 static HINSTANCE hXPCOM = NULL;
74
75 static nsIServiceManager *pServMgr = NULL;
76 static nsIComponentManager *pCompMgr = NULL;
77 static nsIMemory *nsmem = NULL;
78
79 static const WCHAR wszNsContainer[] = {'N','s','C','o','n','t','a','i','n','e','r',0};
80
81 static ATOM nscontainer_class;
82
83 static LRESULT WINAPI nsembed_proc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
84 {
85     NSContainer *This;
86     nsresult nsres;
87
88     static const WCHAR wszTHIS[] = {'T','H','I','S',0};
89
90     if(msg == WM_CREATE) {
91         This = *(NSContainer**)lParam;
92         SetPropW(hwnd, wszTHIS, This);
93     }else {
94         This = GetPropW(hwnd, wszTHIS);
95     }
96
97     switch(msg) {
98     case WM_SIZE:
99         TRACE("(%p)->(WM_SIZE)\n", This);
100
101         nsres = nsIBaseWindow_SetSize(This->window,
102                 LOWORD(lParam), HIWORD(lParam), TRUE);
103         if(NS_FAILED(nsres))
104             WARN("SetSize failed: %08x\n", nsres);
105         break;
106
107     case WM_PARENTNOTIFY:
108         TRACE("WM_PARENTNOTIFY %x\n", (unsigned)wParam);
109
110         switch(wParam) {
111         case WM_LBUTTONDOWN:
112         case WM_RBUTTONDOWN:
113             nsIWebBrowserFocus_Activate(This->focus);
114         }
115     }
116
117     return DefWindowProcW(hwnd, msg, wParam, lParam);
118 }
119
120
121 static void register_nscontainer_class(void)
122 {
123     static WNDCLASSEXW wndclass = {
124         sizeof(WNDCLASSEXW),
125         CS_DBLCLKS,
126         nsembed_proc,
127         0, 0, NULL, NULL, NULL, NULL, NULL,
128         wszNsContainer,
129         NULL,
130     };
131     wndclass.hInstance = hInst;
132     nscontainer_class = RegisterClassExW(&wndclass);
133 }
134
135 static void set_environment(LPCWSTR gre_path)
136 {
137     WCHAR path_env[MAX_PATH], buf[20];
138     int len, debug_level = 0;
139
140     static const WCHAR pathW[] = {'P','A','T','H',0};
141     static const WCHAR warnW[] = {'w','a','r','n',0};
142     static const WCHAR xpcom_debug_breakW[] =
143         {'X','P','C','O','M','_','D','E','B','U','G','_','B','R','E','A','K',0};
144     static const WCHAR nspr_log_modulesW[] =
145         {'N','S','P','R','_','L','O','G','_','M','O','D','U','L','E','S',0};
146     static const WCHAR debug_formatW[] = {'a','l','l',':','%','d',0};
147
148     /* We have to modify PATH as XPCOM loads other DLLs from this directory. */
149     GetEnvironmentVariableW(pathW, path_env, sizeof(path_env)/sizeof(WCHAR));
150     len = strlenW(path_env);
151     path_env[len++] = ';';
152     strcpyW(path_env+len, gre_path);
153     SetEnvironmentVariableW(pathW, path_env);
154
155     SetEnvironmentVariableW(xpcom_debug_breakW, warnW);
156
157     if(TRACE_ON(gecko))
158         debug_level = 5;
159     else if(WARN_ON(gecko))
160         debug_level = 3;
161     else if(ERR_ON(gecko))
162         debug_level = 2;
163
164     sprintfW(buf, debug_formatW, debug_level);
165     SetEnvironmentVariableW(nspr_log_modulesW, buf);
166 }
167
168 static BOOL load_xpcom(const PRUnichar *gre_path)
169 {
170     static const WCHAR strXPCOM[] = {'x','p','c','o','m','.','d','l','l',0};
171
172     TRACE("(%s)\n", debugstr_w(gre_path));
173
174     set_environment(gre_path);
175
176     hXPCOM = LoadLibraryW(strXPCOM);
177     if(!hXPCOM) {
178         WARN("Could not load XPCOM: %d\n", GetLastError());
179         return FALSE;
180     }
181
182 #define NS_DLSYM(func) \
183     func = (void *)GetProcAddress(hXPCOM, #func); \
184     if(!func) \
185         ERR("Could not GetProcAddress(" #func ") failed\n")
186
187     NS_DLSYM(NS_InitXPCOM2);
188     NS_DLSYM(NS_ShutdownXPCOM);
189     NS_DLSYM(NS_GetComponentRegistrar);
190     NS_DLSYM(NS_StringContainerInit2);
191     NS_DLSYM(NS_CStringContainerInit);
192     NS_DLSYM(NS_StringContainerFinish);
193     NS_DLSYM(NS_CStringContainerFinish);
194     NS_DLSYM(NS_StringSetData);
195     NS_DLSYM(NS_CStringSetData);
196     NS_DLSYM(NS_NewLocalFile);
197     NS_DLSYM(NS_StringGetData);
198     NS_DLSYM(NS_CStringGetData);
199
200 #undef NS_DLSYM
201
202     return TRUE;
203 }
204
205 static BOOL check_version(LPCWSTR gre_path, const char *version_string)
206 {
207     WCHAR file_name[MAX_PATH];
208     char version[128];
209     DWORD read=0;
210     HANDLE hfile;
211
212     static const WCHAR wszVersion[] = {'\\','V','E','R','S','I','O','N',0};
213
214     strcpyW(file_name, gre_path);
215     strcatW(file_name, wszVersion);
216
217     hfile = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ, NULL,
218                         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
219     if(hfile == INVALID_HANDLE_VALUE) {
220         ERR("Could not open VERSION file\n");
221         return FALSE;
222     }
223
224     ReadFile(hfile, version, sizeof(version), &read, NULL);
225     version[read] = 0;
226     CloseHandle(hfile);
227
228     TRACE("%s\n", debugstr_a(version));
229
230     if(strcmp(version, version_string)) {
231         ERR("Unexpected version %s, expected %s\n", debugstr_a(version),
232             debugstr_a(version_string));
233         return FALSE;
234     }
235
236     return TRUE;
237 }
238
239 static BOOL load_wine_gecko_v(PRUnichar *gre_path, HKEY mshtml_key,
240         const char *version, const char *version_string)
241 {
242     DWORD res, type, size = MAX_PATH;
243     HKEY hkey = mshtml_key;
244
245     static const WCHAR wszGeckoPath[] =
246         {'G','e','c','k','o','P','a','t','h',0};
247
248     if(version) {
249         /* @@ Wine registry key: HKCU\Software\Wine\MSHTML\<version> */
250         res = RegOpenKeyA(mshtml_key, version, &hkey);
251         if(res != ERROR_SUCCESS)
252             return FALSE;
253     }
254
255     res = RegQueryValueExW(hkey, wszGeckoPath, NULL, &type, (LPBYTE)gre_path, &size);
256     if(hkey != mshtml_key)
257         RegCloseKey(hkey);
258     if(res != ERROR_SUCCESS || type != REG_SZ)
259         return FALSE;
260
261     if(!check_version(gre_path, version_string))
262         return FALSE;
263
264     return load_xpcom(gre_path);
265 }
266
267 static BOOL load_wine_gecko(PRUnichar *gre_path)
268 {
269     HKEY hkey;
270     DWORD res;
271     BOOL ret;
272
273     static const WCHAR wszMshtmlKey[] = {
274         'S','o','f','t','w','a','r','e','\\','W','i','n','e',
275         '\\','M','S','H','T','M','L',0};
276
277     /* @@ Wine registry key: HKCU\Software\Wine\MSHTML */
278     res = RegOpenKeyW(HKEY_CURRENT_USER, wszMshtmlKey, &hkey);
279     if(res != ERROR_SUCCESS)
280         return FALSE;
281
282     ret = load_wine_gecko_v(gre_path, hkey, GECKO_VERSION, GECKO_VERSION_STRING);
283
284     RegCloseKey(hkey);
285     return ret;
286 }
287
288 static void set_bool_pref(nsIPrefBranch *pref, const char *pref_name, BOOL val)
289 {
290     nsresult nsres;
291
292     nsres = nsIPrefBranch_SetBoolPref(pref, pref_name, val);
293     if(NS_FAILED(nsres))
294         ERR("Could not set pref %s\n", debugstr_a(pref_name));
295 }
296
297 static void set_int_pref(nsIPrefBranch *pref, const char *pref_name, int val)
298 {
299     nsresult nsres;
300
301     nsres = nsIPrefBranch_SetIntPref(pref, pref_name, val);
302     if(NS_FAILED(nsres))
303         ERR("Could not set pref %s\n", debugstr_a(pref_name));
304 }
305
306 static void set_string_pref(nsIPrefBranch *pref, const char *pref_name, const char *val)
307 {
308     nsresult nsres;
309
310     nsres = nsIPrefBranch_SetCharPref(pref, pref_name, val);
311     if(NS_FAILED(nsres))
312         ERR("Could not set pref %s\n", debugstr_a(pref_name));
313 }
314
315 static void set_lang(nsIPrefBranch *pref)
316 {
317     char langs[100];
318     DWORD res, size, type;
319     HKEY hkey;
320
321     static const WCHAR international_keyW[] =
322         {'S','o','f','t','w','a','r','e',
323          '\\','M','i','c','r','o','s','o','f','t',
324          '\\','I','n','t','e','r','n','e','t',' ','E','x','p','l','o','r','e','r',
325          '\\','I','n','t','e','r','n','a','t','i','o','n','a','l',0};
326
327     res = RegOpenKeyW(HKEY_CURRENT_USER, international_keyW, &hkey);
328     if(res != ERROR_SUCCESS)
329         return;
330
331     size = sizeof(langs);
332     res = RegQueryValueExA(hkey, "AcceptLanguage", 0, &type, (LPBYTE)langs, &size);
333     RegCloseKey(hkey);
334     if(res != ERROR_SUCCESS || type != REG_SZ)
335         return;
336
337     TRACE("Setting lang %s\n", debugstr_a(langs));
338
339     set_string_pref(pref, "intl.accept_languages", langs);
340 }
341
342 static void set_proxy(nsIPrefBranch *pref)
343 {
344     char proxy[512];
345     char * proxy_port;
346     int proxy_port_num;
347     DWORD enabled = 0, res, size, type;
348     HKEY hkey;
349
350     static const WCHAR proxy_keyW[] =
351         {'S','o','f','t','w','a','r','e',
352          '\\','M','i','c','r','o','s','o','f','t',
353          '\\','W','i','n','d','o','w','s',
354          '\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n',
355          '\\','I','n','t','e','r','n','e','t',' ','S','e','t','t','i','n','g','s',0};
356
357     res = RegOpenKeyW(HKEY_CURRENT_USER, proxy_keyW, &hkey);
358     if(res != ERROR_SUCCESS)
359         return;
360
361     size = sizeof(enabled);
362     res = RegQueryValueExA(hkey, "ProxyEnable", 0, &type, (LPBYTE)&enabled, &size);
363     if(res != ERROR_SUCCESS || type != REG_DWORD || enabled == 0)
364     {
365         RegCloseKey(hkey);
366         return;
367     }
368
369     size = sizeof(proxy);
370     res = RegQueryValueExA(hkey, "ProxyServer", 0, &type, (LPBYTE)proxy, &size);
371     RegCloseKey(hkey);
372     if(res != ERROR_SUCCESS || type != REG_SZ)
373         return;
374
375     proxy_port = strchr(proxy, ':');
376     if (!proxy_port)
377         return;
378
379     *proxy_port = 0;
380     proxy_port_num = atoi(proxy_port + 1);
381     TRACE("Setting proxy to %s, port %d\n", debugstr_a(proxy), proxy_port_num);
382
383     set_string_pref(pref, "network.proxy.http", proxy);
384     set_string_pref(pref, "network.proxy.ssl", proxy);
385
386     set_int_pref(pref, "network.proxy.type", 1);
387     set_int_pref(pref, "network.proxy.http_port", proxy_port_num);
388     set_int_pref(pref, "network.proxy.ssl_port", proxy_port_num);
389 }
390
391 static void set_preferences(void)
392 {
393     nsIPrefBranch *pref;
394     nsresult nsres;
395
396     nsres = nsIServiceManager_GetServiceByContractID(pServMgr, NS_PREFERENCES_CONTRACTID,
397             &IID_nsIPrefBranch, (void**)&pref);
398     if(NS_FAILED(nsres)) {
399         ERR("Could not get preference service: %08x\n", nsres);
400         return;
401     }
402
403     set_lang(pref);
404     set_proxy(pref);
405     set_bool_pref(pref, "security.warn_entering_secure", FALSE);
406     set_bool_pref(pref, "security.warn_submit_insecure", FALSE);
407     set_int_pref(pref, "layout.spellcheckDefault", 0);
408
409     nsIPrefBranch_Release(pref);
410 }
411
412 static BOOL init_xpcom(const PRUnichar *gre_path)
413 {
414     nsresult nsres;
415     nsIObserver *pStartNotif;
416     nsIComponentRegistrar *registrar = NULL;
417     nsAString path;
418     nsIFile *gre_dir;
419
420     nsAString_InitDepend(&path, gre_path);
421     nsres = NS_NewLocalFile(&path, FALSE, &gre_dir);
422     nsAString_Finish(&path);
423     if(NS_FAILED(nsres)) {
424         ERR("NS_NewLocalFile failed: %08x\n", nsres);
425         FreeLibrary(hXPCOM);
426         return FALSE;
427     }
428
429     nsres = NS_InitXPCOM2(&pServMgr, gre_dir, NULL);
430     if(NS_FAILED(nsres)) {
431         ERR("NS_InitXPCOM2 failed: %08x\n", nsres);
432         FreeLibrary(hXPCOM);
433         return FALSE;
434     }
435
436     nsres = nsIServiceManager_QueryInterface(pServMgr, &IID_nsIComponentManager, (void**)&pCompMgr);
437     if(NS_FAILED(nsres))
438         ERR("Could not get nsIComponentManager: %08x\n", nsres);
439
440     nsres = NS_GetComponentRegistrar(&registrar);
441     if(NS_SUCCEEDED(nsres)) {
442         nsres = nsIComponentRegistrar_AutoRegister(registrar, NULL);
443         if(NS_FAILED(nsres))
444             ERR("AutoRegister(NULL) failed: %08x\n", nsres);
445
446         init_nsio(pCompMgr, registrar);
447     }else {
448         ERR("NS_GetComponentRegistrar failed: %08x\n", nsres);
449     }
450
451     nsres = nsIComponentManager_CreateInstanceByContractID(pCompMgr, NS_APPSTARTUPNOTIFIER_CONTRACTID,
452             NULL, &IID_nsIObserver, (void**)&pStartNotif);
453     if(NS_SUCCEEDED(nsres)) {
454         nsres = nsIObserver_Observe(pStartNotif, NULL, APPSTARTUP_TOPIC, NULL);
455         if(NS_FAILED(nsres))
456             ERR("Observe failed: %08x\n", nsres);
457
458         nsIObserver_Release(pStartNotif);
459     }else {
460         ERR("could not get appstartup-notifier: %08x\n", nsres);
461     }
462
463     set_preferences();
464
465     nsres = nsIComponentManager_CreateInstanceByContractID(pCompMgr, NS_MEMORY_CONTRACTID,
466             NULL, &IID_nsIMemory, (void**)&nsmem);
467     if(NS_FAILED(nsres))
468         ERR("Could not get nsIMemory: %08x\n", nsres);
469
470     if(registrar) {
471         register_nsservice(registrar, pServMgr);
472         nsIComponentRegistrar_Release(registrar);
473     }
474
475     return TRUE;
476 }
477
478 static CRITICAL_SECTION cs_load_gecko;
479 static CRITICAL_SECTION_DEBUG cs_load_gecko_dbg =
480 {
481     0, 0, &cs_load_gecko,
482     { &cs_load_gecko_dbg.ProcessLocksList, &cs_load_gecko_dbg.ProcessLocksList },
483       0, 0, { (DWORD_PTR)(__FILE__ ": load_gecko") }
484 };
485 static CRITICAL_SECTION cs_load_gecko = { &cs_load_gecko_dbg, -1, 0, 0, 0, 0 };
486
487 BOOL load_gecko(BOOL silent)
488 {
489     PRUnichar gre_path[MAX_PATH];
490     BOOL ret = FALSE;
491
492     static DWORD loading_thread;
493
494     TRACE("()\n");
495
496     /* load_gecko may be called recursively */
497     if(loading_thread == GetCurrentThreadId())
498         return pCompMgr != NULL;
499
500     EnterCriticalSection(&cs_load_gecko);
501
502     if(!loading_thread) {
503         loading_thread = GetCurrentThreadId();
504
505         if(load_wine_gecko(gre_path)
506            || (install_wine_gecko(silent) && load_wine_gecko(gre_path)))
507             ret = init_xpcom(gre_path);
508         else
509            MESSAGE("Could not load wine-gecko. HTML rendering will be disabled.\n");
510     }else {
511         ret = pCompMgr != NULL;
512     }
513
514     LeaveCriticalSection(&cs_load_gecko);
515
516     return ret;
517 }
518
519 void *nsalloc(size_t size)
520 {
521     return nsIMemory_Alloc(nsmem, size);
522 }
523
524 void nsfree(void *mem)
525 {
526     nsIMemory_Free(nsmem, mem);
527 }
528
529 static void nsACString_Init(nsACString *str, const char *data)
530 {
531     NS_CStringContainerInit(str);
532     if(data)
533         nsACString_SetData(str, data);
534 }
535
536 void nsACString_SetData(nsACString *str, const char *data)
537 {
538     NS_CStringSetData(str, data, PR_UINT32_MAX);
539 }
540
541 PRUint32 nsACString_GetData(const nsACString *str, const char **data)
542 {
543     return NS_CStringGetData(str, data, NULL);
544 }
545
546 static void nsACString_Finish(nsACString *str)
547 {
548     NS_CStringContainerFinish(str);
549 }
550
551 BOOL nsAString_Init(nsAString *str, const PRUnichar *data)
552 {
553     return NS_SUCCEEDED(NS_StringContainerInit2(str, data, PR_UINT32_MAX, 0));
554 }
555
556 /*
557  * Initializes nsAString with data owned by caller.
558  * Caller must ensure that data is valid during lifetime of string object.
559  */
560 void nsAString_InitDepend(nsAString *str, const PRUnichar *data)
561 {
562     NS_StringContainerInit2(str, data, PR_UINT32_MAX, NS_STRING_CONTAINER_INIT_DEPEND);
563 }
564
565 void nsAString_SetData(nsAString *str, const PRUnichar *data)
566 {
567     NS_StringSetData(str, data, PR_UINT32_MAX);
568 }
569
570 PRUint32 nsAString_GetData(const nsAString *str, const PRUnichar **data)
571 {
572     return NS_StringGetData(str, data, NULL);
573 }
574
575 void nsAString_Finish(nsAString *str)
576 {
577     NS_StringContainerFinish(str);
578 }
579
580 nsICommandParams *create_nscommand_params(void)
581 {
582     nsICommandParams *ret = NULL;
583     nsresult nsres;
584
585     if(!pCompMgr)
586         return NULL;
587
588     nsres = nsIComponentManager_CreateInstanceByContractID(pCompMgr,
589             NS_COMMANDPARAMS_CONTRACTID, NULL, &IID_nsICommandParams,
590             (void**)&ret);
591     if(NS_FAILED(nsres))
592         ERR("Could not get nsICommandParams\n");
593
594     return ret;
595 }
596
597 nsresult get_nsinterface(nsISupports *iface, REFIID riid, void **ppv)
598 {
599     nsIInterfaceRequestor *iface_req;
600     nsresult nsres;
601
602     nsres = nsISupports_QueryInterface(iface, &IID_nsIInterfaceRequestor, (void**)&iface_req);
603     if(NS_FAILED(nsres))
604         return nsres;
605
606     nsres = nsIInterfaceRequestor_GetInterface(iface_req, riid, ppv);
607     nsIInterfaceRequestor_Release(iface_req);
608
609     return nsres;
610 }
611
612 static HRESULT nsnode_to_nsstring_rec(nsIContentSerializer *serializer, nsIDOMNode *nsnode, nsAString *str)
613 {
614     nsIDOMNodeList *node_list = NULL;
615     PRBool has_children = FALSE;
616     PRUint16 type;
617     nsresult nsres;
618
619     nsIDOMNode_HasChildNodes(nsnode, &has_children);
620
621     nsres = nsIDOMNode_GetNodeType(nsnode, &type);
622     if(NS_FAILED(nsres)) {
623         ERR("GetType failed: %08x\n", nsres);
624         return E_FAIL;
625     }
626
627     switch(type) {
628     case ELEMENT_NODE: {
629         nsIDOMElement *nselem;
630         nsIDOMNode_QueryInterface(nsnode, &IID_nsIDOMElement, (void**)&nselem);
631         nsIContentSerializer_AppendElementStart(serializer, nselem, nselem, str);
632         nsIDOMElement_Release(nselem);
633         break;
634     }
635     case TEXT_NODE: {
636         nsIDOMText *nstext;
637         nsIDOMNode_QueryInterface(nsnode, &IID_nsIDOMText, (void**)&nstext);
638         nsIContentSerializer_AppendText(serializer, nstext, 0, -1, str);
639         nsIDOMText_Release(nstext);
640         break;
641     }
642     case COMMENT_NODE: {
643         nsIDOMComment *nscomment;
644         nsres = nsIDOMNode_QueryInterface(nsnode, &IID_nsIDOMComment, (void**)&nscomment);
645         nsres = nsIContentSerializer_AppendComment(serializer, nscomment, 0, -1, str);
646         break;
647     }
648     case DOCUMENT_NODE: {
649         nsIDOMDocument *nsdoc;
650         nsIDOMNode_QueryInterface(nsnode, &IID_nsIDOMDocument, (void**)&nsdoc);
651         nsIContentSerializer_AppendDocumentStart(serializer, nsdoc, str);
652         nsIDOMDocument_Release(nsdoc);
653         break;
654     }
655     case DOCUMENT_TYPE_NODE:
656         WARN("Ignoring DOCUMENT_TYPE_NODE\n");
657         break;
658     case DOCUMENT_FRAGMENT_NODE:
659         break;
660     default:
661         FIXME("Unhandled type %u\n", type);
662     }
663
664     if(has_children) {
665         PRUint32 child_cnt, i;
666         nsIDOMNode *child_node;
667
668         nsIDOMNode_GetChildNodes(nsnode, &node_list);
669         nsIDOMNodeList_GetLength(node_list, &child_cnt);
670
671         for(i=0; i<child_cnt; i++) {
672             nsres = nsIDOMNodeList_Item(node_list, i, &child_node);
673             if(NS_SUCCEEDED(nsres)) {
674                 nsnode_to_nsstring_rec(serializer, child_node, str);
675                 nsIDOMNode_Release(child_node);
676             }else {
677                 ERR("Item failed: %08x\n", nsres);
678             }
679         }
680
681         nsIDOMNodeList_Release(node_list);
682     }
683
684     if(type == ELEMENT_NODE) {
685         nsIDOMElement *nselem;
686         nsIDOMNode_QueryInterface(nsnode, &IID_nsIDOMElement, (void**)&nselem);
687         nsIContentSerializer_AppendElementEnd(serializer, nselem, str);
688         nsIDOMElement_Release(nselem);
689     }
690
691     return S_OK;
692 }
693
694 HRESULT nsnode_to_nsstring(nsIDOMNode *nsnode, nsAString *str)
695 {
696     nsIContentSerializer *serializer;
697     nsresult nsres;
698     HRESULT hres;
699
700     nsres = nsIComponentManager_CreateInstanceByContractID(pCompMgr,
701             NS_HTMLSERIALIZER_CONTRACTID, NULL, &IID_nsIContentSerializer,
702             (void**)&serializer);
703     if(NS_FAILED(nsres)) {
704         ERR("Could not get nsIContentSerializer: %08x\n", nsres);
705         return E_FAIL;
706     }
707
708     nsres = nsIContentSerializer_Init(serializer, 0, 100, NULL, FALSE, FALSE /* FIXME */);
709     if(NS_FAILED(nsres))
710         ERR("Init failed: %08x\n", nsres);
711
712     hres = nsnode_to_nsstring_rec(serializer, nsnode, str);
713     if(SUCCEEDED(hres)) {
714         nsres = nsIContentSerializer_Flush(serializer, str);
715         if(NS_FAILED(nsres))
716             ERR("Flush failed: %08x\n", nsres);
717     }
718
719     nsIContentSerializer_Release(serializer);
720     return hres;
721 }
722
723 void get_editor_controller(NSContainer *This)
724 {
725     nsIEditingSession *editing_session = NULL;
726     nsIControllerContext *ctrlctx;
727     nsresult nsres;
728
729     if(This->editor) {
730         nsIEditor_Release(This->editor);
731         This->editor = NULL;
732     }
733
734     if(This->editor_controller) {
735         nsIController_Release(This->editor_controller);
736         This->editor_controller = NULL;
737     }
738
739     nsres = get_nsinterface((nsISupports*)This->webbrowser, &IID_nsIEditingSession,
740             (void**)&editing_session);
741     if(NS_FAILED(nsres)) {
742         ERR("Could not get nsIEditingSession: %08x\n", nsres);
743         return;
744     }
745
746     nsres = nsIEditingSession_GetEditorForWindow(editing_session,
747             This->doc->basedoc.window->nswindow, &This->editor);
748     nsIEditingSession_Release(editing_session);
749     if(NS_FAILED(nsres)) {
750         ERR("Could not get editor: %08x\n", nsres);
751         return;
752     }
753
754     nsres = nsIComponentManager_CreateInstanceByContractID(pCompMgr,
755             NS_EDITORCONTROLLER_CONTRACTID, NULL, &IID_nsIControllerContext, (void**)&ctrlctx);
756     if(NS_SUCCEEDED(nsres)) {
757         nsres = nsIControllerContext_SetCommandContext(ctrlctx, (nsISupports *)This->editor);
758         if(NS_FAILED(nsres))
759             ERR("SetCommandContext failed: %08x\n", nsres);
760         nsres = nsIControllerContext_QueryInterface(ctrlctx, &IID_nsIController,
761                 (void**)&This->editor_controller);
762         nsIControllerContext_Release(ctrlctx);
763         if(NS_FAILED(nsres))
764             ERR("Could not get nsIController interface: %08x\n", nsres);
765     }else {
766         ERR("Could not create edit controller: %08x\n", nsres);
767     }
768 }
769
770 void set_ns_editmode(NSContainer *This)
771 {
772     nsIEditingSession *editing_session = NULL;
773     nsIURIContentListener *listener = NULL;
774     nsIDOMWindow *dom_window = NULL;
775     nsresult nsres;
776
777     nsres = get_nsinterface((nsISupports*)This->webbrowser, &IID_nsIEditingSession,
778             (void**)&editing_session);
779     if(NS_FAILED(nsres)) {
780         ERR("Could not get nsIEditingSession: %08x\n", nsres);
781         return;
782     }
783
784     nsres = nsIWebBrowser_GetContentDOMWindow(This->webbrowser, &dom_window);
785     if(NS_FAILED(nsres)) {
786         ERR("Could not get content DOM window: %08x\n", nsres);
787         nsIEditingSession_Release(editing_session);
788         return;
789     }
790
791     nsres = nsIEditingSession_MakeWindowEditable(editing_session, dom_window,
792             NULL, FALSE, TRUE, TRUE);
793     nsIEditingSession_Release(editing_session);
794     nsIDOMWindow_Release(dom_window);
795     if(NS_FAILED(nsres)) {
796         ERR("MakeWindowEditable failed: %08x\n", nsres);
797         return;
798     }
799
800     /* MakeWindowEditable changes WebBrowser's parent URI content listener.
801      * It seams to be a bug in Gecko. To workaround it we set our content
802      * listener again and Gecko's one as its parent.
803      */
804     nsIWebBrowser_GetParentURIContentListener(This->webbrowser, &listener);
805     nsIURIContentListener_SetParentContentListener(NSURICL(This), listener);
806     nsIURIContentListener_Release(listener);
807     nsIWebBrowser_SetParentURIContentListener(This->webbrowser, NSURICL(This));
808 }
809
810 void close_gecko(void)
811 {
812     TRACE("()\n");
813
814     release_nsio();
815
816     if(pCompMgr)
817         nsIComponentManager_Release(pCompMgr);
818
819     if(pServMgr)
820         nsIServiceManager_Release(pServMgr);
821
822     if(nsmem)
823         nsIMemory_Release(nsmem);
824
825     /* Gecko doesn't really support being unloaded */
826     /* if (hXPCOM) FreeLibrary(hXPCOM); */
827 }
828
829 /**********************************************************
830  *      nsIWebBrowserChrome interface
831  */
832
833 #define NSWBCHROME_THIS(iface) DEFINE_THIS(NSContainer, WebBrowserChrome, iface)
834
835 static nsresult NSAPI nsWebBrowserChrome_QueryInterface(nsIWebBrowserChrome *iface,
836         nsIIDRef riid, nsQIResult result)
837 {
838     NSContainer *This = NSWBCHROME_THIS(iface);
839
840     *result = NULL;
841     if(IsEqualGUID(&IID_nsISupports, riid)) {
842         TRACE("(%p)->(IID_nsISupports, %p)\n", This, result);
843         *result = NSWBCHROME(This);
844     }else if(IsEqualGUID(&IID_nsIWebBrowserChrome, riid)) {
845         TRACE("(%p)->(IID_nsIWebBrowserChrome, %p)\n", This, result);
846         *result = NSWBCHROME(This);
847     }else if(IsEqualGUID(&IID_nsIContextMenuListener, riid)) {
848         TRACE("(%p)->(IID_nsIContextMenuListener, %p)\n", This, result);
849         *result = NSCML(This);
850     }else if(IsEqualGUID(&IID_nsIURIContentListener, riid)) {
851         TRACE("(%p)->(IID_nsIURIContentListener %p)\n", This, result);
852         *result = NSURICL(This);
853     }else if(IsEqualGUID(&IID_nsIEmbeddingSiteWindow, riid)) {
854         TRACE("(%p)->(IID_nsIEmbeddingSiteWindow %p)\n", This, result);
855         *result = NSEMBWNDS(This);
856     }else if(IsEqualGUID(&IID_nsITooltipListener, riid)) {
857         TRACE("(%p)->(IID_nsITooltipListener %p)\n", This, result);
858         *result = NSTOOLTIP(This);
859     }else if(IsEqualGUID(&IID_nsIInterfaceRequestor, riid)) {
860         TRACE("(%p)->(IID_nsIInterfaceRequestor %p)\n", This, result);
861         *result = NSIFACEREQ(This);
862     }else if(IsEqualGUID(&IID_nsIWeakReference, riid)) {
863         TRACE("(%p)->(IID_nsIWeakReference %p)\n", This, result);
864         *result = NSWEAKREF(This);
865     }else if(IsEqualGUID(&IID_nsISupportsWeakReference, riid)) {
866         TRACE("(%p)->(IID_nsISupportsWeakReference %p)\n", This, result);
867         *result = NSSUPWEAKREF(This);
868     }
869
870     if(*result) {
871         nsIWebBrowserChrome_AddRef(NSWBCHROME(This));
872         return NS_OK;
873     }
874
875     TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), result);
876     return NS_NOINTERFACE;
877 }
878
879 static nsrefcnt NSAPI nsWebBrowserChrome_AddRef(nsIWebBrowserChrome *iface)
880 {
881     NSContainer *This = NSWBCHROME_THIS(iface);
882     LONG ref = InterlockedIncrement(&This->ref);
883
884     TRACE("(%p) ref=%d\n", This, ref);
885
886     return ref;
887 }
888
889 static nsrefcnt NSAPI nsWebBrowserChrome_Release(nsIWebBrowserChrome *iface)
890 {
891     NSContainer *This = NSWBCHROME_THIS(iface);
892     LONG ref = InterlockedDecrement(&This->ref);
893
894     TRACE("(%p) ref=%d\n", This, ref);
895
896     if(!ref) {
897         if(This->parent)
898             nsIWebBrowserChrome_Release(NSWBCHROME(This->parent));
899         heap_free(This);
900     }
901
902     return ref;
903 }
904
905 static nsresult NSAPI nsWebBrowserChrome_SetStatus(nsIWebBrowserChrome *iface,
906         PRUint32 statusType, const PRUnichar *status)
907 {
908     NSContainer *This = NSWBCHROME_THIS(iface);
909     TRACE("(%p)->(%d %s)\n", This, statusType, debugstr_w(status));
910     return NS_OK;
911 }
912
913 static nsresult NSAPI nsWebBrowserChrome_GetWebBrowser(nsIWebBrowserChrome *iface,
914         nsIWebBrowser **aWebBrowser)
915 {
916     NSContainer *This = NSWBCHROME_THIS(iface);
917
918     TRACE("(%p)->(%p)\n", This, aWebBrowser);
919
920     if(!aWebBrowser)
921         return NS_ERROR_INVALID_ARG;
922
923     if(This->webbrowser)
924         nsIWebBrowser_AddRef(This->webbrowser);
925     *aWebBrowser = This->webbrowser;
926     return S_OK;
927 }
928
929 static nsresult NSAPI nsWebBrowserChrome_SetWebBrowser(nsIWebBrowserChrome *iface,
930         nsIWebBrowser *aWebBrowser)
931 {
932     NSContainer *This = NSWBCHROME_THIS(iface);
933
934     TRACE("(%p)->(%p)\n", This, aWebBrowser);
935
936     if(aWebBrowser != This->webbrowser)
937         ERR("Wrong nsWebBrowser!\n");
938
939     return NS_OK;
940 }
941
942 static nsresult NSAPI nsWebBrowserChrome_GetChromeFlags(nsIWebBrowserChrome *iface,
943         PRUint32 *aChromeFlags)
944 {
945     NSContainer *This = NSWBCHROME_THIS(iface);
946     WARN("(%p)->(%p)\n", This, aChromeFlags);
947     return NS_ERROR_NOT_IMPLEMENTED;
948 }
949
950 static nsresult NSAPI nsWebBrowserChrome_SetChromeFlags(nsIWebBrowserChrome *iface,
951         PRUint32 aChromeFlags)
952 {
953     NSContainer *This = NSWBCHROME_THIS(iface);
954     WARN("(%p)->(%08x)\n", This, aChromeFlags);
955     return NS_ERROR_NOT_IMPLEMENTED;
956 }
957
958 static nsresult NSAPI nsWebBrowserChrome_DestroyBrowserWindow(nsIWebBrowserChrome *iface)
959 {
960     NSContainer *This = NSWBCHROME_THIS(iface);
961     TRACE("(%p)\n", This);
962     return NS_ERROR_NOT_IMPLEMENTED;
963 }
964
965 static nsresult NSAPI nsWebBrowserChrome_SizeBrowserTo(nsIWebBrowserChrome *iface,
966         PRInt32 aCX, PRInt32 aCY)
967 {
968     NSContainer *This = NSWBCHROME_THIS(iface);
969     WARN("(%p)->(%d %d)\n", This, aCX, aCY);
970     return NS_ERROR_NOT_IMPLEMENTED;
971 }
972
973 static nsresult NSAPI nsWebBrowserChrome_ShowAsModal(nsIWebBrowserChrome *iface)
974 {
975     NSContainer *This = NSWBCHROME_THIS(iface);
976     WARN("(%p)\n", This);
977     return NS_ERROR_NOT_IMPLEMENTED;
978 }
979
980 static nsresult NSAPI nsWebBrowserChrome_IsWindowModal(nsIWebBrowserChrome *iface, PRBool *_retval)
981 {
982     NSContainer *This = NSWBCHROME_THIS(iface);
983     WARN("(%p)->(%p)\n", This, _retval);
984     return NS_ERROR_NOT_IMPLEMENTED;
985 }
986
987 static nsresult NSAPI nsWebBrowserChrome_ExitModalEventLoop(nsIWebBrowserChrome *iface,
988         nsresult aStatus)
989 {
990     NSContainer *This = NSWBCHROME_THIS(iface);
991     WARN("(%p)->(%08x)\n", This, aStatus);
992     return NS_ERROR_NOT_IMPLEMENTED;
993 }
994
995 #undef NSWBCHROME_THIS
996
997 static const nsIWebBrowserChromeVtbl nsWebBrowserChromeVtbl = {
998     nsWebBrowserChrome_QueryInterface,
999     nsWebBrowserChrome_AddRef,
1000     nsWebBrowserChrome_Release,
1001     nsWebBrowserChrome_SetStatus,
1002     nsWebBrowserChrome_GetWebBrowser,
1003     nsWebBrowserChrome_SetWebBrowser,
1004     nsWebBrowserChrome_GetChromeFlags,
1005     nsWebBrowserChrome_SetChromeFlags,
1006     nsWebBrowserChrome_DestroyBrowserWindow,
1007     nsWebBrowserChrome_SizeBrowserTo,
1008     nsWebBrowserChrome_ShowAsModal,
1009     nsWebBrowserChrome_IsWindowModal,
1010     nsWebBrowserChrome_ExitModalEventLoop
1011 };
1012
1013 /**********************************************************
1014  *      nsIContextMenuListener interface
1015  */
1016
1017 #define NSCML_THIS(iface) DEFINE_THIS(NSContainer, ContextMenuListener, iface)
1018
1019 static nsresult NSAPI nsContextMenuListener_QueryInterface(nsIContextMenuListener *iface,
1020         nsIIDRef riid, nsQIResult result)
1021 {
1022     NSContainer *This = NSCML_THIS(iface);
1023     return nsIWebBrowserChrome_QueryInterface(NSWBCHROME(This), riid, result);
1024 }
1025
1026 static nsrefcnt NSAPI nsContextMenuListener_AddRef(nsIContextMenuListener *iface)
1027 {
1028     NSContainer *This = NSCML_THIS(iface);
1029     return nsIWebBrowserChrome_AddRef(NSWBCHROME(This));
1030 }
1031
1032 static nsrefcnt NSAPI nsContextMenuListener_Release(nsIContextMenuListener *iface)
1033 {
1034     NSContainer *This = NSCML_THIS(iface);
1035     return nsIWebBrowserChrome_Release(NSWBCHROME(This));
1036 }
1037
1038 static nsresult NSAPI nsContextMenuListener_OnShowContextMenu(nsIContextMenuListener *iface,
1039         PRUint32 aContextFlags, nsIDOMEvent *aEvent, nsIDOMNode *aNode)
1040 {
1041     NSContainer *This = NSCML_THIS(iface);
1042     nsIDOMMouseEvent *event;
1043     POINT pt;
1044     DWORD dwID = CONTEXT_MENU_DEFAULT;
1045     nsresult nsres;
1046
1047     TRACE("(%p)->(%08x %p %p)\n", This, aContextFlags, aEvent, aNode);
1048
1049     nsres = nsIDOMEvent_QueryInterface(aEvent, &IID_nsIDOMMouseEvent, (void**)&event);
1050     if(NS_FAILED(nsres)) {
1051         ERR("Could not get nsIDOMMouseEvent interface: %08x\n", nsres);
1052         return nsres;
1053     }
1054
1055     nsIDOMMouseEvent_GetScreenX(event, &pt.x);
1056     nsIDOMMouseEvent_GetScreenY(event, &pt.y);
1057     nsIDOMMouseEvent_Release(event);
1058
1059     switch(aContextFlags) {
1060     case CONTEXT_NONE:
1061     case CONTEXT_DOCUMENT:
1062     case CONTEXT_TEXT:
1063         dwID = CONTEXT_MENU_DEFAULT;
1064         break;
1065     case CONTEXT_IMAGE:
1066     case CONTEXT_IMAGE|CONTEXT_LINK:
1067         dwID = CONTEXT_MENU_IMAGE;
1068         break;
1069     case CONTEXT_LINK:
1070         dwID = CONTEXT_MENU_ANCHOR;
1071         break;
1072     case CONTEXT_INPUT:
1073         dwID = CONTEXT_MENU_CONTROL;
1074         break;
1075     default:
1076         FIXME("aContextFlags=%08x\n", aContextFlags);
1077     };
1078
1079     show_context_menu(This->doc, dwID, &pt, (IDispatch*)HTMLDOMNODE(get_node(This->doc->basedoc.doc_node, aNode, TRUE)));
1080
1081     return NS_OK;
1082 }
1083
1084 #undef NSCML_THIS
1085
1086 static const nsIContextMenuListenerVtbl nsContextMenuListenerVtbl = {
1087     nsContextMenuListener_QueryInterface,
1088     nsContextMenuListener_AddRef,
1089     nsContextMenuListener_Release,
1090     nsContextMenuListener_OnShowContextMenu
1091 };
1092
1093 /**********************************************************
1094  *      nsIURIContentListener interface
1095  */
1096
1097 #define NSURICL_THIS(iface) DEFINE_THIS(NSContainer, URIContentListener, iface)
1098
1099 static nsresult NSAPI nsURIContentListener_QueryInterface(nsIURIContentListener *iface,
1100         nsIIDRef riid, nsQIResult result)
1101 {
1102     NSContainer *This = NSURICL_THIS(iface);
1103     return nsIWebBrowserChrome_QueryInterface(NSWBCHROME(This), riid, result);
1104 }
1105
1106 static nsrefcnt NSAPI nsURIContentListener_AddRef(nsIURIContentListener *iface)
1107 {
1108     NSContainer *This = NSURICL_THIS(iface);
1109     return nsIWebBrowserChrome_AddRef(NSWBCHROME(This));
1110 }
1111
1112 static nsrefcnt NSAPI nsURIContentListener_Release(nsIURIContentListener *iface)
1113 {
1114     NSContainer *This = NSURICL_THIS(iface);
1115     return nsIWebBrowserChrome_Release(NSWBCHROME(This));
1116 }
1117
1118 static nsresult NSAPI nsURIContentListener_OnStartURIOpen(nsIURIContentListener *iface,
1119                                                           nsIURI *aURI, PRBool *_retval)
1120 {
1121     NSContainer *This = NSURICL_THIS(iface);
1122     nsACString spec_str;
1123     const char *spec;
1124     nsresult nsres;
1125
1126     nsACString_Init(&spec_str, NULL);
1127     nsIURI_GetSpec(aURI, &spec_str);
1128     nsACString_GetData(&spec_str, &spec);
1129
1130     TRACE("(%p)->(%p(%s) %p)\n", This, aURI, debugstr_a(spec), _retval);
1131
1132     nsACString_Finish(&spec_str);
1133
1134     nsres = on_start_uri_open(This, aURI, _retval);
1135     if(NS_FAILED(nsres))
1136         return nsres;
1137
1138     return !*_retval && This->content_listener
1139         ? nsIURIContentListener_OnStartURIOpen(This->content_listener, aURI, _retval)
1140         : NS_OK;
1141 }
1142
1143 static nsresult NSAPI nsURIContentListener_DoContent(nsIURIContentListener *iface,
1144         const char *aContentType, PRBool aIsContentPreferred, nsIRequest *aRequest,
1145         nsIStreamListener **aContentHandler, PRBool *_retval)
1146 {
1147     NSContainer *This = NSURICL_THIS(iface);
1148
1149     TRACE("(%p)->(%s %x %p %p %p)\n", This, debugstr_a(aContentType), aIsContentPreferred,
1150             aRequest, aContentHandler, _retval);
1151
1152     return This->content_listener
1153         ? nsIURIContentListener_DoContent(This->content_listener, aContentType,
1154                   aIsContentPreferred, aRequest, aContentHandler, _retval)
1155         : NS_ERROR_NOT_IMPLEMENTED;
1156 }
1157
1158 static nsresult NSAPI nsURIContentListener_IsPreferred(nsIURIContentListener *iface,
1159         const char *aContentType, char **aDesiredContentType, PRBool *_retval)
1160 {
1161     NSContainer *This = NSURICL_THIS(iface);
1162
1163     TRACE("(%p)->(%s %p %p)\n", This, debugstr_a(aContentType), aDesiredContentType, _retval);
1164
1165     /* FIXME: Should we do something here? */
1166     *_retval = TRUE; 
1167
1168     return This->content_listener
1169         ? nsIURIContentListener_IsPreferred(This->content_listener, aContentType,
1170                   aDesiredContentType, _retval)
1171         : NS_OK;
1172 }
1173
1174 static nsresult NSAPI nsURIContentListener_CanHandleContent(nsIURIContentListener *iface,
1175         const char *aContentType, PRBool aIsContentPreferred, char **aDesiredContentType,
1176         PRBool *_retval)
1177 {
1178     NSContainer *This = NSURICL_THIS(iface);
1179
1180     TRACE("(%p)->(%s %x %p %p)\n", This, debugstr_a(aContentType), aIsContentPreferred,
1181             aDesiredContentType, _retval);
1182
1183     return This->content_listener
1184         ? nsIURIContentListener_CanHandleContent(This->content_listener, aContentType,
1185                 aIsContentPreferred, aDesiredContentType, _retval)
1186         : NS_ERROR_NOT_IMPLEMENTED;
1187 }
1188
1189 static nsresult NSAPI nsURIContentListener_GetLoadCookie(nsIURIContentListener *iface,
1190         nsISupports **aLoadCookie)
1191 {
1192     NSContainer *This = NSURICL_THIS(iface);
1193
1194     WARN("(%p)->(%p)\n", This, aLoadCookie);
1195
1196     return This->content_listener
1197         ? nsIURIContentListener_GetLoadCookie(This->content_listener, aLoadCookie)
1198         : NS_ERROR_NOT_IMPLEMENTED;
1199 }
1200
1201 static nsresult NSAPI nsURIContentListener_SetLoadCookie(nsIURIContentListener *iface,
1202         nsISupports *aLoadCookie)
1203 {
1204     NSContainer *This = NSURICL_THIS(iface);
1205
1206     WARN("(%p)->(%p)\n", This, aLoadCookie);
1207
1208     return This->content_listener
1209         ? nsIURIContentListener_SetLoadCookie(This->content_listener, aLoadCookie)
1210         : NS_ERROR_NOT_IMPLEMENTED;
1211 }
1212
1213 static nsresult NSAPI nsURIContentListener_GetParentContentListener(nsIURIContentListener *iface,
1214         nsIURIContentListener **aParentContentListener)
1215 {
1216     NSContainer *This = NSURICL_THIS(iface);
1217
1218     TRACE("(%p)->(%p)\n", This, aParentContentListener);
1219
1220     if(This->content_listener)
1221         nsIURIContentListener_AddRef(This->content_listener);
1222
1223     *aParentContentListener = This->content_listener;
1224     return NS_OK;
1225 }
1226
1227 static nsresult NSAPI nsURIContentListener_SetParentContentListener(nsIURIContentListener *iface,
1228         nsIURIContentListener *aParentContentListener)
1229 {
1230     NSContainer *This = NSURICL_THIS(iface);
1231
1232     TRACE("(%p)->(%p)\n", This, aParentContentListener);
1233
1234     if(aParentContentListener == NSURICL(This))
1235         return NS_OK;
1236
1237     if(This->content_listener)
1238         nsIURIContentListener_Release(This->content_listener);
1239
1240     This->content_listener = aParentContentListener;
1241     if(This->content_listener)
1242         nsIURIContentListener_AddRef(This->content_listener);
1243
1244     return NS_OK;
1245 }
1246
1247 #undef NSURICL_THIS
1248
1249 static const nsIURIContentListenerVtbl nsURIContentListenerVtbl = {
1250     nsURIContentListener_QueryInterface,
1251     nsURIContentListener_AddRef,
1252     nsURIContentListener_Release,
1253     nsURIContentListener_OnStartURIOpen,
1254     nsURIContentListener_DoContent,
1255     nsURIContentListener_IsPreferred,
1256     nsURIContentListener_CanHandleContent,
1257     nsURIContentListener_GetLoadCookie,
1258     nsURIContentListener_SetLoadCookie,
1259     nsURIContentListener_GetParentContentListener,
1260     nsURIContentListener_SetParentContentListener
1261 };
1262
1263 /**********************************************************
1264  *      nsIEmbeddinSiteWindow interface
1265  */
1266
1267 #define NSEMBWNDS_THIS(iface) DEFINE_THIS(NSContainer, EmbeddingSiteWindow, iface)
1268
1269 static nsresult NSAPI nsEmbeddingSiteWindow_QueryInterface(nsIEmbeddingSiteWindow *iface,
1270         nsIIDRef riid, nsQIResult result)
1271 {
1272     NSContainer *This = NSEMBWNDS_THIS(iface);
1273     return nsIWebBrowserChrome_QueryInterface(NSWBCHROME(This), riid, result);
1274 }
1275
1276 static nsrefcnt NSAPI nsEmbeddingSiteWindow_AddRef(nsIEmbeddingSiteWindow *iface)
1277 {
1278     NSContainer *This = NSEMBWNDS_THIS(iface);
1279     return nsIWebBrowserChrome_AddRef(NSWBCHROME(This));
1280 }
1281
1282 static nsrefcnt NSAPI nsEmbeddingSiteWindow_Release(nsIEmbeddingSiteWindow *iface)
1283 {
1284     NSContainer *This = NSEMBWNDS_THIS(iface);
1285     return nsIWebBrowserChrome_Release(NSWBCHROME(This));
1286 }
1287
1288 static nsresult NSAPI nsEmbeddingSiteWindow_SetDimensions(nsIEmbeddingSiteWindow *iface,
1289         PRUint32 flags, PRInt32 x, PRInt32 y, PRInt32 cx, PRInt32 cy)
1290 {
1291     NSContainer *This = NSEMBWNDS_THIS(iface);
1292     WARN("(%p)->(%08x %d %d %d %d)\n", This, flags, x, y, cx, cy);
1293     return NS_ERROR_NOT_IMPLEMENTED;
1294 }
1295
1296 static nsresult NSAPI nsEmbeddingSiteWindow_GetDimensions(nsIEmbeddingSiteWindow *iface,
1297         PRUint32 flags, PRInt32 *x, PRInt32 *y, PRInt32 *cx, PRInt32 *cy)
1298 {
1299     NSContainer *This = NSEMBWNDS_THIS(iface);
1300     WARN("(%p)->(%08x %p %p %p %p)\n", This, flags, x, y, cx, cy);
1301     return NS_ERROR_NOT_IMPLEMENTED;
1302 }
1303
1304 static nsresult NSAPI nsEmbeddingSiteWindow_SetFocus(nsIEmbeddingSiteWindow *iface)
1305 {
1306     NSContainer *This = NSEMBWNDS_THIS(iface);
1307
1308     TRACE("(%p)\n", This);
1309
1310     return nsIBaseWindow_SetFocus(This->window);
1311 }
1312
1313 static nsresult NSAPI nsEmbeddingSiteWindow_GetVisibility(nsIEmbeddingSiteWindow *iface,
1314         PRBool *aVisibility)
1315 {
1316     NSContainer *This = NSEMBWNDS_THIS(iface);
1317
1318     TRACE("(%p)->(%p)\n", This, aVisibility);
1319
1320     *aVisibility = This->doc && This->doc->hwnd && IsWindowVisible(This->doc->hwnd);
1321     return NS_OK;
1322 }
1323
1324 static nsresult NSAPI nsEmbeddingSiteWindow_SetVisibility(nsIEmbeddingSiteWindow *iface,
1325         PRBool aVisibility)
1326 {
1327     NSContainer *This = NSEMBWNDS_THIS(iface);
1328
1329     TRACE("(%p)->(%x)\n", This, aVisibility);
1330
1331     return NS_OK;
1332 }
1333
1334 static nsresult NSAPI nsEmbeddingSiteWindow_GetTitle(nsIEmbeddingSiteWindow *iface,
1335         PRUnichar **aTitle)
1336 {
1337     NSContainer *This = NSEMBWNDS_THIS(iface);
1338     WARN("(%p)->(%p)\n", This, aTitle);
1339     return NS_ERROR_NOT_IMPLEMENTED;
1340 }
1341
1342 static nsresult NSAPI nsEmbeddingSiteWindow_SetTitle(nsIEmbeddingSiteWindow *iface,
1343         const PRUnichar *aTitle)
1344 {
1345     NSContainer *This = NSEMBWNDS_THIS(iface);
1346     WARN("(%p)->(%s)\n", This, debugstr_w(aTitle));
1347     return NS_ERROR_NOT_IMPLEMENTED;
1348 }
1349
1350 static nsresult NSAPI nsEmbeddingSiteWindow_GetSiteWindow(nsIEmbeddingSiteWindow *iface,
1351         void **aSiteWindow)
1352 {
1353     NSContainer *This = NSEMBWNDS_THIS(iface);
1354
1355     TRACE("(%p)->(%p)\n", This, aSiteWindow);
1356
1357     *aSiteWindow = This->hwnd;
1358     return NS_OK;
1359 }
1360
1361 static const nsIEmbeddingSiteWindowVtbl nsEmbeddingSiteWindowVtbl = {
1362     nsEmbeddingSiteWindow_QueryInterface,
1363     nsEmbeddingSiteWindow_AddRef,
1364     nsEmbeddingSiteWindow_Release,
1365     nsEmbeddingSiteWindow_SetDimensions,
1366     nsEmbeddingSiteWindow_GetDimensions,
1367     nsEmbeddingSiteWindow_SetFocus,
1368     nsEmbeddingSiteWindow_GetVisibility,
1369     nsEmbeddingSiteWindow_SetVisibility,
1370     nsEmbeddingSiteWindow_GetTitle,
1371     nsEmbeddingSiteWindow_SetTitle,
1372     nsEmbeddingSiteWindow_GetSiteWindow
1373 };
1374
1375 #define NSTOOLTIP_THIS(iface) DEFINE_THIS(NSContainer, TooltipListener, iface)
1376
1377 static nsresult NSAPI nsTooltipListener_QueryInterface(nsITooltipListener *iface, nsIIDRef riid,
1378                                                        nsQIResult result)
1379 {
1380     NSContainer *This = NSTOOLTIP_THIS(iface);
1381     return nsIWebBrowserChrome_QueryInterface(NSWBCHROME(This), riid, result);
1382 }
1383
1384 static nsrefcnt NSAPI nsTooltipListener_AddRef(nsITooltipListener *iface)
1385 {
1386     NSContainer *This = NSTOOLTIP_THIS(iface);
1387     return nsIWebBrowserChrome_AddRef(NSWBCHROME(This));
1388 }
1389
1390 static nsrefcnt NSAPI nsTooltipListener_Release(nsITooltipListener *iface)
1391 {
1392     NSContainer *This = NSTOOLTIP_THIS(iface);
1393     return nsIWebBrowserChrome_Release(NSWBCHROME(This));
1394 }
1395
1396 static nsresult NSAPI nsTooltipListener_OnShowTooltip(nsITooltipListener *iface,
1397         PRInt32 aXCoord, PRInt32 aYCoord, const PRUnichar *aTipText)
1398 {
1399     NSContainer *This = NSTOOLTIP_THIS(iface);
1400
1401     if (This->doc)
1402         show_tooltip(This->doc, aXCoord, aYCoord, aTipText);
1403
1404     return NS_OK;
1405 }
1406
1407 static nsresult NSAPI nsTooltipListener_OnHideTooltip(nsITooltipListener *iface)
1408 {
1409     NSContainer *This = NSTOOLTIP_THIS(iface);
1410
1411     if (This->doc)
1412         hide_tooltip(This->doc);
1413
1414     return NS_OK;
1415 }
1416
1417 #undef NSTOOLTIM_THIS
1418
1419 static const nsITooltipListenerVtbl nsTooltipListenerVtbl = {
1420     nsTooltipListener_QueryInterface,
1421     nsTooltipListener_AddRef,
1422     nsTooltipListener_Release,
1423     nsTooltipListener_OnShowTooltip,
1424     nsTooltipListener_OnHideTooltip
1425 };
1426
1427 #define NSIFACEREQ_THIS(iface) DEFINE_THIS(NSContainer, InterfaceRequestor, iface)
1428
1429 static nsresult NSAPI nsInterfaceRequestor_QueryInterface(nsIInterfaceRequestor *iface,
1430                                                           nsIIDRef riid, nsQIResult result)
1431 {
1432     NSContainer *This = NSIFACEREQ_THIS(iface);
1433     return nsIWebBrowserChrome_QueryInterface(NSWBCHROME(This), riid, result);
1434 }
1435
1436 static nsrefcnt NSAPI nsInterfaceRequestor_AddRef(nsIInterfaceRequestor *iface)
1437 {
1438     NSContainer *This = NSIFACEREQ_THIS(iface);
1439     return nsIWebBrowserChrome_AddRef(NSWBCHROME(This));
1440 }
1441
1442 static nsrefcnt NSAPI nsInterfaceRequestor_Release(nsIInterfaceRequestor *iface)
1443 {
1444     NSContainer *This = NSIFACEREQ_THIS(iface);
1445     return nsIWebBrowserChrome_Release(NSWBCHROME(This));
1446 }
1447
1448 static nsresult NSAPI nsInterfaceRequestor_GetInterface(nsIInterfaceRequestor *iface,
1449                                                         nsIIDRef riid, nsQIResult result)
1450 {
1451     NSContainer *This = NSIFACEREQ_THIS(iface);
1452
1453     if(IsEqualGUID(&IID_nsIDOMWindow, riid)) {
1454         TRACE("(%p)->(IID_nsIDOMWindow %p)\n", This, result);
1455         return nsIWebBrowser_GetContentDOMWindow(This->webbrowser, (nsIDOMWindow**)result);
1456     }
1457
1458     return nsIWebBrowserChrome_QueryInterface(NSWBCHROME(This), riid, result);
1459 }
1460
1461 #undef NSIFACEREQ_THIS
1462
1463 static const nsIInterfaceRequestorVtbl nsInterfaceRequestorVtbl = {
1464     nsInterfaceRequestor_QueryInterface,
1465     nsInterfaceRequestor_AddRef,
1466     nsInterfaceRequestor_Release,
1467     nsInterfaceRequestor_GetInterface
1468 };
1469
1470 #define NSWEAKREF_THIS(iface) DEFINE_THIS(NSContainer, WeakReference, iface)
1471
1472 static nsresult NSAPI nsWeakReference_QueryInterface(nsIWeakReference *iface,
1473         nsIIDRef riid, nsQIResult result)
1474 {
1475     NSContainer *This = NSWEAKREF_THIS(iface);
1476     return nsIWebBrowserChrome_QueryInterface(NSWBCHROME(This), riid, result);
1477 }
1478
1479 static nsrefcnt NSAPI nsWeakReference_AddRef(nsIWeakReference *iface)
1480 {
1481     NSContainer *This = NSWEAKREF_THIS(iface);
1482     return nsIWebBrowserChrome_AddRef(NSWBCHROME(This));
1483 }
1484
1485 static nsrefcnt NSAPI nsWeakReference_Release(nsIWeakReference *iface)
1486 {
1487     NSContainer *This = NSWEAKREF_THIS(iface);
1488     return nsIWebBrowserChrome_Release(NSWBCHROME(This));
1489 }
1490
1491 static nsresult NSAPI nsWeakReference_QueryReferent(nsIWeakReference *iface,
1492         const nsIID *riid, void **result)
1493 {
1494     NSContainer *This = NSWEAKREF_THIS(iface);
1495     return nsIWebBrowserChrome_QueryInterface(NSWBCHROME(This), riid, result);
1496 }
1497
1498 #undef NSWEAKREF_THIS
1499
1500 static const nsIWeakReferenceVtbl nsWeakReferenceVtbl = {
1501     nsWeakReference_QueryInterface,
1502     nsWeakReference_AddRef,
1503     nsWeakReference_Release,
1504     nsWeakReference_QueryReferent
1505 };
1506
1507 #define NSSUPWEAKREF_THIS(iface) DEFINE_THIS(NSContainer, SupportsWeakReference, iface)
1508
1509 static nsresult NSAPI nsSupportsWeakReference_QueryInterface(nsISupportsWeakReference *iface,
1510         nsIIDRef riid, nsQIResult result)
1511 {
1512     NSContainer *This = NSSUPWEAKREF_THIS(iface);
1513     return nsIWebBrowserChrome_QueryInterface(NSWBCHROME(This), riid, result);
1514 }
1515
1516 static nsrefcnt NSAPI nsSupportsWeakReference_AddRef(nsISupportsWeakReference *iface)
1517 {
1518     NSContainer *This = NSSUPWEAKREF_THIS(iface);
1519     return nsIWebBrowserChrome_AddRef(NSWBCHROME(This));
1520 }
1521
1522 static nsrefcnt NSAPI nsSupportsWeakReference_Release(nsISupportsWeakReference *iface)
1523 {
1524     NSContainer *This = NSSUPWEAKREF_THIS(iface);
1525     return nsIWebBrowserChrome_Release(NSWBCHROME(This));
1526 }
1527
1528 static nsresult NSAPI nsSupportsWeakReference_GetWeakReference(nsISupportsWeakReference *iface,
1529         nsIWeakReference **_retval)
1530 {
1531     NSContainer *This = NSSUPWEAKREF_THIS(iface);
1532
1533     TRACE("(%p)->(%p)\n", This, _retval);
1534
1535     nsIWeakReference_AddRef(NSWEAKREF(This));
1536     *_retval = NSWEAKREF(This);
1537     return NS_OK;
1538 }
1539
1540 #undef NSWEAKREF_THIS
1541
1542 static const nsISupportsWeakReferenceVtbl nsSupportsWeakReferenceVtbl = {
1543     nsSupportsWeakReference_QueryInterface,
1544     nsSupportsWeakReference_AddRef,
1545     nsSupportsWeakReference_Release,
1546     nsSupportsWeakReference_GetWeakReference
1547 };
1548
1549
1550 NSContainer *NSContainer_Create(HTMLDocumentObj *doc, NSContainer *parent)
1551 {
1552     nsIWebBrowserSetup *wbsetup;
1553     nsIScrollable *scrollable;
1554     NSContainer *ret;
1555     nsresult nsres;
1556
1557     if(!load_gecko(TRUE))
1558         return NULL;
1559
1560     ret = heap_alloc_zero(sizeof(NSContainer));
1561
1562     ret->lpWebBrowserChromeVtbl      = &nsWebBrowserChromeVtbl;
1563     ret->lpContextMenuListenerVtbl   = &nsContextMenuListenerVtbl;
1564     ret->lpURIContentListenerVtbl    = &nsURIContentListenerVtbl;
1565     ret->lpEmbeddingSiteWindowVtbl   = &nsEmbeddingSiteWindowVtbl;
1566     ret->lpTooltipListenerVtbl       = &nsTooltipListenerVtbl;
1567     ret->lpInterfaceRequestorVtbl    = &nsInterfaceRequestorVtbl;
1568     ret->lpWeakReferenceVtbl         = &nsWeakReferenceVtbl;
1569     ret->lpSupportsWeakReferenceVtbl = &nsSupportsWeakReferenceVtbl;
1570
1571     ret->doc = doc;
1572     ret->ref = 1;
1573
1574     nsres = nsIComponentManager_CreateInstanceByContractID(pCompMgr, NS_WEBBROWSER_CONTRACTID,
1575             NULL, &IID_nsIWebBrowser, (void**)&ret->webbrowser);
1576     if(NS_FAILED(nsres)) {
1577         ERR("Creating WebBrowser failed: %08x\n", nsres);
1578         heap_free(ret);
1579         return NULL;
1580     }
1581
1582     if(parent)
1583         nsIWebBrowserChrome_AddRef(NSWBCHROME(parent));
1584     ret->parent = parent;
1585
1586     nsres = nsIWebBrowser_SetContainerWindow(ret->webbrowser, NSWBCHROME(ret));
1587     if(NS_FAILED(nsres))
1588         ERR("SetContainerWindow failed: %08x\n", nsres);
1589
1590     nsres = nsIWebBrowser_QueryInterface(ret->webbrowser, &IID_nsIBaseWindow,
1591             (void**)&ret->window);
1592     if(NS_FAILED(nsres))
1593         ERR("Could not get nsIBaseWindow interface: %08x\n", nsres);
1594
1595     nsres = nsIWebBrowser_QueryInterface(ret->webbrowser, &IID_nsIWebBrowserSetup,
1596                                          (void**)&wbsetup);
1597     if(NS_SUCCEEDED(nsres)) {
1598         nsres = nsIWebBrowserSetup_SetProperty(wbsetup, SETUP_IS_CHROME_WRAPPER, FALSE);
1599         nsIWebBrowserSetup_Release(wbsetup);
1600         if(NS_FAILED(nsres))
1601             ERR("SetProperty(SETUP_IS_CHROME_WRAPPER) failed: %08x\n", nsres);
1602     }else {
1603         ERR("Could not get nsIWebBrowserSetup interface\n");
1604     }
1605
1606     nsres = nsIWebBrowser_QueryInterface(ret->webbrowser, &IID_nsIWebNavigation,
1607             (void**)&ret->navigation);
1608     if(NS_FAILED(nsres))
1609         ERR("Could not get nsIWebNavigation interface: %08x\n", nsres);
1610
1611     nsres = nsIWebBrowserFocus_QueryInterface(ret->webbrowser, &IID_nsIWebBrowserFocus,
1612             (void**)&ret->focus);
1613     if(NS_FAILED(nsres))
1614         ERR("Could not get nsIWebBrowserFocus interface: %08x\n", nsres);
1615
1616     if(!nscontainer_class)
1617         register_nscontainer_class();
1618
1619     ret->hwnd = CreateWindowExW(0, wszNsContainer, NULL,
1620             WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, 100, 100,
1621             GetDesktopWindow(), NULL, hInst, ret);
1622
1623     nsres = nsIBaseWindow_InitWindow(ret->window, ret->hwnd, NULL, 0, 0, 100, 100);
1624     if(NS_SUCCEEDED(nsres)) {
1625         nsres = nsIBaseWindow_Create(ret->window);
1626         if(NS_FAILED(nsres))
1627             WARN("Creating window failed: %08x\n", nsres);
1628
1629         nsIBaseWindow_SetVisibility(ret->window, FALSE);
1630         nsIBaseWindow_SetEnabled(ret->window, FALSE);
1631     }else {
1632         ERR("InitWindow failed: %08x\n", nsres);
1633     }
1634
1635     nsres = nsIWebBrowser_SetParentURIContentListener(ret->webbrowser, NSURICL(ret));
1636     if(NS_FAILED(nsres))
1637         ERR("SetParentURIContentListener failed: %08x\n", nsres);
1638
1639     nsres = nsIWebBrowser_QueryInterface(ret->webbrowser, &IID_nsIScrollable, (void**)&scrollable);
1640     if(NS_SUCCEEDED(nsres)) {
1641         nsres = nsIScrollable_SetDefaultScrollbarPreferences(scrollable,
1642                 ScrollOrientation_Y, Scrollbar_Always);
1643         if(NS_FAILED(nsres))
1644             ERR("Could not set default Y scrollbar prefs: %08x\n", nsres);
1645
1646         nsres = nsIScrollable_SetDefaultScrollbarPreferences(scrollable,
1647                 ScrollOrientation_X, Scrollbar_Auto);
1648         if(NS_FAILED(nsres))
1649             ERR("Could not set default X scrollbar prefs: %08x\n", nsres);
1650
1651         nsIScrollable_Release(scrollable);
1652     }else {
1653         ERR("Could not get nsIScrollable: %08x\n", nsres);
1654     }
1655
1656     return ret;
1657 }
1658
1659 void NSContainer_Release(NSContainer *This)
1660 {
1661     TRACE("(%p)\n", This);
1662
1663     This->doc = NULL;
1664
1665     ShowWindow(This->hwnd, SW_HIDE);
1666     SetParent(This->hwnd, NULL);
1667
1668     nsIBaseWindow_SetVisibility(This->window, FALSE);
1669     nsIBaseWindow_Destroy(This->window);
1670
1671     nsIWebBrowser_SetContainerWindow(This->webbrowser, NULL);
1672
1673     nsIWebBrowser_Release(This->webbrowser);
1674     This->webbrowser = NULL;
1675
1676     nsIWebNavigation_Release(This->navigation);
1677     This->navigation = NULL;
1678
1679     nsIBaseWindow_Release(This->window);
1680     This->window = NULL;
1681
1682     nsIWebBrowserFocus_Release(This->focus);
1683     This->focus = NULL;
1684
1685     if(This->editor_controller) {
1686         nsIController_Release(This->editor_controller);
1687         This->editor_controller = NULL;
1688     }
1689
1690     if(This->editor) {
1691         nsIEditor_Release(This->editor);
1692         This->editor = NULL;
1693     }
1694
1695     if(This->content_listener) {
1696         nsIURIContentListener_Release(This->content_listener);
1697         This->content_listener = NULL;
1698     }
1699
1700     if(This->hwnd) {
1701         DestroyWindow(This->hwnd);
1702         This->hwnd = NULL;
1703     }
1704
1705     nsIWebBrowserChrome_Release(NSWBCHROME(This));
1706 }