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