mshtml: Added Wine Gecko installer.
[wine] / dlls / shell32 / shlexec.c
1 /*
2  *                              Shell Library Functions
3  *
4  * Copyright 1998 Marcus Meissner
5  * Copyright 2002 Eric Pouech
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #ifdef HAVE_UNISTD_H
30 # include <unistd.h>
31 #endif
32 #include <ctype.h>
33 #include <assert.h>
34
35 #define COBJMACROS
36
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "winreg.h"
41 #include "winuser.h"
42 #include "shlwapi.h"
43 #include "ddeml.h"
44
45 #include "wine/winbase16.h"
46 #include "shell32_main.h"
47 #include "pidl.h"
48
49 #include "wine/debug.h"
50
51 WINE_DEFAULT_DEBUG_CHANNEL(exec);
52
53 static const WCHAR wszOpen[] = {'o','p','e','n',0};
54 static const WCHAR wszExe[] = {'.','e','x','e',0};
55 static const WCHAR wszILPtr[] = {':','%','p',0};
56 static const WCHAR wszShell[] = {'\\','s','h','e','l','l','\\',0};
57 static const WCHAR wszFolder[] = {'F','o','l','d','e','r',0};
58 static const WCHAR wszEmpty[] = {0};
59
60 #define SEE_MASK_CLASSALL (SEE_MASK_CLASSNAME | SEE_MASK_CLASSKEY)
61
62
63 /***********************************************************************
64  *      SHELL_ArgifyW [Internal]
65  *
66  * this function is supposed to expand the escape sequences found in the registry
67  * some diving reported that the following were used:
68  * + %1, %2...  seem to report to parameter of index N in ShellExecute pmts
69  *      %1 file
70  *      %2 printer
71  *      %3 driver
72  *      %4 port
73  * %I address of a global item ID (explorer switch /idlist)
74  * %L seems to be %1 as long filename followed by the 8+3 variation
75  * %S ???
76  * %* all following parameters (see batfile)
77  *
78  * FIXME: use 'len'
79  * FIXME: Careful of going over string boundaries. No checking is done to 'res'...
80  */
81 static BOOL SHELL_ArgifyW(WCHAR* out, int len, const WCHAR* fmt, const WCHAR* lpFile, LPITEMIDLIST pidl, LPCWSTR args)
82 {
83     WCHAR   xlpFile[1024];
84     BOOL    done = FALSE;
85     BOOL    found_p1 = FALSE;
86     PWSTR   res = out;
87     PCWSTR  cmd;
88     LPVOID  pv;
89
90     TRACE("%p, %d, %s, %s, %p, %p\n", out, len, debugstr_w(fmt),
91           debugstr_w(lpFile), pidl, args);
92
93     while (*fmt)
94     {
95         if (*fmt == '%')
96         {
97             switch (*++fmt)
98             {
99             case '\0':
100             case '%':
101                 *res++ = '%';
102                 break;
103
104             case '2':
105             case '3':
106             case '4':
107             case '5':
108             case '6':
109             case '7':
110             case '8':
111             case '9':
112             case '0':
113             case '*':
114                 if (args)
115                 {
116                     if (*fmt == '*')
117                     {
118                         *res++ = '"';
119                         while(*args)
120                             *res++ = *args++;
121                         *res++ = '"';
122                     }
123                     else
124                     {
125                         while(*args && !isspace(*args))
126                             *res++ = *args++;
127
128                         while(isspace(*args))
129                             ++args;
130                     }
131                     break;
132                 }
133                 /* else fall through */
134             case '1':
135                 if (!done || (*fmt == '1'))
136                 {
137                     /*FIXME Is the call to SearchPathW() really needed? We already have separated out the parameter string in args. */
138                     if (SearchPathW(NULL, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
139                         cmd = xlpFile;
140                     else
141                         cmd = lpFile;
142
143                     /* Add double quotation marks unless we already have them
144                        (e.g.: "file://%1" %* for exefile) or unless the arg is already
145                        enclosed in double quotation marks */
146                     if ((res == out || *(fmt + 1) != '"') && *cmd != '"')
147                     {
148                         *res++ = '"';
149                         strcpyW(res, cmd);
150                         res += strlenW(cmd);
151                         *res++ = '"';
152                     }
153                     else
154                     {
155                         strcpyW(res, cmd);
156                         res += strlenW(cmd);
157                     }
158                 }
159                 found_p1 = TRUE;
160                 break;
161
162             /*
163              * IE uses this a lot for activating things such as windows media
164              * player. This is not verified to be fully correct but it appears
165              * to work just fine.
166              */
167             case 'l':
168             case 'L':
169                 if (lpFile) {
170                     strcpyW(res, lpFile);
171                     res += strlenW(lpFile);
172                 }
173                 found_p1 = TRUE;
174                 break;
175
176             case 'i':
177             case 'I':
178                 if (pidl) {
179                     HGLOBAL hmem = SHAllocShared(pidl, ILGetSize(pidl), 0);
180                     pv = SHLockShared(hmem, 0);
181                     res += sprintfW(res, wszILPtr, pv);
182                     SHUnlockShared(pv);
183                 }
184                 found_p1 = TRUE;
185                 break;
186
187             default:
188                 /*
189                  * Check if this is an env-variable here...
190                  */
191
192                 /* Make sure that we have at least one more %.*/
193                 if (strchrW(fmt, '%'))
194                 {
195                     WCHAR   tmpBuffer[1024];
196                     PWSTR   tmpB = tmpBuffer;
197                     WCHAR   tmpEnvBuff[MAX_PATH];
198                     DWORD   envRet;
199
200                     while (*fmt != '%')
201                         *tmpB++ = *fmt++;
202                     *tmpB++ = 0;
203
204                     TRACE("Checking %s to be an env-var\n", debugstr_w(tmpBuffer));
205
206                     envRet = GetEnvironmentVariableW(tmpBuffer, tmpEnvBuff, MAX_PATH);
207                     if (envRet == 0 || envRet > MAX_PATH)
208                         strcpyW( res, tmpBuffer );
209                     else
210                         strcpyW( res, tmpEnvBuff );
211                     res += strlenW(res);
212                 }
213                 done = TRUE;
214                 break;
215             }
216             /* Don't skip past terminator (catch a single '%' at the end) */
217             if (*fmt != '\0')
218             {
219                 fmt++;
220             }
221         }
222         else
223             *res++ = *fmt++;
224     }
225
226     *res = '\0';
227
228     return found_p1;
229 }
230
231 HRESULT SHELL_GetPathFromIDListForExecuteA(LPCITEMIDLIST pidl, LPSTR pszPath, UINT uOutSize)
232 {
233     STRRET strret;
234     IShellFolder* desktop;
235
236     HRESULT hr = SHGetDesktopFolder(&desktop);
237
238     if (SUCCEEDED(hr)) {
239         hr = IShellFolder_GetDisplayNameOf(desktop, pidl, SHGDN_FORPARSING, &strret);
240
241         if (SUCCEEDED(hr))
242             StrRetToStrNA(pszPath, uOutSize, &strret, pidl);
243
244         IShellFolder_Release(desktop);
245     }
246
247     return hr;
248 }
249
250 HRESULT SHELL_GetPathFromIDListForExecuteW(LPCITEMIDLIST pidl, LPWSTR pszPath, UINT uOutSize)
251 {
252     STRRET strret;
253     IShellFolder* desktop;
254
255     HRESULT hr = SHGetDesktopFolder(&desktop);
256
257     if (SUCCEEDED(hr)) {
258         hr = IShellFolder_GetDisplayNameOf(desktop, pidl, SHGDN_FORPARSING, &strret);
259
260         if (SUCCEEDED(hr))
261             StrRetToStrNW(pszPath, uOutSize, &strret, pidl);
262
263         IShellFolder_Release(desktop);
264     }
265
266     return hr;
267 }
268
269 /*************************************************************************
270  *      SHELL_ExecuteW [Internal]
271  *
272  */
273 static UINT_PTR SHELL_ExecuteW(const WCHAR *lpCmd, WCHAR *env, BOOL shWait,
274                             LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
275 {
276     STARTUPINFOW  startup;
277     PROCESS_INFORMATION info;
278     UINT_PTR retval = 31;
279     UINT gcdret = 0;
280     WCHAR curdir[MAX_PATH];
281
282     TRACE("Execute %s from directory %s\n", debugstr_w(lpCmd), debugstr_w(psei->lpDirectory));
283     /* ShellExecute specifies the command from psei->lpDirectory
284      * if present. Not from the current dir as CreateProcess does */
285     if( psei->lpDirectory && psei->lpDirectory[0] )
286         if( ( gcdret = GetCurrentDirectoryW( MAX_PATH, curdir)))
287             if( !SetCurrentDirectoryW( psei->lpDirectory))
288                 ERR("cannot set directory %s\n", debugstr_w(psei->lpDirectory));
289     ZeroMemory(&startup,sizeof(STARTUPINFOW));
290     startup.cb = sizeof(STARTUPINFOW);
291     startup.dwFlags = STARTF_USESHOWWINDOW;
292     startup.wShowWindow = psei->nShow;
293     if (CreateProcessW(NULL, (LPWSTR)lpCmd, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, env,
294                        psei->lpDirectory && *psei->lpDirectory ? psei->lpDirectory : NULL,
295                        &startup, &info))
296     {
297         /* Give 30 seconds to the app to come up, if desired. Probably only needed
298            when starting app immediately before making a DDE connection. */
299         if (shWait)
300             if (WaitForInputIdle( info.hProcess, 30000 ) == WAIT_FAILED)
301                 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
302         retval = 33;
303         if (psei->fMask & SEE_MASK_NOCLOSEPROCESS)
304             psei_out->hProcess = info.hProcess;
305         else
306             CloseHandle( info.hProcess );
307         CloseHandle( info.hThread );
308     }
309     else if ((retval = GetLastError()) >= 32)
310     {
311         TRACE("CreateProcess returned error %d\n", retval);
312         retval = ERROR_BAD_FORMAT;
313     }
314
315     TRACE("returning %u\n", retval);
316
317     psei_out->hInstApp = (HINSTANCE)retval;
318     if( gcdret )
319         if( !SetCurrentDirectoryW( curdir))
320             ERR("cannot return to directory %s\n", debugstr_w(curdir));
321
322     return retval;
323 }
324
325
326 /***********************************************************************
327  *           SHELL_BuildEnvW    [Internal]
328  *
329  * Build the environment for the new process, adding the specified
330  * path to the PATH variable. Returned pointer must be freed by caller.
331  */
332 static void *SHELL_BuildEnvW( const WCHAR *path )
333 {
334     static const WCHAR wPath[] = {'P','A','T','H','=',0};
335     WCHAR *strings, *new_env;
336     WCHAR *p, *p2;
337     int total = strlenW(path) + 1;
338     BOOL got_path = FALSE;
339
340     if (!(strings = GetEnvironmentStringsW())) return NULL;
341     p = strings;
342     while (*p)
343     {
344         int len = strlenW(p) + 1;
345         if (!strncmpiW( p, wPath, 5 )) got_path = TRUE;
346         total += len;
347         p += len;
348     }
349     if (!got_path) total += 5;  /* we need to create PATH */
350     total++;  /* terminating null */
351
352     if (!(new_env = HeapAlloc( GetProcessHeap(), 0, total * sizeof(WCHAR) )))
353     {
354         FreeEnvironmentStringsW( strings );
355         return NULL;
356     }
357     p = strings;
358     p2 = new_env;
359     while (*p)
360     {
361         int len = strlenW(p) + 1;
362         memcpy( p2, p, len * sizeof(WCHAR) );
363         if (!strncmpiW( p, wPath, 5 ))
364         {
365             p2[len - 1] = ';';
366             strcpyW( p2 + len, path );
367             p2 += strlenW(path) + 1;
368         }
369         p += len;
370         p2 += len;
371     }
372     if (!got_path)
373     {
374         strcpyW( p2, wPath );
375         strcatW( p2, path );
376         p2 += strlenW(p2) + 1;
377     }
378     *p2 = 0;
379     FreeEnvironmentStringsW( strings );
380     return new_env;
381 }
382
383
384 /***********************************************************************
385  *           SHELL_TryAppPathW  [Internal]
386  *
387  * Helper function for SHELL_FindExecutable
388  * @param lpResult - pointer to a buffer of size MAX_PATH
389  * On entry: szName is a filename (probably without path separators).
390  * On exit: if szName found in "App Path", place full path in lpResult, and return true
391  */
392 static BOOL SHELL_TryAppPathW( LPCWSTR szName, LPWSTR lpResult, WCHAR **env)
393 {
394     static const WCHAR wszKeyAppPaths[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s',
395         '\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','A','p','p',' ','P','a','t','h','s','\\',0};
396     static const WCHAR wPath[] = {'P','a','t','h',0};
397     HKEY hkApp = 0;
398     WCHAR buffer[1024];
399     LONG len;
400     LONG res;
401     BOOL found = FALSE;
402
403     if (env) *env = NULL;
404     strcpyW(buffer, wszKeyAppPaths);
405     strcatW(buffer, szName);
406     res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hkApp);
407     if (res) goto end;
408
409     len = MAX_PATH*sizeof(WCHAR);
410     res = RegQueryValueW(hkApp, NULL, lpResult, &len);
411     if (res) goto end;
412     found = TRUE;
413
414     if (env)
415     {
416         DWORD count = sizeof(buffer);
417         if (!RegQueryValueExW(hkApp, wPath, NULL, NULL, (LPBYTE)buffer, &count) && buffer[0])
418             *env = SHELL_BuildEnvW( buffer );
419     }
420
421 end:
422     if (hkApp) RegCloseKey(hkApp);
423     return found;
424 }
425
426 static UINT SHELL_FindExecutableByOperation(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation, LPWSTR key, LPWSTR filetype, LPWSTR command, LONG commandlen)
427 {
428     static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
429
430     /* Looking for ...buffer\shell\<verb>\command */
431     strcatW(filetype, wszShell);
432     strcatW(filetype, lpOperation);
433     strcatW(filetype, wCommand);
434
435     if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, command,
436                        &commandlen) == ERROR_SUCCESS)
437     {
438         commandlen /= sizeof(WCHAR);
439         if (key) strcpyW(key, filetype);
440 #if 0
441         LPWSTR tmp;
442         WCHAR param[256];
443         LONG paramlen = sizeof(param);
444         static const WCHAR wSpace[] = {' ',0};
445
446         /* FIXME: it seems all Windows version don't behave the same here.
447          * the doc states that this ddeexec information can be found after
448          * the exec names.
449          * on Win98, it doesn't appear, but I think it does on Win2k
450          */
451         /* Get the parameters needed by the application
452            from the associated ddeexec key */
453         tmp = strstrW(filetype, wCommand);
454         tmp[0] = '\0';
455         strcatW(filetype, wDdeexec);
456         if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, param,
457                                      &paramlen) == ERROR_SUCCESS)
458         {
459             paramlen /= sizeof(WCHAR);
460             strcatW(command, wSpace);
461             strcatW(command, param);
462             commandlen += paramlen;
463         }
464 #endif
465
466         command[commandlen] = '\0';
467
468         return 33; /* FIXME see SHELL_FindExecutable() */
469     }
470
471     return 31;  /* default - 'No association was found' */
472 }
473
474 /*************************************************************************
475  *      SHELL_FindExecutable [Internal]
476  *
477  * Utility for code sharing between FindExecutable and ShellExecute
478  * in:
479  *      lpFile the name of a file
480  *      lpOperation the operation on it (open)
481  * out:
482  *      lpResult a buffer, big enough :-(, to store the command to do the
483  *              operation on the file
484  *      key a buffer, big enough, to get the key name to do actually the
485  *              command (it'll be used afterwards for more information
486  *              on the operation)
487  */
488 UINT SHELL_FindExecutable(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation,
489                                  LPWSTR lpResult, int resultLen, LPWSTR key, WCHAR **env, LPITEMIDLIST pidl, LPCWSTR args)
490 {
491     static const WCHAR wWindows[] = {'w','i','n','d','o','w','s',0};
492     static const WCHAR wPrograms[] = {'p','r','o','g','r','a','m','s',0};
493     static const WCHAR wExtensions[] = {'e','x','e',' ','p','i','f',' ','b','a','t',' ','c','m','d',' ','c','o','m',0};
494     WCHAR *extension = NULL; /* pointer to file extension */
495     WCHAR filetype[256];     /* registry name for this filetype */
496     LONG  filetypelen = sizeof(filetype); /* length of above */
497     WCHAR command[1024];     /* command from registry */
498     WCHAR wBuffer[256];      /* Used to GetProfileString */
499     UINT  retval = 31;       /* default - 'No association was found' */
500     WCHAR *tok;              /* token pointer */
501     WCHAR xlpFile[256];      /* result of SearchPath */
502     DWORD attribs;           /* file attributes */
503
504     TRACE("%s\n", (lpFile != NULL) ? debugstr_w(lpFile) : "-");
505
506     xlpFile[0] = '\0';
507     lpResult[0] = '\0'; /* Start off with an empty return string */
508     if (key) *key = '\0';
509
510     /* trap NULL parameters on entry */
511     if ((lpFile == NULL) || (lpResult == NULL) || (lpOperation == NULL))
512     {
513         WARN("(lpFile=%s,lpResult=%s,lpOperation=%s): NULL parameter\n",
514              debugstr_w(lpFile), debugstr_w(lpOperation), debugstr_w(lpResult));
515         return 2; /* File not found. Close enough, I guess. */
516     }
517
518     if (SHELL_TryAppPathW( lpFile, lpResult, env ))
519     {
520         TRACE("found %s via App Paths\n", debugstr_w(lpResult));
521         return 33;
522     }
523
524     if (SearchPathW(lpPath, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
525     {
526         TRACE("SearchPathW returned non-zero\n");
527         lpFile = xlpFile;
528         /* Hey, isn't this value ignored?  Why make this call?  Shouldn't we return here?  --dank*/
529     }
530
531     attribs = GetFileAttributesW(lpFile);
532     if (attribs!=INVALID_FILE_ATTRIBUTES && (attribs&FILE_ATTRIBUTE_DIRECTORY))
533     {
534        strcpyW(filetype, wszFolder);
535        filetypelen = 6;    /* strlen("Folder") */
536     }
537     else
538     {
539         /* First thing we need is the file's extension */
540         extension = strrchrW(xlpFile, '.'); /* Assume last "." is the one; */
541         /* File->Run in progman uses */
542         /* .\FILE.EXE :( */
543         TRACE("xlpFile=%s,extension=%s\n", debugstr_w(xlpFile), debugstr_w(extension));
544
545         if (extension == NULL || extension[1]==0)
546         {
547             WARN("Returning 31 - No association\n");
548             return 31; /* no association */
549         }
550
551         /* Three places to check: */
552         /* 1. win.ini, [windows], programs (NB no leading '.') */
553         /* 2. Registry, HKEY_CLASS_ROOT\<filetype>\shell\open\command */
554         /* 3. win.ini, [extensions], extension (NB no leading '.' */
555         /* All I know of the order is that registry is checked before */
556         /* extensions; however, it'd make sense to check the programs */
557         /* section first, so that's what happens here. */
558
559         /* See if it's a program - if GetProfileString fails, we skip this
560          * section. Actually, if GetProfileString fails, we've probably
561          * got a lot more to worry about than running a program... */
562         if (GetProfileStringW(wWindows, wPrograms, wExtensions, wBuffer, sizeof(wBuffer)/sizeof(WCHAR)) > 0)
563         {
564             CharLowerW(wBuffer);
565             tok = wBuffer;
566             while (*tok)
567             {
568                 WCHAR *p = tok;
569                 while (*p && *p != ' ' && *p != '\t') p++;
570                 if (*p)
571                 {
572                     *p++ = 0;
573                     while (*p == ' ' || *p == '\t') p++;
574                 }
575
576                 if (strcmpiW(tok, &extension[1]) == 0) /* have to skip the leading "." */
577                 {
578                     strcpyW(lpResult, xlpFile);
579                     /* Need to perhaps check that the file has a path
580                      * attached */
581                     TRACE("found %s\n", debugstr_w(lpResult));
582                     return 33;
583
584                     /* Greater than 32 to indicate success FIXME According to the
585                      * docs, I should be returning a handle for the
586                      * executable. Does this mean I'm supposed to open the
587                      * executable file or something? More RTFM, I guess... */
588                 }
589                 tok = p;
590             }
591         }
592
593         /* Check registry */
594         if (RegQueryValueW(HKEY_CLASSES_ROOT, extension, filetype,
595                            &filetypelen) == ERROR_SUCCESS)
596         {
597             filetypelen /= sizeof(WCHAR);
598             filetype[filetypelen] = '\0';
599             TRACE("File type: %s\n", debugstr_w(filetype));
600         }
601         else
602         {
603             *filetype = '\0';
604             filetypelen = 0;
605         }
606     }
607
608     if (*filetype)
609     {
610         /* pass the operation string to SHELL_FindExecutableByOperation() */
611         filetype[filetypelen] = '\0';
612         retval = SHELL_FindExecutableByOperation(lpPath, lpFile, lpOperation, key, filetype, command, sizeof(command));
613
614         if (retval > 32)
615         {
616             SHELL_ArgifyW(lpResult, resultLen, command, xlpFile, pidl, args);
617
618             /* Remove double quotation marks and command line arguments */
619             if (*lpResult == '"')
620             {
621                 WCHAR *p = lpResult;
622                 while (*(p + 1) != '"')
623                 {
624                     *p = *(p + 1);
625                     p++;
626                 }
627                 *p = '\0';
628             }
629         }
630     }
631     else /* Check win.ini */
632     {
633         static const WCHAR wExtensions[] = {'e','x','t','e','n','s','i','o','n','s',0};
634
635         /* Toss the leading dot */
636         extension++;
637         if (GetProfileStringW(wExtensions, extension, wszEmpty, command, sizeof(command)/sizeof(WCHAR)) > 0)
638         {
639             if (strlenW(command) != 0)
640             {
641                 strcpyW(lpResult, command);
642                 tok = strchrW(lpResult, '^'); /* should be ^.extension? */
643                 if (tok != NULL)
644                 {
645                     tok[0] = '\0';
646                     strcatW(lpResult, xlpFile); /* what if no dir in xlpFile? */
647                     tok = strchrW(command, '^'); /* see above */
648                     if ((tok != NULL) && (strlenW(tok)>5))
649                     {
650                         strcatW(lpResult, &tok[5]);
651                     }
652                 }
653                 retval = 33; /* FIXME - see above */
654             }
655         }
656     }
657
658     TRACE("returning %s\n", debugstr_w(lpResult));
659     return retval;
660 }
661
662 /******************************************************************
663  *              dde_cb
664  *
665  * callback for the DDE connection. not really useful
666  */
667 static HDDEDATA CALLBACK dde_cb(UINT uType, UINT uFmt, HCONV hConv,
668                                 HSZ hsz1, HSZ hsz2, HDDEDATA hData,
669                                 ULONG_PTR dwData1, ULONG_PTR dwData2)
670 {
671     TRACE("dde_cb: %04x, %04x, %p, %p, %p, %p, %08lx, %08lx\n",
672            uType, uFmt, hConv, hsz1, hsz2, hData, dwData1, dwData2);
673     return NULL;
674 }
675
676 /******************************************************************
677  *              dde_connect
678  *
679  * ShellExecute helper. Used to do an operation with a DDE connection
680  *
681  * Handles both the direct connection (try #1), and if it fails,
682  * launching an application and trying (#2) to connect to it
683  *
684  */
685 static unsigned dde_connect(WCHAR* key, const WCHAR* start, WCHAR* ddeexec,
686                             const WCHAR* lpFile, WCHAR *env,
687                             LPCWSTR szCommandline, LPITEMIDLIST pidl, SHELL_ExecuteW32 execfunc,
688                             LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
689 {
690     static const WCHAR wApplication[] = {'\\','a','p','p','l','i','c','a','t','i','o','n',0};
691     static const WCHAR wTopic[] = {'\\','t','o','p','i','c',0};
692     WCHAR *     endkey = key + strlenW(key);
693     WCHAR       app[256], topic[256], ifexec[256], res[256];
694     LONG        applen, topiclen, ifexeclen;
695     WCHAR *     exec;
696     DWORD       ddeInst = 0;
697     DWORD       tid;
698     HSZ         hszApp, hszTopic;
699     HCONV       hConv;
700     HDDEDATA    hDdeData;
701     unsigned    ret = 31;
702     BOOL unicode = !(GetVersion() & 0x80000000);
703
704     strcpyW(endkey, wApplication);
705     applen = sizeof(app);
706     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, app, &applen) != ERROR_SUCCESS)
707     {
708         FIXME("default app name NIY %s\n", debugstr_w(key));
709         return 2;
710     }
711
712     strcpyW(endkey, wTopic);
713     topiclen = sizeof(topic);
714     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, topic, &topiclen) != ERROR_SUCCESS)
715     {
716         static const WCHAR wSystem[] = {'S','y','s','t','e','m',0};
717         strcpyW(topic, wSystem);
718     }
719
720     if (unicode)
721     {
722         if (DdeInitializeW(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
723             return 2;
724     }
725     else
726     {
727         if (DdeInitializeA(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
728             return 2;
729     }
730
731     hszApp = DdeCreateStringHandleW(ddeInst, app, CP_WINUNICODE);
732     hszTopic = DdeCreateStringHandleW(ddeInst, topic, CP_WINUNICODE);
733
734     hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
735     exec = ddeexec;
736     if (!hConv)
737     {
738         static const WCHAR wIfexec[] = {'\\','i','f','e','x','e','c',0};
739         TRACE("Launching '%s'\n", debugstr_w(start));
740         ret = execfunc(start, env, TRUE, psei, psei_out);
741         if (ret < 32)
742         {
743             TRACE("Couldn't launch\n");
744             goto error;
745         }
746         hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
747         if (!hConv)
748         {
749             TRACE("Couldn't connect. ret=%d\n", ret);
750             DdeUninitialize(ddeInst);
751             SetLastError(ERROR_DDE_FAIL);
752             return 30; /* whatever */
753         }
754         strcpyW(endkey, wIfexec);
755         ifexeclen = sizeof(ifexec);
756         if (RegQueryValueW(HKEY_CLASSES_ROOT, key, ifexec, &ifexeclen) == ERROR_SUCCESS)
757         {
758             exec = ifexec;
759         }
760     }
761
762     SHELL_ArgifyW(res, sizeof(res)/sizeof(WCHAR), exec, lpFile, pidl, szCommandline);
763     TRACE("%s %s => %s\n", debugstr_w(exec), debugstr_w(lpFile), debugstr_w(res));
764
765     /* It's documented in the KB 330337 that IE has a bug and returns
766      * error DMLERR_NOTPROCESSED on XTYP_EXECUTE request.
767      */
768     if (unicode)
769         hDdeData = DdeClientTransaction((LPBYTE)res, (strlenW(res) + 1) * sizeof(WCHAR), hConv, 0L, 0,
770                                          XTYP_EXECUTE, 30000, &tid);
771     else
772     {
773         DWORD lenA = WideCharToMultiByte(CP_ACP, 0, res, -1, NULL, 0, NULL, NULL);
774         char *resA = HeapAlloc(GetProcessHeap(), 0, lenA);
775         WideCharToMultiByte(CP_ACP, 0, res, -1, resA, lenA, NULL, NULL);
776         hDdeData = DdeClientTransaction( (LPBYTE)resA, lenA, hConv, 0L, 0,
777                                          XTYP_EXECUTE, 10000, &tid );
778         HeapFree(GetProcessHeap(), 0, resA);
779     }
780     if (hDdeData)
781         DdeFreeDataHandle(hDdeData);
782     else
783         WARN("DdeClientTransaction failed with error %04x\n", DdeGetLastError(ddeInst));
784     ret = 33;
785
786     DdeDisconnect(hConv);
787
788  error:
789     DdeUninitialize(ddeInst);
790
791     return ret;
792 }
793
794 /*************************************************************************
795  *      execute_from_key [Internal]
796  */
797 static UINT_PTR execute_from_key(LPWSTR key, LPCWSTR lpFile, WCHAR *env, LPCWSTR szCommandline,
798                              LPCWSTR executable_name,
799                              SHELL_ExecuteW32 execfunc,
800                              LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
801 {
802     WCHAR cmd[256];
803     LONG cmdlen = sizeof(cmd);
804     UINT_PTR retval = 31;
805
806     TRACE("%s %s %s %s %s\n", debugstr_w(key), debugstr_w(lpFile), debugstr_w(env),
807            debugstr_w(szCommandline), debugstr_w(executable_name));
808
809     cmd[0] = '\0';
810
811     /* Get the application from the registry */
812     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, cmd, &cmdlen) == ERROR_SUCCESS)
813     {
814         WCHAR param[1024];
815
816         TRACE("got cmd: %s\n", debugstr_w(cmd));
817
818         param[0] = '\0';
819
820         /* Is there a replace() function anywhere? */
821         cmdlen /= sizeof(WCHAR);
822         cmd[cmdlen] = '\0';
823         if (!SHELL_ArgifyW(param, sizeof(param)/sizeof(WCHAR), cmd, lpFile, psei->lpIDList, szCommandline))
824         {
825             /* looks like there is no %1 param in the cmd, add one */
826             static const WCHAR oneW[] = { ' ','\"','%','1','\"',0 };
827             strcatW(cmd, oneW);
828             SHELL_ArgifyW(param, sizeof(param)/sizeof(WCHAR), cmd, lpFile, psei->lpIDList, szCommandline);
829         }
830         TRACE("executing: %s\n", debugstr_w(param));
831         retval = execfunc(param, env, FALSE, psei, psei_out);
832     }
833     else
834     {
835         static const WCHAR wCommand[] = {'c','o','m','m','a','n','d',0};
836         static const WCHAR wDdeexec[] = {'d','d','e','e','x','e','c',0};
837         LPWSTR tmp;
838         WCHAR param[256];
839         LONG paramlen = sizeof(param);
840
841         param[0] = '\0';
842
843         /* Get the parameters needed by the application
844            from the associated ddeexec key */
845         tmp = strstrW(key, wCommand);
846         assert(tmp);
847         strcpyW(tmp, wDdeexec);
848
849         TRACE("trying ddeexec cmd: %s\n", debugstr_w(key));
850
851         if (RegQueryValueW(HKEY_CLASSES_ROOT, key, param, &paramlen) == ERROR_SUCCESS)
852         {
853             TRACE("Got ddeexec %s => %s\n", debugstr_w(key), debugstr_w(param));
854             retval = dde_connect(key, executable_name, param, lpFile, env, szCommandline, psei->lpIDList, execfunc, psei, psei_out);
855         }
856         else
857             WARN("Nothing appropriate found for %s\n", debugstr_w(key));
858     }
859
860     return retval;
861 }
862
863 /*************************************************************************
864  * FindExecutableA                      [SHELL32.@]
865  */
866 HINSTANCE WINAPI FindExecutableA(LPCSTR lpFile, LPCSTR lpDirectory, LPSTR lpResult)
867 {
868     HINSTANCE retval;
869     WCHAR *wFile = NULL, *wDirectory = NULL;
870     WCHAR wResult[MAX_PATH];
871
872     if (lpFile) __SHCloneStrAtoW(&wFile, lpFile);
873     if (lpDirectory) __SHCloneStrAtoW(&wDirectory, lpDirectory);
874
875     retval = FindExecutableW(wFile, wDirectory, wResult);
876     WideCharToMultiByte(CP_ACP, 0, wResult, -1, lpResult, MAX_PATH, NULL, NULL);
877     if (wFile) SHFree( wFile );
878     if (wDirectory) SHFree( wDirectory );
879
880     TRACE("returning %s\n", lpResult);
881     return retval;
882 }
883
884 /*************************************************************************
885  * FindExecutableW                      [SHELL32.@]
886  */
887 HINSTANCE WINAPI FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, LPWSTR lpResult)
888 {
889     UINT_PTR retval = 31;    /* default - 'No association was found' */
890     WCHAR old_dir[1024];
891
892     TRACE("File %s, Dir %s\n",
893           (lpFile != NULL ? debugstr_w(lpFile) : "-"), (lpDirectory != NULL ? debugstr_w(lpDirectory) : "-"));
894
895     lpResult[0] = '\0'; /* Start off with an empty return string */
896
897     /* trap NULL parameters on entry */
898     if ((lpFile == NULL) || (lpResult == NULL))
899     {
900         /* FIXME - should throw a warning, perhaps! */
901         return (HINSTANCE)2; /* File not found. Close enough, I guess. */
902     }
903
904     if (lpDirectory)
905     {
906         GetCurrentDirectoryW(sizeof(old_dir)/sizeof(WCHAR), old_dir);
907         SetCurrentDirectoryW(lpDirectory);
908     }
909
910     retval = SHELL_FindExecutable(lpDirectory, lpFile, wszOpen, lpResult, MAX_PATH, NULL, NULL, NULL, NULL);
911
912     TRACE("returning %s\n", debugstr_w(lpResult));
913     if (lpDirectory)
914         SetCurrentDirectoryW(old_dir);
915     return (HINSTANCE)retval;
916 }
917
918 /* FIXME: is this already implemented somewhere else? */
919 static HKEY ShellExecute_GetClassKey( LPSHELLEXECUTEINFOW sei )
920 {
921     LPCWSTR ext = NULL, lpClass = NULL;
922     LPWSTR cls = NULL;
923     DWORD type = 0, sz = 0;
924     HKEY hkey = 0;
925     LONG r;
926
927     if (sei->fMask & SEE_MASK_CLASSALL)
928         return sei->hkeyClass;
929  
930     if (sei->fMask & SEE_MASK_CLASSNAME)
931         lpClass = sei->lpClass;
932     else
933     {
934         ext = PathFindExtensionW( sei->lpFile );
935         TRACE("ext = %s\n", debugstr_w( ext ) );
936         if (!ext)
937             return hkey;
938
939         r = RegOpenKeyW( HKEY_CLASSES_ROOT, ext, &hkey );
940         if (r != ERROR_SUCCESS )
941             return hkey;
942
943         r = RegQueryValueExW( hkey, NULL, 0, &type, NULL, &sz );
944         if ( r == ERROR_SUCCESS && type == REG_SZ )
945         {
946             sz += sizeof (WCHAR);
947             cls = HeapAlloc( GetProcessHeap(), 0, sz );
948             cls[0] = 0;
949             RegQueryValueExW( hkey, NULL, 0, &type, (LPBYTE) cls, &sz );
950         }
951
952         RegCloseKey( hkey );
953         lpClass = cls;
954     }
955
956     TRACE("class = %s\n", debugstr_w(lpClass) );
957
958     hkey = 0;
959     if ( lpClass )
960         RegOpenKeyW( HKEY_CLASSES_ROOT, lpClass, &hkey );
961
962     HeapFree( GetProcessHeap(), 0, cls );
963
964     return hkey;
965 }
966
967 static IDataObject *shellex_get_dataobj( LPSHELLEXECUTEINFOW sei )
968 {
969     LPCITEMIDLIST pidllast = NULL;
970     IDataObject *dataobj = NULL;
971     IShellFolder *shf = NULL;
972     LPITEMIDLIST pidl = NULL;
973     HRESULT r;
974
975     if (sei->fMask & SEE_MASK_CLASSALL)
976         pidl = sei->lpIDList;
977     else
978     {
979         WCHAR fullpath[MAX_PATH];
980
981         fullpath[0] = 0;
982         r = GetFullPathNameW( sei->lpFile, MAX_PATH, fullpath, NULL );
983         if (!r)
984             goto end;
985
986         pidl = ILCreateFromPathW( fullpath );
987     }
988
989     r = SHBindToParent( pidl, &IID_IShellFolder, (LPVOID*)&shf, &pidllast );
990     if ( FAILED( r ) )
991         goto end;
992
993     IShellFolder_GetUIObjectOf( shf, NULL, 1, &pidllast,
994                                 &IID_IDataObject, NULL, (LPVOID*) &dataobj );
995
996 end:
997     if ( pidl != sei->lpIDList )
998         ILFree( pidl );
999     if ( shf )
1000         IShellFolder_Release( shf );
1001     return dataobj;
1002 }
1003
1004 static HRESULT shellex_run_context_menu_default( IShellExtInit *obj,
1005                                                  LPSHELLEXECUTEINFOW sei )
1006 {
1007     IContextMenu *cm = NULL;
1008     CMINVOKECOMMANDINFOEX ici;
1009     MENUITEMINFOW info;
1010     WCHAR string[0x80];
1011     INT i, n, def = -1;
1012     HMENU hmenu = 0;
1013     HRESULT r;
1014
1015     TRACE("%p %p\n", obj, sei );
1016
1017     r = IShellExtInit_QueryInterface( obj, &IID_IContextMenu, (LPVOID*) &cm );
1018     if ( FAILED( r ) )
1019         return r;
1020
1021     hmenu = CreateMenu();
1022     if ( !hmenu )
1023         goto end;
1024
1025     /* the number of the last menu added is returned in r */
1026     r = IContextMenu_QueryContextMenu( cm, hmenu, 0, 0x20, 0x7fff, CMF_DEFAULTONLY );
1027     if ( FAILED( r ) )
1028         goto end;
1029
1030     n = GetMenuItemCount( hmenu );
1031     for ( i = 0; i < n; i++ )
1032     {
1033         memset( &info, 0, sizeof info );
1034         info.cbSize = sizeof info;
1035         info.fMask = MIIM_FTYPE | MIIM_STRING | MIIM_STATE | MIIM_DATA | MIIM_ID;
1036         info.dwTypeData = string;
1037         info.cch = sizeof string;
1038         string[0] = 0;
1039         GetMenuItemInfoW( hmenu, i, TRUE, &info );
1040
1041         TRACE("menu %d %s %08x %08lx %08x %08x\n", i, debugstr_w(string),
1042             info.fState, info.dwItemData, info.fType, info.wID );
1043         if ( ( !sei->lpVerb && (info.fState & MFS_DEFAULT) ) ||
1044              ( sei->lpVerb && !lstrcmpiW( sei->lpVerb, string ) ) )
1045         {
1046             def = i;
1047             break;
1048         }
1049     }
1050
1051     r = E_FAIL;
1052     if ( def == -1 )
1053         goto end;
1054
1055     memset( &ici, 0, sizeof ici );
1056     ici.cbSize = sizeof ici;
1057     ici.fMask = CMIC_MASK_UNICODE;
1058     ici.nShow = sei->nShow;
1059     ici.lpVerb = MAKEINTRESOURCEA( def );
1060     ici.hwnd = sei->hwnd;
1061     ici.lpParametersW = sei->lpParameters;
1062     
1063     r = IContextMenu_InvokeCommand( cm, (LPCMINVOKECOMMANDINFO) &ici );
1064
1065     TRACE("invoke command returned %08lx\n", r );
1066
1067 end:
1068     if ( hmenu )
1069         DestroyMenu( hmenu );
1070     if ( cm )
1071         IContextMenu_Release( cm );
1072     return r;
1073 }
1074
1075 static HRESULT shellex_load_object_and_run( HKEY hkey, LPCGUID guid, LPSHELLEXECUTEINFOW sei )
1076 {
1077     IDataObject *dataobj = NULL;
1078     IObjectWithSite *ows = NULL;
1079     IShellExtInit *obj = NULL;
1080     HRESULT r;
1081
1082     TRACE("%p %s %p\n", hkey, debugstr_guid( guid ), sei );
1083
1084     r = CoInitialize( NULL );
1085     if ( FAILED( r ) )
1086         goto end;
1087
1088     r = CoCreateInstance( guid, NULL, CLSCTX_INPROC_SERVER,
1089                            &IID_IShellExtInit, (LPVOID*)&obj );
1090     if ( FAILED( r ) )
1091     {
1092         ERR("failed %08lx\n", r );
1093         goto end;
1094     }
1095
1096     dataobj = shellex_get_dataobj( sei );
1097     if ( !dataobj )
1098     {
1099         ERR("failed to get data object\n");
1100         goto end;
1101     }
1102
1103     r = IShellExtInit_Initialize( obj, NULL, dataobj, hkey );
1104     if ( FAILED( r ) )
1105         goto end;
1106
1107     r = IShellExtInit_QueryInterface( obj, &IID_IObjectWithSite, (LPVOID*) &ows );
1108     if ( FAILED( r ) )
1109         goto end;
1110
1111     IObjectWithSite_SetSite( ows, NULL );
1112
1113     r = shellex_run_context_menu_default( obj, sei );
1114
1115 end:
1116     if ( ows )
1117         IObjectWithSite_Release( ows );
1118     if ( dataobj )
1119         IDataObject_Release( dataobj );
1120     if ( obj )
1121         IShellExtInit_Release( obj );
1122     CoUninitialize();
1123     return r;
1124 }
1125
1126
1127 /*************************************************************************
1128  *      ShellExecute_FromContextMenu [Internal]
1129  */
1130 static LONG ShellExecute_FromContextMenu( LPSHELLEXECUTEINFOW sei )
1131 {
1132     static const WCHAR szcm[] = { 's','h','e','l','l','e','x','\\',
1133         'C','o','n','t','e','x','t','M','e','n','u','H','a','n','d','l','e','r','s',0 };
1134     HKEY hkey, hkeycm = 0;
1135     WCHAR szguid[39];
1136     HRESULT hr;
1137     GUID guid;
1138     DWORD i;
1139     LONG r;
1140
1141     TRACE("%s\n", debugstr_w(sei->lpFile) );
1142
1143     hkey = ShellExecute_GetClassKey( sei );
1144     if ( !hkey )
1145         return ERROR_FUNCTION_FAILED;
1146
1147     r = RegOpenKeyW( hkey, szcm, &hkeycm );
1148     if ( r == ERROR_SUCCESS )
1149     {
1150         i = 0;
1151         while ( 1 )
1152         {
1153             r = RegEnumKeyW( hkeycm, i++, szguid, 39 );
1154             if ( r != ERROR_SUCCESS )
1155                 break;
1156
1157             hr = CLSIDFromString( szguid, &guid );
1158             if (SUCCEEDED(hr))
1159             {
1160                 /* stop at the first one that succeeds in running */
1161                 hr = shellex_load_object_and_run( hkey, &guid, sei );
1162                 if ( SUCCEEDED( hr ) )
1163                     break;
1164             }
1165         }
1166         RegCloseKey( hkeycm );
1167     }
1168
1169     if ( hkey != sei->hkeyClass )
1170         RegCloseKey( hkey );
1171     return r;
1172 }
1173
1174 /*************************************************************************
1175  *      SHELL_execute [Internal]
1176  */
1177 BOOL SHELL_execute( LPSHELLEXECUTEINFOW sei, SHELL_ExecuteW32 execfunc )
1178 {
1179     static const WCHAR wQuote[] = {'"',0};
1180     static const WCHAR wSpace[] = {' ',0};
1181     static const WCHAR wWww[] = {'w','w','w',0};
1182     static const WCHAR wFile[] = {'f','i','l','e',0};
1183     static const WCHAR wHttp[] = {'h','t','t','p',':','/','/',0};
1184     static const WCHAR wExplorer[] = {'e','x','p','l','o','r','e','r','.','e','x','e',0};
1185     static const DWORD unsupportedFlags =
1186         SEE_MASK_INVOKEIDLIST  | SEE_MASK_ICON         | SEE_MASK_HOTKEY |
1187         SEE_MASK_CONNECTNETDRV | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI |
1188         SEE_MASK_UNICODE       | SEE_MASK_NO_CONSOLE   | SEE_MASK_ASYNCOK |
1189         SEE_MASK_HMONITOR;
1190
1191     WCHAR *wszApplicationName, wszParameters[1024], wszDir[MAX_PATH];
1192     DWORD dwApplicationNameLen = MAX_PATH+2;
1193     SHELLEXECUTEINFOW sei_tmp;  /* modifiable copy of SHELLEXECUTEINFO struct */
1194     WCHAR wfileName[MAX_PATH];
1195     WCHAR *env;
1196     WCHAR lpstrProtocol[256];
1197     LPCWSTR lpFile;
1198     UINT_PTR retval = 31;
1199     WCHAR wcmd[1024];
1200     WCHAR buffer[MAX_PATH];
1201     BOOL done;
1202
1203     /* make a local copy of the LPSHELLEXECUTEINFO structure and work with this from now on */
1204     memcpy(&sei_tmp, sei, sizeof(sei_tmp));
1205
1206     TRACE("mask=0x%08lx hwnd=%p verb=%s file=%s parm=%s dir=%s show=0x%08x class=%s\n",
1207             sei_tmp.fMask, sei_tmp.hwnd, debugstr_w(sei_tmp.lpVerb),
1208             debugstr_w(sei_tmp.lpFile), debugstr_w(sei_tmp.lpParameters),
1209             debugstr_w(sei_tmp.lpDirectory), sei_tmp.nShow,
1210             ((sei_tmp.fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME) ?
1211                 debugstr_w(sei_tmp.lpClass) : "not used");
1212
1213     sei->hProcess = NULL;
1214
1215     /* make copies of all path/command strings */
1216     if (!sei_tmp.lpFile)
1217     {
1218         wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1219         *wszApplicationName = '\0';
1220     }
1221     else if (*sei_tmp.lpFile == '\"')
1222     {
1223         DWORD l = strlenW(sei_tmp.lpFile+1);
1224         if(l >= dwApplicationNameLen) dwApplicationNameLen = l+1;
1225         wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1226         memcpy(wszApplicationName, sei_tmp.lpFile+1, (l+1)*sizeof(WCHAR));
1227         if (wszApplicationName[l-1] == '\"')
1228             wszApplicationName[l-1] = '\0';
1229         TRACE("wszApplicationName=%s\n",debugstr_w(wszApplicationName));
1230     } else {
1231         DWORD l = strlenW(sei_tmp.lpFile)+1;
1232         if(l > dwApplicationNameLen) dwApplicationNameLen = l+1;
1233         wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1234         memcpy(wszApplicationName, sei_tmp.lpFile, l*sizeof(WCHAR));
1235     }
1236
1237     if (sei_tmp.lpParameters)
1238         strcpyW(wszParameters, sei_tmp.lpParameters);
1239     else
1240         *wszParameters = '\0';
1241
1242     if (sei_tmp.lpDirectory)
1243         strcpyW(wszDir, sei_tmp.lpDirectory);
1244     else
1245         *wszDir = '\0';
1246
1247     /* adjust string pointers to point to the new buffers */
1248     sei_tmp.lpFile = wszApplicationName;
1249     sei_tmp.lpParameters = wszParameters;
1250     sei_tmp.lpDirectory = wszDir;
1251
1252     if (sei_tmp.fMask & unsupportedFlags)
1253     {
1254         FIXME("flags ignored: 0x%08lx\n", sei_tmp.fMask & unsupportedFlags);
1255     }
1256
1257     /* process the IDList */
1258     if (sei_tmp.fMask & SEE_MASK_IDLIST)
1259     {
1260         IShellExecuteHookW* pSEH;
1261
1262         HRESULT hr = SHBindToParent(sei_tmp.lpIDList, &IID_IShellExecuteHookW, (LPVOID*)&pSEH, NULL);
1263
1264         if (SUCCEEDED(hr))
1265         {
1266             hr = IShellExecuteHookW_Execute(pSEH, &sei_tmp);
1267
1268             IShellExecuteHookW_Release(pSEH);
1269
1270             if (hr == S_OK) {
1271                 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1272                 return TRUE;
1273             }
1274         }
1275
1276         SHGetPathFromIDListW(sei_tmp.lpIDList, wszApplicationName);
1277         TRACE("-- idlist=%p (%s)\n", sei_tmp.lpIDList, debugstr_w(wszApplicationName));
1278     }
1279
1280     if ( ERROR_SUCCESS == ShellExecute_FromContextMenu( &sei_tmp ) )
1281     {
1282         sei->hInstApp = (HINSTANCE) 33;
1283         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1284         return TRUE;
1285     }
1286
1287     if (sei_tmp.fMask & SEE_MASK_CLASSALL)
1288     {
1289         /* launch a document by fileclass like 'WordPad.Document.1' */
1290         /* the Commandline contains 'c:\Path\wordpad.exe "%1"' */
1291         /* FIXME: szCommandline should not be of a fixed size. Fixed to 1024, MAX_PATH is way too short! */
1292         ULONG cmask=(sei_tmp.fMask & SEE_MASK_CLASSALL);
1293         HCR_GetExecuteCommandW((cmask == SEE_MASK_CLASSKEY) ? sei_tmp.hkeyClass : NULL,
1294                                (cmask == SEE_MASK_CLASSNAME) ? sei_tmp.lpClass: NULL,
1295                                (sei_tmp.lpVerb) ? sei_tmp.lpVerb : wszOpen,
1296                                wszParameters, sizeof(wszParameters)/sizeof(WCHAR));
1297
1298         /* FIXME: get the extension of lpFile, check if it fits to the lpClass */
1299         TRACE("SEE_MASK_CLASSNAME->'%s', doc->'%s'\n", debugstr_w(wszParameters), debugstr_w(wszApplicationName));
1300
1301         wcmd[0] = '\0';
1302         done = SHELL_ArgifyW(wcmd, sizeof(wcmd)/sizeof(WCHAR), wszParameters, wszApplicationName, sei_tmp.lpIDList, NULL);
1303         if (!done && wszApplicationName[0])
1304         {
1305             strcatW(wcmd, wSpace);
1306             strcatW(wcmd, wszApplicationName);
1307         }
1308         retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
1309
1310         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1311         return retval > 32;
1312     }
1313
1314     /* Has the IDList not yet been translated? */
1315     if (sei_tmp.fMask & SEE_MASK_IDLIST)
1316     {
1317         /* last chance to translate IDList: now also allow CLSID paths */
1318         if (SUCCEEDED(SHELL_GetPathFromIDListForExecuteW(sei_tmp.lpIDList, buffer, sizeof(buffer)))) {
1319             if (buffer[0]==':' && buffer[1]==':') {
1320                 /* open shell folder for the specified class GUID */
1321                 strcpyW(wszParameters, buffer);
1322                 strcpyW(wszApplicationName, wExplorer);
1323
1324                 sei_tmp.fMask &= ~SEE_MASK_INVOKEIDLIST;
1325             } else {
1326                 WCHAR target[MAX_PATH];
1327                 DWORD attribs;
1328                 /* Check if we're executing a directory and if so use the
1329                    handler for the Folder class */
1330                 strcpyW(target, buffer);
1331                 attribs = GetFileAttributesW(buffer);
1332                 if (attribs != INVALID_FILE_ATTRIBUTES &&
1333                     (attribs & FILE_ATTRIBUTE_DIRECTORY) &&
1334                     HCR_GetExecuteCommandW(0, wszFolder,
1335                                            sei_tmp.lpVerb?sei_tmp.lpVerb:wszOpen,
1336                                            buffer, sizeof(buffer))) {
1337                     SHELL_ArgifyW(wszApplicationName, dwApplicationNameLen,
1338                                   buffer, target, sei_tmp.lpIDList, NULL);
1339                 }
1340                 sei_tmp.fMask &= ~SEE_MASK_INVOKEIDLIST;
1341             }
1342         }
1343     }
1344
1345     /* expand environment strings */
1346     if (ExpandEnvironmentStringsW(sei_tmp.lpFile, buffer, MAX_PATH))
1347         lstrcpyW(wszApplicationName, buffer);
1348
1349     if (*sei_tmp.lpParameters)
1350         if (ExpandEnvironmentStringsW(sei_tmp.lpParameters, buffer, MAX_PATH))
1351             lstrcpyW(wszParameters, buffer);
1352
1353     if (*sei_tmp.lpDirectory)
1354         if (ExpandEnvironmentStringsW(sei_tmp.lpDirectory, buffer, MAX_PATH))
1355             lstrcpyW(wszDir, buffer);
1356
1357     /* Else, try to execute the filename */
1358     TRACE("execute:%s,%s,%s\n", debugstr_w(wszApplicationName), debugstr_w(wszParameters), debugstr_w(wszDir));
1359
1360     /* separate out command line arguments from executable file name */
1361     if (!*sei_tmp.lpParameters) {
1362         /* If the executable path is quoted, handle the rest of the command line as parameters. */
1363         if (sei_tmp.lpFile[0] == '"') {
1364             LPWSTR src = wszApplicationName/*sei_tmp.lpFile*/ + 1;
1365             LPWSTR dst = wfileName;
1366             LPWSTR end;
1367
1368             /* copy the unquoted executable path to 'wfileName' */
1369             while(*src && *src!='"')
1370                 *dst++ = *src++;
1371
1372             *dst = '\0';
1373
1374             if (*src == '"') {
1375                 end = ++src;
1376
1377                 while(isspace(*src))
1378                     ++src;
1379             } else
1380                 end = src;
1381
1382             /* copy the parameter string to 'wszParameters' */
1383             strcpyW(wszParameters, src);
1384
1385             /* terminate previous command string after the quote character */
1386             *end = '\0';
1387         }
1388         else
1389         {
1390             /* If the executable name is not quoted, we have to use this search loop here,
1391                that in CreateProcess() is not sufficient because it does not handle shell links. */
1392             WCHAR buffer[MAX_PATH], xlpFile[MAX_PATH];
1393             LPWSTR space, s;
1394
1395             LPWSTR beg = wszApplicationName/*sei_tmp.lpFile*/;
1396             for(s=beg; (space=strchrW(s, ' ')); s=space+1) {
1397                 int idx = space-sei_tmp.lpFile;
1398                 memcpy(buffer, sei_tmp.lpFile, idx * sizeof(WCHAR));
1399                 buffer[idx] = '\0';
1400
1401                 /*FIXME This finds directory paths if the targeted file name contains spaces. */
1402                 if (SearchPathW(*sei_tmp.lpDirectory? sei_tmp.lpDirectory: NULL, buffer, wszExe, sizeof(xlpFile), xlpFile, NULL))
1403                 {
1404                     /* separate out command from parameter string */
1405                     LPCWSTR p = space + 1;
1406
1407                     while(isspaceW(*p))
1408                         ++p;
1409
1410                     strcpyW(wszParameters, p);
1411                     *space = '\0';
1412
1413                     break;
1414                 }
1415             }
1416
1417             strcpyW(wfileName, sei_tmp.lpFile);
1418         }
1419     } else
1420         strcpyW(wfileName, sei_tmp.lpFile);
1421
1422     lpFile = wfileName;
1423
1424     strcpyW(wcmd, wszApplicationName);
1425     if (sei_tmp.lpParameters[0]) {
1426         strcatW(wcmd, wSpace);
1427         strcatW(wcmd, wszParameters);
1428     }
1429
1430     /* We set the default to open, and that should generally work.
1431        But that is not really the way the MS docs say to do it. */
1432     if (!sei_tmp.lpVerb)
1433         sei_tmp.lpVerb = wszOpen;
1434
1435     retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
1436     if (retval > 32) {
1437         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1438         return TRUE;
1439     }
1440
1441     /* Else, try to find the executable */
1442     wcmd[0] = '\0';
1443     retval = SHELL_FindExecutable(sei_tmp.lpDirectory, lpFile, sei_tmp.lpVerb, wcmd, 1024, lpstrProtocol, &env, sei_tmp.lpIDList, sei_tmp.lpParameters);
1444     if (retval > 32)  /* Found */
1445     {
1446         WCHAR wszQuotedCmd[MAX_PATH+2];
1447         /* Must quote to handle case where cmd contains spaces,
1448          * else security hole if malicious user creates executable file "C:\\Program"
1449          */
1450         strcpyW(wszQuotedCmd, wQuote);
1451         strcatW(wszQuotedCmd, wcmd);
1452         strcatW(wszQuotedCmd, wQuote);
1453         if (wszParameters[0]) {
1454             strcatW(wszQuotedCmd, wSpace);
1455             strcatW(wszQuotedCmd, wszParameters);
1456         }
1457         TRACE("%s/%s => %s/%s\n", debugstr_w(wszApplicationName), debugstr_w(sei_tmp.lpVerb), debugstr_w(wszQuotedCmd), debugstr_w(lpstrProtocol));
1458         if (*lpstrProtocol)
1459             retval = execute_from_key(lpstrProtocol, wszApplicationName, env, sei_tmp.lpParameters, wcmd, execfunc, &sei_tmp, sei);
1460         else
1461             retval = execfunc(wszQuotedCmd, env, FALSE, &sei_tmp, sei);
1462         HeapFree( GetProcessHeap(), 0, env );
1463     }
1464     else if (PathIsURLW((LPWSTR)lpFile))    /* File not found, check for URL */
1465     {
1466         static const WCHAR wShell[] = {'\\','s','h','e','l','l','\\',0};
1467         static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
1468         LPWSTR lpstrRes;
1469         INT iSize;
1470
1471         lpstrRes = strchrW(lpFile, ':');
1472         if (lpstrRes)
1473             iSize = lpstrRes - lpFile;
1474         else
1475             iSize = strlenW(lpFile);
1476
1477         TRACE("Got URL: %s\n", debugstr_w(lpFile));
1478         /* Looking for ...protocol\shell\lpOperation\command */
1479         memcpy(lpstrProtocol, lpFile, iSize*sizeof(WCHAR));
1480         lpstrProtocol[iSize] = '\0';
1481         strcatW(lpstrProtocol, wShell);
1482         strcatW(lpstrProtocol, sei_tmp.lpVerb? sei_tmp.lpVerb: wszOpen);
1483         strcatW(lpstrProtocol, wCommand);
1484
1485         /* Remove File Protocol from lpFile */
1486         /* In the case file://path/file     */
1487         if (!strncmpiW(lpFile, wFile, iSize))
1488         {
1489             lpFile += iSize;
1490             while (*lpFile == ':') lpFile++;
1491         }
1492         retval = execute_from_key(lpstrProtocol, lpFile, NULL, sei_tmp.lpParameters, wcmd, execfunc, &sei_tmp, sei);
1493     }
1494     /* Check if file specified is in the form www.??????.*** */
1495     else if (!strncmpiW(lpFile, wWww, 3))
1496     {
1497         /* if so, append lpFile http:// and call ShellExecute */
1498         WCHAR lpstrTmpFile[256];
1499         strcpyW(lpstrTmpFile, wHttp);
1500         strcatW(lpstrTmpFile, lpFile);
1501         retval = (UINT_PTR)ShellExecuteW(sei_tmp.hwnd, sei_tmp.lpVerb, lpstrTmpFile, NULL, NULL, 0);
1502     }
1503
1504     TRACE("retval %u\n", retval);
1505
1506     HeapFree(GetProcessHeap(), 0, wszApplicationName);
1507
1508     sei->hInstApp = (HINSTANCE)(retval > 32 ? 33 : retval);
1509     return retval > 32;
1510 }
1511
1512 /*************************************************************************
1513  * ShellExecuteA                        [SHELL32.290]
1514  */
1515 HINSTANCE WINAPI ShellExecuteA(HWND hWnd, LPCSTR lpOperation,LPCSTR lpFile,
1516                                LPCSTR lpParameters,LPCSTR lpDirectory, INT iShowCmd)
1517 {
1518     SHELLEXECUTEINFOA sei;
1519
1520     TRACE("%p,%s,%s,%s,%s,%d\n",
1521           hWnd, debugstr_a(lpOperation), debugstr_a(lpFile),
1522           debugstr_a(lpParameters), debugstr_a(lpDirectory), iShowCmd);
1523
1524     sei.cbSize = sizeof(sei);
1525     sei.fMask = 0;
1526     sei.hwnd = hWnd;
1527     sei.lpVerb = lpOperation;
1528     sei.lpFile = lpFile;
1529     sei.lpParameters = lpParameters;
1530     sei.lpDirectory = lpDirectory;
1531     sei.nShow = iShowCmd;
1532     sei.lpIDList = 0;
1533     sei.lpClass = 0;
1534     sei.hkeyClass = 0;
1535     sei.dwHotKey = 0;
1536     sei.hProcess = 0;
1537
1538     ShellExecuteExA (&sei);
1539     return sei.hInstApp;
1540 }
1541
1542 /*************************************************************************
1543  * ShellExecuteExA                              [SHELL32.292]
1544  *
1545  */
1546 BOOL WINAPI ShellExecuteExA (LPSHELLEXECUTEINFOA sei)
1547 {
1548     SHELLEXECUTEINFOW seiW;
1549     BOOL ret;
1550     WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL, *wClass = NULL;
1551
1552     TRACE("%p\n", sei);
1553
1554     memcpy(&seiW, sei, sizeof(SHELLEXECUTEINFOW));
1555
1556     if (sei->lpVerb)
1557         seiW.lpVerb = __SHCloneStrAtoW(&wVerb, sei->lpVerb);
1558
1559     if (sei->lpFile)
1560         seiW.lpFile = __SHCloneStrAtoW(&wFile, sei->lpFile);
1561
1562     if (sei->lpParameters)
1563         seiW.lpParameters = __SHCloneStrAtoW(&wParameters, sei->lpParameters);
1564
1565     if (sei->lpDirectory)
1566         seiW.lpDirectory = __SHCloneStrAtoW(&wDirectory, sei->lpDirectory);
1567
1568     if ((sei->fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME && sei->lpClass)
1569         seiW.lpClass = __SHCloneStrAtoW(&wClass, sei->lpClass);
1570     else
1571         seiW.lpClass = NULL;
1572
1573     ret = SHELL_execute( &seiW, SHELL_ExecuteW );
1574
1575     sei->hInstApp = seiW.hInstApp;
1576
1577     if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
1578         sei->hProcess = seiW.hProcess;
1579
1580     if (wVerb) SHFree(wVerb);
1581     if (wFile) SHFree(wFile);
1582     if (wParameters) SHFree(wParameters);
1583     if (wDirectory) SHFree(wDirectory);
1584     if (wClass) SHFree(wClass);
1585
1586     return ret;
1587 }
1588
1589 /*************************************************************************
1590  * ShellExecuteExW                              [SHELL32.293]
1591  *
1592  */
1593 BOOL WINAPI ShellExecuteExW (LPSHELLEXECUTEINFOW sei)
1594 {
1595     return SHELL_execute( sei, SHELL_ExecuteW );
1596 }
1597
1598 /*************************************************************************
1599  * ShellExecuteW                        [SHELL32.294]
1600  * from shellapi.h
1601  * WINSHELLAPI HINSTANCE APIENTRY ShellExecuteW(HWND hwnd, LPCWSTR lpOperation,
1602  * LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd);
1603  */
1604 HINSTANCE WINAPI ShellExecuteW(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile,
1605                                LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd)
1606 {
1607     SHELLEXECUTEINFOW sei;
1608
1609     TRACE("\n");
1610     sei.cbSize = sizeof(sei);
1611     sei.fMask = 0;
1612     sei.hwnd = hwnd;
1613     sei.lpVerb = lpOperation;
1614     sei.lpFile = lpFile;
1615     sei.lpParameters = lpParameters;
1616     sei.lpDirectory = lpDirectory;
1617     sei.nShow = nShowCmd;
1618     sei.lpIDList = 0;
1619     sei.lpClass = 0;
1620     sei.hkeyClass = 0;
1621     sei.dwHotKey = 0;
1622     sei.hProcess = 0;
1623
1624     SHELL_execute( &sei, SHELL_ExecuteW );
1625     return sei.hInstApp;
1626 }