windowscodecs: Implement IWICBitmapScaler::Initialize.
[wine] / programs / cmd / batch.c
1 /*
2  * CMD - Wine-compatible command line interface - batch interface.
3  *
4  * Copyright (C) 1999 D A Pickles
5  * Copyright (C) 2007 J Edmeades
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 "wcmd.h"
23 #include "wine/debug.h"
24
25 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
26
27 /****************************************************************************
28  * WCMD_batch
29  *
30  * Open and execute a batch file.
31  * On entry *command includes the complete command line beginning with the name
32  * of the batch file (if a CALL command was entered the CALL has been removed).
33  * *file is the name of the file, which might not exist and may not have the
34  * .BAT suffix on. Called is 1 for a CALL, 0 otherwise.
35  *
36  * We need to handle recursion correctly, since one batch program might call another.
37  * So parameters for this batch file are held in a BATCH_CONTEXT structure.
38  *
39  * To support call within the same batch program, another input parameter is
40  * a label to goto once opened.
41  */
42
43 void WCMD_batch (WCHAR *file, WCHAR *command, BOOL called, WCHAR *startLabel, HANDLE pgmHandle)
44 {
45   HANDLE h = INVALID_HANDLE_VALUE;
46   BATCH_CONTEXT *prev_context;
47
48   if (startLabel == NULL) {
49     h = CreateFileW (file, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
50                      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
51     if (h == INVALID_HANDLE_VALUE) {
52       SetLastError (ERROR_FILE_NOT_FOUND);
53       WCMD_print_error ();
54       return;
55     }
56   } else {
57     DuplicateHandle(GetCurrentProcess(), pgmHandle,
58                     GetCurrentProcess(), &h,
59                     0, FALSE, DUPLICATE_SAME_ACCESS);
60   }
61
62 /*
63  *      Create a context structure for this batch file.
64  */
65
66   prev_context = context;
67   context = LocalAlloc (LMEM_FIXED, sizeof (BATCH_CONTEXT));
68   context -> h = h;
69   context->batchfileW = WCMD_strdupW(file);
70   context -> command = command;
71   memset(context -> shift_count, 0x00, sizeof(context -> shift_count));
72   context -> prev_context = prev_context;
73   context -> skip_rest = FALSE;
74
75   /* If processing a call :label, 'goto' the label in question */
76   if (startLabel) {
77     strcpyW(param1, startLabel);
78     WCMD_goto(NULL);
79   }
80
81 /*
82  *      Work through the file line by line. Specific batch commands are processed here,
83  *      the rest are handled by the main command processor.
84  */
85
86   while (context -> skip_rest == FALSE) {
87       CMD_LIST *toExecute = NULL;         /* Commands left to be executed */
88       if (!WCMD_ReadAndParseLine(NULL, &toExecute, h))
89         break;
90       WCMD_process_commands(toExecute, FALSE, NULL, NULL);
91       WCMD_free_commands(toExecute);
92       toExecute = NULL;
93   }
94   CloseHandle (h);
95
96 /*
97  *      If invoked by a CALL, we return to the context of our caller. Otherwise return
98  *      to the caller's caller.
99  */
100
101   HeapFree(GetProcessHeap(), 0, context->batchfileW);
102   LocalFree (context);
103   if ((prev_context != NULL) && (!called)) {
104     prev_context -> skip_rest = TRUE;
105     context = prev_context;
106   }
107   context = prev_context;
108 }
109
110 /*******************************************************************
111  * WCMD_parameter
112  *
113  * Extracts a delimited parameter from an input string
114  *
115  * PARAMS
116  *  s     [I] input string, non NULL
117  *  n     [I] # of the parameter to return, counted from 0
118  *  start [O] Optional. Pointer to the first char of param n in s
119  *  end   [O] Optional. Pointer to the last char of param n in s
120  *
121  * RETURNS
122  *  Success: The nth delimited parameter found in s, with any surrounding quotes removed
123  *           if start != NULL, *start points to the start of the param
124  *           if end != NULL, *end points to the end of the param
125  *  Failure: An empty string if the param is not found.
126  *           *start == *end == NULL
127  *
128  * NOTES
129  *  Return value is stored in static storage (i.e. overwritten after each call).
130  *  Specify 'start' and/or 'end' to include delimiting double quotes as well, if any.
131  */
132 WCHAR *WCMD_parameter (WCHAR *s, int n, WCHAR **start, WCHAR **end)
133 {
134     int curParamNb = 0;
135     static WCHAR param[MAX_PATH];
136     WCHAR *p = s, *q;
137     BOOL quotesDelimited;
138
139     if (start != NULL) *start = NULL;
140     if (end != NULL) *end = NULL;
141     param[0] = '\0';
142     while (TRUE) {
143         while (*p && ((*p == ' ') || (*p == ',') || (*p == '=') || (*p == '\t')))
144             p++;
145         if (*p == '\0') return param;
146
147         quotesDelimited = (*p == '"');
148         if (start != NULL && curParamNb == n) *start = p;
149
150         if (quotesDelimited) {
151             q = ++p;
152             while (*p && *p != '"') p++;
153         } else {
154             q = p;
155             while (*p && (*p != ' ') && (*p != ',') && (*p != '=') && (*p != '\t'))
156                 p++;
157         }
158         if (curParamNb == n) {
159             memcpy(param, q, (p - q) * sizeof(WCHAR));
160             param[p-q] = '\0';
161             if (end) *end = p - 1 + quotesDelimited;
162             return param;
163         }
164         if (quotesDelimited && *p == '"') p++;
165         curParamNb++;
166     }
167 }
168
169 /****************************************************************************
170  * WCMD_fgets
171  *
172  * Gets one line from a file/console and puts it into buffer buf
173  * Pre:  buf has size noChars
174  *       1 <= noChars <= MAXSTRING
175  * Post: buf is filled with at most noChars-1 characters, and gets nul-terminated
176          buf does not include EOL terminator
177  * Returns:
178  *       buf on success
179  *       NULL on error or EOF
180  */
181
182 WCHAR *WCMD_fgets(WCHAR *buf, DWORD noChars, HANDLE h)
183 {
184   DWORD charsRead;
185   BOOL status;
186   LARGE_INTEGER filepos;
187   DWORD i;
188
189   /* We can't use the native f* functions because of the filename syntax differences
190      between DOS and Unix. Also need to lose the LF (or CRLF) from the line. */
191
192   if (!WCMD_is_console_handle(h)) {
193     /* Save current file position */
194     filepos.QuadPart = 0;
195     SetFilePointerEx(h, filepos, &filepos, FILE_CURRENT);
196   }
197
198   status = WCMD_ReadFile(h, buf, noChars, &charsRead);
199   if (!status || charsRead == 0) return NULL;
200
201   /* Find first EOL */
202   for (i = 0; i < charsRead; i++) {
203     if (buf[i] == '\n' || buf[i] == '\r')
204       break;
205   }
206
207   if (!WCMD_is_console_handle(h) && i != charsRead) {
208     /* Sets file pointer to the start of the next line, if any */
209     filepos.QuadPart += i + 1 + (buf[i] == '\r' ? 1 : 0);
210     SetFilePointerEx(h, filepos, NULL, FILE_BEGIN);
211   }
212
213   /* Truncate at EOL (or end of buffer) */
214   if (i == noChars)
215     i--;
216
217   buf[i] = '\0';
218
219   return buf;
220 }
221
222 /* WCMD_splitpath - copied from winefile as no obvious way to use it otherwise */
223 void WCMD_splitpath(const WCHAR* path, WCHAR* drv, WCHAR* dir, WCHAR* name, WCHAR* ext)
224 {
225         const WCHAR* end; /* end of processed string */
226         const WCHAR* p;  /* search pointer */
227         const WCHAR* s;  /* copy pointer */
228
229         /* extract drive name */
230         if (path[0] && path[1]==':') {
231                 if (drv) {
232                         *drv++ = *path++;
233                         *drv++ = *path++;
234                         *drv = '\0';
235                 }
236         } else if (drv)
237                 *drv = '\0';
238
239         end = path + strlenW(path);
240
241         /* search for begin of file extension */
242         for(p=end; p>path && *--p!='\\' && *p!='/'; )
243                 if (*p == '.') {
244                         end = p;
245                         break;
246                 }
247
248         if (ext)
249                 for(s=end; (*ext=*s++); )
250                         ext++;
251
252         /* search for end of directory name */
253         for(p=end; p>path; )
254                 if (*--p=='\\' || *p=='/') {
255                         p++;
256                         break;
257                 }
258
259         if (name) {
260                 for(s=p; s<end; )
261                         *name++ = *s++;
262
263                 *name = '\0';
264         }
265
266         if (dir) {
267                 for(s=path; s<p; )
268                         *dir++ = *s++;
269
270                 *dir = '\0';
271         }
272 }
273
274 /****************************************************************************
275  * WCMD_HandleTildaModifiers
276  *
277  * Handle the ~ modifiers when expanding %0-9 or (%a-z in for command)
278  *    %~xxxxxV  (V=0-9 or A-Z)
279  * Where xxxx is any combination of:
280  *    ~ - Removes quotes
281  *    f - Fully qualified path (assumes current dir if not drive\dir)
282  *    d - drive letter
283  *    p - path
284  *    n - filename
285  *    x - file extension
286  *    s - path with shortnames
287  *    a - attributes
288  *    t - date/time
289  *    z - size
290  *    $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully
291  *                   qualified path
292  *
293  *  To work out the length of the modifier:
294  *
295  *  Note: In the case of %0-9 knowing the end of the modifier is easy,
296  *    but in a for loop, the for end WCHARacter may also be a modifier
297  *    eg. for %a in (c:\a.a) do echo XXX
298  *             where XXX = %~a    (just ~)
299  *                         %~aa   (~ and attributes)
300  *                         %~aaxa (~, attributes and extension)
301  *                   BUT   %~aax  (~ and attributes followed by 'x')
302  *
303  *  Hence search forwards until find an invalid modifier, and then
304  *  backwards until find for variable or 0-9
305  */
306 void WCMD_HandleTildaModifiers(WCHAR **start, const WCHAR *forVariable,
307                                const WCHAR *forValue, BOOL justFors) {
308
309 #define NUMMODIFIERS 11
310   static const WCHAR validmodifiers[NUMMODIFIERS] = {
311         '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
312   };
313
314   WIN32_FILE_ATTRIBUTE_DATA fileInfo;
315   WCHAR  outputparam[MAX_PATH];
316   WCHAR  finaloutput[MAX_PATH];
317   WCHAR  fullfilename[MAX_PATH];
318   WCHAR  thisoutput[MAX_PATH];
319   WCHAR  *pos            = *start+1;
320   WCHAR  *firstModifier  = pos;
321   WCHAR  *lastModifier   = NULL;
322   int   modifierLen     = 0;
323   BOOL  finished        = FALSE;
324   int   i               = 0;
325   BOOL  exists          = TRUE;
326   BOOL  skipFileParsing = FALSE;
327   BOOL  doneModifier    = FALSE;
328
329   /* Search forwards until find invalid character modifier */
330   while (!finished) {
331
332     /* Work on the previous character */
333     if (lastModifier != NULL) {
334
335       for (i=0; i<NUMMODIFIERS; i++) {
336         if (validmodifiers[i] == *lastModifier) {
337
338           /* Special case '$' to skip until : found */
339           if (*lastModifier == '$') {
340             while (*pos != ':' && *pos) pos++;
341             if (*pos == 0x00) return; /* Invalid syntax */
342             pos++;                    /* Skip ':'       */
343           }
344           break;
345         }
346       }
347
348       if (i==NUMMODIFIERS) {
349         finished = TRUE;
350       }
351     }
352
353     /* Save this one away */
354     if (!finished) {
355       lastModifier = pos;
356       pos++;
357     }
358   }
359
360   while (lastModifier > firstModifier) {
361     WINE_TRACE("Looking backwards for parameter id: %s / %s\n",
362                wine_dbgstr_w(lastModifier), wine_dbgstr_w(forVariable));
363
364     if (!justFors && context && (*lastModifier >= '0' && *lastModifier <= '9')) {
365       /* Its a valid parameter identifier - OK */
366       break;
367
368     } else if (forVariable && *lastModifier == *(forVariable+1)) {
369       /* Its a valid parameter identifier - OK */
370       break;
371
372     } else {
373       lastModifier--;
374     }
375   }
376   if (lastModifier == firstModifier) return; /* Invalid syntax */
377
378   /* Extract the parameter to play with */
379   if (*lastModifier == '0') {
380     strcpyW(outputparam, context->batchfileW);
381   } else if ((*lastModifier >= '1' && *lastModifier <= '9')) {
382     strcpyW(outputparam,
383             WCMD_parameter (context -> command, *lastModifier-'0' + context -> shift_count[*lastModifier-'0'],
384                             NULL, NULL));
385   } else {
386     strcpyW(outputparam, forValue);
387   }
388
389   /* So now, firstModifier points to beginning of modifiers, lastModifier
390      points to the variable just after the modifiers. Process modifiers
391      in a specific order, remembering there could be duplicates           */
392   modifierLen = lastModifier - firstModifier;
393   finaloutput[0] = 0x00;
394
395   /* Useful for debugging purposes: */
396   /*printf("Modifier string '%*.*s' and variable is %c\n Param starts as '%s'\n",
397              (modifierLen), (modifierLen), firstModifier, *lastModifier,
398              outputparam);*/
399
400   /* 1. Handle '~' : Strip surrounding quotes */
401   if (outputparam[0]=='"' &&
402       memchrW(firstModifier, '~', modifierLen) != NULL) {
403     int len = strlenW(outputparam);
404     if (outputparam[len-1] == '"') {
405         outputparam[len-1]=0x00;
406         len = len - 1;
407     }
408     memmove(outputparam, &outputparam[1], (len * sizeof(WCHAR))-1);
409   }
410
411   /* 2. Handle the special case of a $ */
412   if (memchrW(firstModifier, '$', modifierLen) != NULL) {
413     /* Special Case: Search envar specified in $[envvar] for outputparam
414        Note both $ and : are guaranteed otherwise check above would fail */
415     WCHAR *begin = strchrW(firstModifier, '$') + 1;
416     WCHAR *end   = strchrW(firstModifier, ':');
417     WCHAR env[MAX_PATH];
418     WCHAR fullpath[MAX_PATH];
419
420     /* Extract the env var */
421     memcpy(env, begin, (end-begin) * sizeof(WCHAR));
422     env[(end-begin)] = 0x00;
423
424     /* If env var not found, return empty string */
425     if ((GetEnvironmentVariableW(env, fullpath, MAX_PATH) == 0) ||
426         (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0)) {
427       finaloutput[0] = 0x00;
428       outputparam[0] = 0x00;
429       skipFileParsing = TRUE;
430     }
431   }
432
433   /* After this, we need full information on the file,
434     which is valid not to exist.  */
435   if (!skipFileParsing) {
436     if (GetFullPathNameW(outputparam, MAX_PATH, fullfilename, NULL) == 0)
437       return;
438
439     exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard,
440                                   &fileInfo);
441
442     /* 2. Handle 'a' : Output attributes */
443     if (exists &&
444         memchrW(firstModifier, 'a', modifierLen) != NULL) {
445
446       WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'};
447       doneModifier = TRUE;
448       strcpyW(thisoutput, defaults);
449       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
450         thisoutput[0]='d';
451       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
452         thisoutput[1]='r';
453       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
454         thisoutput[2]='a';
455       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
456         thisoutput[3]='h';
457       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
458         thisoutput[4]='s';
459       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)
460         thisoutput[5]='c';
461       /* FIXME: What are 6 and 7? */
462       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
463         thisoutput[8]='l';
464       strcatW(finaloutput, thisoutput);
465     }
466
467     /* 3. Handle 't' : Date+time */
468     if (exists &&
469         memchrW(firstModifier, 't', modifierLen) != NULL) {
470
471       SYSTEMTIME systime;
472       int datelen;
473
474       doneModifier = TRUE;
475       if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
476
477       /* Format the time */
478       FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime);
479       GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime,
480                         NULL, thisoutput, MAX_PATH);
481       strcatW(thisoutput, spaceW);
482       datelen = strlenW(thisoutput);
483       GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime,
484                         NULL, (thisoutput+datelen), MAX_PATH-datelen);
485       strcatW(finaloutput, thisoutput);
486     }
487
488     /* 4. Handle 'z' : File length */
489     if (exists &&
490         memchrW(firstModifier, 'z', modifierLen) != NULL) {
491       /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */
492       ULONG/*64*/ fullsize = /*(fileInfo.nFileSizeHigh << 32) +*/
493                                   fileInfo.nFileSizeLow;
494       static const WCHAR fmt[] = {'%','u','\0'};
495
496       doneModifier = TRUE;
497       if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
498       wsprintfW(thisoutput, fmt, fullsize);
499       strcatW(finaloutput, thisoutput);
500     }
501
502     /* 4. Handle 's' : Use short paths (File doesn't have to exist) */
503     if (memchrW(firstModifier, 's', modifierLen) != NULL) {
504       if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
505       /* Don't flag as doneModifier - %~s on its own is processed later */
506       GetShortPathNameW(outputparam, outputparam, sizeof(outputparam)/sizeof(outputparam[0]));
507     }
508
509     /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */
510     /*      Note this overrides d,p,n,x                                 */
511     if (memchrW(firstModifier, 'f', modifierLen) != NULL) {
512       doneModifier = TRUE;
513       if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
514       strcatW(finaloutput, fullfilename);
515     } else {
516
517       WCHAR drive[10];
518       WCHAR dir[MAX_PATH];
519       WCHAR fname[MAX_PATH];
520       WCHAR ext[MAX_PATH];
521       BOOL doneFileModifier = FALSE;
522
523       if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
524
525       /* Split into components */
526       WCMD_splitpath(fullfilename, drive, dir, fname, ext);
527
528       /* 5. Handle 'd' : Drive Letter */
529       if (memchrW(firstModifier, 'd', modifierLen) != NULL) {
530         strcatW(finaloutput, drive);
531         doneModifier = TRUE;
532         doneFileModifier = TRUE;
533       }
534
535       /* 6. Handle 'p' : Path */
536       if (memchrW(firstModifier, 'p', modifierLen) != NULL) {
537         strcatW(finaloutput, dir);
538         doneModifier = TRUE;
539         doneFileModifier = TRUE;
540       }
541
542       /* 7. Handle 'n' : Name */
543       if (memchrW(firstModifier, 'n', modifierLen) != NULL) {
544         strcatW(finaloutput, fname);
545         doneModifier = TRUE;
546         doneFileModifier = TRUE;
547       }
548
549       /* 8. Handle 'x' : Ext */
550       if (memchrW(firstModifier, 'x', modifierLen) != NULL) {
551         strcatW(finaloutput, ext);
552         doneModifier = TRUE;
553         doneFileModifier = TRUE;
554       }
555
556       /* If 's' but no other parameter, dump the whole thing */
557       if (!doneFileModifier &&
558           memchrW(firstModifier, 's', modifierLen) != NULL) {
559         doneModifier = TRUE;
560         if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
561         strcatW(finaloutput, outputparam);
562       }
563     }
564   }
565
566   /* If No other modifier processed,  just add in parameter */
567   if (!doneModifier) strcpyW(finaloutput, outputparam);
568
569   /* Finish by inserting the replacement into the string */
570   WCMD_strsubstW(*start, lastModifier+1, finaloutput, -1);
571 }
572
573 /*******************************************************************
574  * WCMD_call - processes a batch call statement
575  *
576  *      If there is a leading ':', calls within this batch program
577  *      otherwise launches another program.
578  */
579 void WCMD_call (WCHAR *command) {
580
581   /* Run other program if no leading ':' */
582   if (*command != ':') {
583     WCMD_run_program(command, TRUE);
584   } else {
585
586     WCHAR gotoLabel[MAX_PATH];
587
588     strcpyW(gotoLabel, param1);
589
590     if (context) {
591
592       LARGE_INTEGER li;
593
594       /* Save the current file position, call the same file,
595          restore position                                    */
596       li.QuadPart = 0;
597       li.u.LowPart = SetFilePointer(context -> h, li.u.LowPart,
598                      &li.u.HighPart, FILE_CURRENT);
599
600       WCMD_batch (param1, command, TRUE, gotoLabel, context->h);
601
602       SetFilePointer(context -> h, li.u.LowPart,
603                      &li.u.HighPart, FILE_BEGIN);
604     } else {
605       WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_CALLINSCRIPT));
606     }
607   }
608 }