cmd.exe: Support PUSHD with wildcards.
[wine/wine64.git] / programs / cmd / builtins.c
blob422042e8c209caa509da34578ffd1a523002d05b
1 /*
2 * CMD - Wine-compatible command line interface - built-in functions.
4 * Copyright (C) 1999 D A Pickles
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * NOTES:
23 * On entry to each function, global variables quals, param1, param2 contain
24 * the qualifiers (uppercased and concatenated) and parameters entered, with
25 * environment-variable and batch parameter substitution already done.
29 * FIXME:
30 * - No support for pipes, shell parameters
31 * - Lots of functionality missing from builtins
32 * - Messages etc need international support
35 #define WIN32_LEAN_AND_MEAN
37 #include "wcmd.h"
38 #include <shellapi.h>
39 #include "wine/debug.h"
41 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
43 void WCMD_execute (char *orig_command, char *parameter, char *substitution);
45 struct env_stack *saved_environment;
46 struct env_stack *pushd_directories;
48 extern HINSTANCE hinst;
49 extern char *inbuilt[];
50 extern int echo_mode, verify_mode, defaultColor;
51 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
52 extern BATCH_CONTEXT *context;
53 extern DWORD errorlevel;
57 /****************************************************************************
58 * WCMD_clear_screen
60 * Clear the terminal screen.
63 void WCMD_clear_screen (void) {
65 /* Emulate by filling the screen from the top left to bottom right with
66 spaces, then moving the cursor to the top left afterwards */
67 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
68 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
70 if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
72 COORD topLeft;
73 DWORD screenSize;
75 screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
77 topLeft.X = 0;
78 topLeft.Y = 0;
79 FillConsoleOutputCharacter(hStdOut, ' ', screenSize, topLeft, &screenSize);
80 SetConsoleCursorPosition(hStdOut, topLeft);
84 /****************************************************************************
85 * WCMD_change_tty
87 * Change the default i/o device (ie redirect STDin/STDout).
90 void WCMD_change_tty (void) {
92 WCMD_output (nyi);
96 /****************************************************************************
97 * WCMD_copy
99 * Copy a file or wildcarded set.
100 * FIXME: No wildcard support
103 void WCMD_copy (void) {
105 DWORD count;
106 WIN32_FIND_DATA fd;
107 HANDLE hff;
108 BOOL force, status;
109 static const char overwrite[] = "Overwrite file (Y/N)?";
110 char string[8], outpath[MAX_PATH], inpath[MAX_PATH], *infile, copycmd[3];
111 DWORD len;
113 if (param1[0] == 0x00) {
114 WCMD_output ("Argument missing\n");
115 return;
118 if ((strchr(param1,'*') != NULL) && (strchr(param1,'%') != NULL)) {
119 WCMD_output ("Wildcards not yet supported\n");
120 return;
123 /* If no destination supplied, assume current directory */
124 if (param2[0] == 0x00) {
125 strcpy(param2, ".");
128 GetFullPathName (param2, sizeof(outpath), outpath, NULL);
129 if (outpath[strlen(outpath) - 1] == '\\')
130 outpath[strlen(outpath) - 1] = '\0';
131 hff = FindFirstFile (outpath, &fd);
132 if (hff != INVALID_HANDLE_VALUE) {
133 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
134 GetFullPathName (param1, sizeof(inpath), inpath, &infile);
135 strcat (outpath, "\\");
136 strcat (outpath, infile);
138 FindClose (hff);
141 /* /-Y has the highest priority, then /Y and finally the COPYCMD env. variable */
142 if (strstr (quals, "/-Y"))
143 force = FALSE;
144 else if (strstr (quals, "/Y"))
145 force = TRUE;
146 else {
147 len = GetEnvironmentVariable ("COPYCMD", copycmd, sizeof(copycmd));
148 force = (len && len < sizeof(copycmd) && ! lstrcmpi (copycmd, "/Y"));
151 if (!force) {
152 hff = FindFirstFile (outpath, &fd);
153 if (hff != INVALID_HANDLE_VALUE) {
154 FindClose (hff);
155 WCMD_output (overwrite);
156 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
157 if (toupper(string[0]) == 'Y') force = TRUE;
159 else force = TRUE;
161 if (force) {
162 status = CopyFile (param1, outpath, FALSE);
163 if (!status) WCMD_print_error ();
167 /****************************************************************************
168 * WCMD_create_dir
170 * Create a directory.
172 * this works recursivly. so mkdir dir1\dir2\dir3 will create dir1 and dir2 if
173 * they do not already exist.
176 BOOL create_full_path(CHAR* path)
178 int len;
179 CHAR *new_path;
180 BOOL ret = TRUE;
182 new_path = HeapAlloc(GetProcessHeap(),0,strlen(path)+1);
183 strcpy(new_path,path);
185 while ((len = strlen(new_path)) && new_path[len - 1] == '\\')
186 new_path[len - 1] = 0;
188 while (!CreateDirectory(new_path,NULL))
190 CHAR *slash;
191 DWORD last_error = GetLastError();
192 if (last_error == ERROR_ALREADY_EXISTS)
193 break;
195 if (last_error != ERROR_PATH_NOT_FOUND)
197 ret = FALSE;
198 break;
201 if (!(slash = strrchr(new_path,'\\')) && ! (slash = strrchr(new_path,'/')))
203 ret = FALSE;
204 break;
207 len = slash - new_path;
208 new_path[len] = 0;
209 if (!create_full_path(new_path))
211 ret = FALSE;
212 break;
214 new_path[len] = '\\';
216 HeapFree(GetProcessHeap(),0,new_path);
217 return ret;
220 void WCMD_create_dir (void) {
222 if (param1[0] == 0x00) {
223 WCMD_output ("Argument missing\n");
224 return;
226 if (!create_full_path(param1)) WCMD_print_error ();
229 /****************************************************************************
230 * WCMD_delete
232 * Delete a file or wildcarded set.
234 * Note on /A:
235 * - Testing shows /A is repeatable, eg. /a-r /ar matches all files
236 * - Each set is a pattern, eg /ahr /as-r means
237 * readonly+hidden OR nonreadonly system files
238 * - The '-' applies to a single field, ie /a:-hr means read only
239 * non-hidden files
242 void WCMD_delete (char *command) {
244 int argno = 0;
245 int argsProcessed = 0;
246 char *argN = command;
248 /* Loop through all args */
249 while (argN) {
250 char *thisArg = WCMD_parameter (command, argno++, &argN);
251 if (argN && argN[0] != '/') {
253 WIN32_FIND_DATA fd;
254 HANDLE hff;
255 char fpath[MAX_PATH];
256 char *p;
259 WINE_TRACE("del: Processing arg %s (quals:%s)\n", thisArg, quals);
260 argsProcessed++;
262 /* If filename part of parameter is * or *.*, prompt unless
263 /Q supplied. */
264 if ((strstr (quals, "/Q") == NULL) && (strstr (quals, "/P") == NULL)) {
266 char drive[10];
267 char dir[MAX_PATH];
268 char fname[MAX_PATH];
269 char ext[MAX_PATH];
271 /* Convert path into actual directory spec */
272 GetFullPathName (thisArg, sizeof(fpath), fpath, NULL);
273 WCMD_splitpath(fpath, drive, dir, fname, ext);
275 /* Only prompt for * and *.*, not *a, a*, *.a* etc */
276 if ((strcmp(fname, "*") == 0) &&
277 (*ext == 0x00 || (strcmp(ext, ".*") == 0))) {
278 BOOL ok;
279 char question[MAXSTRING];
281 /* Ask for confirmation */
282 sprintf(question, "%s, ", fpath);
283 ok = WCMD_ask_confirm(question, TRUE);
285 /* Abort if answer is 'N' */
286 if (!ok) continue;
290 hff = FindFirstFile (thisArg, &fd);
291 if (hff == INVALID_HANDLE_VALUE) {
292 WCMD_output ("%s :File Not Found\n", thisArg);
293 continue;
295 /* Support del <dirname> by just deleting all files dirname\* */
296 if ((strchr(thisArg,'*') == NULL) && (strchr(thisArg,'?') == NULL)
297 && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
298 char modifiedParm[MAX_PATH];
299 strcpy(modifiedParm, thisArg);
300 strcat(modifiedParm, "\\*");
301 FindClose(hff);
302 WCMD_delete(modifiedParm);
303 continue;
305 } else {
307 /* Build the filename to delete as <supplied directory>\<findfirst filename> */
308 strcpy (fpath, thisArg);
309 do {
310 p = strrchr (fpath, '\\');
311 if (p != NULL) {
312 *++p = '\0';
313 strcat (fpath, fd.cFileName);
315 else strcpy (fpath, fd.cFileName);
316 if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
317 BOOL ok = TRUE;
318 char *nextA = strstr (quals, "/A");
320 /* Handle attribute matching (/A) */
321 if (nextA != NULL) {
322 ok = FALSE;
323 while (nextA != NULL && !ok) {
325 char *thisA = (nextA+2);
326 BOOL stillOK = TRUE;
328 /* Skip optional : */
329 if (*thisA == ':') thisA++;
331 /* Parse each of the /A[:]xxx in turn */
332 while (*thisA && *thisA != '/') {
333 BOOL negate = FALSE;
334 BOOL attribute = FALSE;
336 /* Match negation of attribute first */
337 if (*thisA == '-') {
338 negate=TRUE;
339 thisA++;
342 /* Match attribute */
343 switch (*thisA) {
344 case 'R': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY);
345 break;
346 case 'H': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
347 break;
348 case 'S': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM);
349 break;
350 case 'A': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE);
351 break;
352 default:
353 WCMD_output ("Syntax error\n");
356 /* Now check result, keeping a running boolean about whether it
357 matches all parsed attribues so far */
358 if (attribute && !negate) {
359 stillOK = stillOK;
360 } else if (!attribute && negate) {
361 stillOK = stillOK;
362 } else {
363 stillOK = FALSE;
365 thisA++;
368 /* Save the running total as the final result */
369 ok = stillOK;
371 /* Step on to next /A set */
372 nextA = strstr (nextA+1, "/A");
376 /* /P means prompt for each file */
377 if (ok && strstr (quals, "/P") != NULL) {
378 char question[MAXSTRING];
380 /* Ask for confirmation */
381 sprintf(question, "%s, Delete", fpath);
382 ok = WCMD_ask_confirm(question, FALSE);
385 /* Only proceed if ok to */
386 if (ok) {
388 /* If file is read only, and /F supplied, delete it */
389 if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY &&
390 strstr (quals, "/F") != NULL) {
391 SetFileAttributes(fpath, fd.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
394 /* Now do the delete */
395 if (!DeleteFile (fpath)) WCMD_print_error ();
399 } while (FindNextFile(hff, &fd) != 0);
400 FindClose (hff);
405 /* Handle no valid args */
406 if (argsProcessed == 0) {
407 WCMD_output ("Argument missing\n");
408 return;
412 /****************************************************************************
413 * WCMD_echo
415 * Echo input to the screen (or not). We don't try to emulate the bugs
416 * in DOS (try typing "ECHO ON AGAIN" for an example).
419 void WCMD_echo (const char *command) {
421 static const char eon[] = "Echo is ON\n", eoff[] = "Echo is OFF\n";
422 int count;
424 if ((command[0] == '.') && (command[1] == 0)) {
425 WCMD_output (newline);
426 return;
428 if (command[0]==' ')
429 command++;
430 count = strlen(command);
431 if (count == 0) {
432 if (echo_mode) WCMD_output (eon);
433 else WCMD_output (eoff);
434 return;
436 if (lstrcmpi(command, "ON") == 0) {
437 echo_mode = 1;
438 return;
440 if (lstrcmpi(command, "OFF") == 0) {
441 echo_mode = 0;
442 return;
444 WCMD_output_asis (command);
445 WCMD_output (newline);
449 /**************************************************************************
450 * WCMD_for
452 * Batch file loop processing.
453 * FIXME: We don't exhaustively check syntax. Any command which works in MessDOS
454 * will probably work here, but the reverse is not necessarily the case...
457 void WCMD_for (char *p) {
459 WIN32_FIND_DATA fd;
460 HANDLE hff;
461 char *cmd, *item;
462 char set[MAX_PATH], param[MAX_PATH];
463 int i;
465 if (lstrcmpi (WCMD_parameter (p, 1, NULL), "in")
466 || lstrcmpi (WCMD_parameter (p, 3, NULL), "do")
467 || (param1[0] != '%')) {
468 WCMD_output ("Syntax error\n");
469 return;
471 lstrcpyn (set, WCMD_parameter (p, 2, NULL), sizeof(set));
472 WCMD_parameter (p, 4, &cmd);
473 lstrcpy (param, param1);
476 * If the parameter within the set has a wildcard then search for matching files
477 * otherwise do a literal substitution.
480 i = 0;
481 while (*(item = WCMD_parameter (set, i, NULL))) {
482 if (strpbrk (item, "*?")) {
483 hff = FindFirstFile (item, &fd);
484 if (hff == INVALID_HANDLE_VALUE) {
485 return;
487 do {
488 WCMD_execute (cmd, param, fd.cFileName);
489 } while (FindNextFile(hff, &fd) != 0);
490 FindClose (hff);
492 else {
493 WCMD_execute (cmd, param, item);
495 i++;
499 /*****************************************************************************
500 * WCMD_Execute
502 * Execute a command after substituting variable text for the supplied parameter
505 void WCMD_execute (char *orig_cmd, char *param, char *subst) {
507 char *new_cmd, *p, *s, *dup;
508 int size;
510 size = lstrlen (orig_cmd);
511 new_cmd = (char *) LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, size);
512 dup = s = strdup (orig_cmd);
514 while ((p = strstr (s, param))) {
515 *p = '\0';
516 size += lstrlen (subst);
517 new_cmd = (char *) LocalReAlloc ((HANDLE)new_cmd, size, 0);
518 strcat (new_cmd, s);
519 strcat (new_cmd, subst);
520 s = p + lstrlen (param);
522 strcat (new_cmd, s);
523 WCMD_process_command (new_cmd);
524 free (dup);
525 LocalFree ((HANDLE)new_cmd);
529 /**************************************************************************
530 * WCMD_give_help
532 * Simple on-line help. Help text is stored in the resource file.
535 void WCMD_give_help (char *command) {
537 int i;
538 char buffer[2048];
540 command = WCMD_strtrim_leading_spaces(command);
541 if (lstrlen(command) == 0) {
542 LoadString (hinst, 1000, buffer, sizeof(buffer));
543 WCMD_output_asis (buffer);
545 else {
546 for (i=0; i<=WCMD_EXIT; i++) {
547 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
548 param1, -1, inbuilt[i], -1) == 2) {
549 LoadString (hinst, i, buffer, sizeof(buffer));
550 WCMD_output_asis (buffer);
551 return;
554 WCMD_output ("No help available for %s\n", param1);
556 return;
559 /****************************************************************************
560 * WCMD_go_to
562 * Batch file jump instruction. Not the most efficient algorithm ;-)
563 * Prints error message if the specified label cannot be found - the file pointer is
564 * then at EOF, effectively stopping the batch file.
565 * FIXME: DOS is supposed to allow labels with spaces - we don't.
568 void WCMD_goto (void) {
570 char string[MAX_PATH];
572 if (param1[0] == 0x00) {
573 WCMD_output ("Argument missing\n");
574 return;
576 if (context != NULL) {
577 char *paramStart = param1;
579 /* Handle special :EOF label */
580 if (lstrcmpi (":eof", param1) == 0) {
581 context -> skip_rest = TRUE;
582 return;
585 /* Support goto :label as well as goto label */
586 if (*paramStart == ':') paramStart++;
588 SetFilePointer (context -> h, 0, NULL, FILE_BEGIN);
589 while (WCMD_fgets (string, sizeof(string), context -> h)) {
590 if ((string[0] == ':') && (lstrcmpi (&string[1], paramStart) == 0)) return;
592 WCMD_output ("Target to GOTO not found\n");
594 return;
597 /*****************************************************************************
598 * WCMD_pushd
600 * Push a directory onto the stack
603 void WCMD_pushd (char *command) {
604 struct env_stack *curdir;
605 WCHAR *thisdir;
607 curdir = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
608 thisdir = LocalAlloc (LMEM_FIXED, 1024 * sizeof(WCHAR));
609 if( !curdir || !thisdir ) {
610 LocalFree(curdir);
611 LocalFree(thisdir);
612 WCMD_output ("out of memory\n");
613 return;
616 GetCurrentDirectoryW (1024, thisdir);
617 errorlevel = 0;
618 WCMD_setshow_default(command);
619 if (errorlevel) {
620 LocalFree(curdir);
621 LocalFree(thisdir);
622 return;
623 } else {
624 curdir -> next = pushd_directories;
625 curdir -> strings = thisdir;
626 if (pushd_directories == NULL) {
627 curdir -> stackdepth = 1;
628 } else {
629 curdir -> stackdepth = pushd_directories -> stackdepth + 1;
631 pushd_directories = curdir;
636 /*****************************************************************************
637 * WCMD_popd
639 * Pop a directory from the stack
642 void WCMD_popd (void) {
643 struct env_stack *temp = pushd_directories;
645 if (!pushd_directories)
646 return;
648 /* pop the old environment from the stack, and make it the current dir */
649 pushd_directories = temp->next;
650 SetCurrentDirectoryW(temp->strings);
651 LocalFree (temp->strings);
652 LocalFree (temp);
655 /****************************************************************************
656 * WCMD_if
658 * Batch file conditional.
659 * FIXME: Much more syntax checking needed!
662 void WCMD_if (char *p) {
664 int negate = 0, test = 0;
665 char condition[MAX_PATH], *command, *s;
667 if (!lstrcmpi (param1, "not")) {
668 negate = 1;
669 lstrcpy (condition, param2);
671 else {
672 lstrcpy (condition, param1);
674 if (!lstrcmpi (condition, "errorlevel")) {
675 if (errorlevel >= atoi(WCMD_parameter (p, 1+negate, NULL))) test = 1;
676 WCMD_parameter (p, 2+negate, &command);
678 else if (!lstrcmpi (condition, "exist")) {
679 if (GetFileAttributesA(WCMD_parameter (p, 1+negate, NULL)) != INVALID_FILE_ATTRIBUTES) {
680 test = 1;
682 WCMD_parameter (p, 2+negate, &command);
684 else if (!lstrcmpi (condition, "defined")) {
685 if (GetEnvironmentVariableA(WCMD_parameter (p, 1+negate, NULL), NULL, 0) > 0) {
686 test = 1;
688 WCMD_parameter (p, 2+negate, &command);
690 else if ((s = strstr (p, "=="))) {
691 s += 2;
692 if (!lstrcmpi (condition, WCMD_parameter (s, 0, NULL))) test = 1;
693 WCMD_parameter (s, 1, &command);
695 else {
696 WCMD_output ("Syntax error\n");
697 return;
699 if (test != negate) {
700 command = strdup (command);
701 WCMD_process_command (command);
702 free (command);
706 /****************************************************************************
707 * WCMD_move
709 * Move a file, directory tree or wildcarded set of files.
710 * FIXME: Needs input and output files to be fully specified.
713 void WCMD_move (void) {
715 int status;
716 char outpath[MAX_PATH], inpath[MAX_PATH], *infile;
717 WIN32_FIND_DATA fd;
718 HANDLE hff;
720 if (param1[0] == 0x00) {
721 WCMD_output ("Argument missing\n");
722 return;
725 if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
726 WCMD_output ("Wildcards not yet supported\n");
727 return;
730 /* If no destination supplied, assume current directory */
731 if (param2[0] == 0x00) {
732 strcpy(param2, ".");
735 /* If 2nd parm is directory, then use original filename */
736 GetFullPathName (param2, sizeof(outpath), outpath, NULL);
737 if (outpath[strlen(outpath) - 1] == '\\')
738 outpath[strlen(outpath) - 1] = '\0';
739 hff = FindFirstFile (outpath, &fd);
740 if (hff != INVALID_HANDLE_VALUE) {
741 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
742 GetFullPathName (param1, sizeof(inpath), inpath, &infile);
743 strcat (outpath, "\\");
744 strcat (outpath, infile);
746 FindClose (hff);
749 status = MoveFile (param1, outpath);
750 if (!status) WCMD_print_error ();
753 /****************************************************************************
754 * WCMD_pause
756 * Wait for keyboard input.
759 void WCMD_pause (void) {
761 DWORD count;
762 char string[32];
764 WCMD_output (anykey);
765 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
768 /****************************************************************************
769 * WCMD_remove_dir
771 * Delete a directory.
774 void WCMD_remove_dir (char *command) {
776 int argno = 0;
777 int argsProcessed = 0;
778 char *argN = command;
780 /* Loop through all args */
781 while (argN) {
782 char *thisArg = WCMD_parameter (command, argno++, &argN);
783 if (argN && argN[0] != '/') {
784 WINE_TRACE("rd: Processing arg %s (quals:%s)\n", thisArg, quals);
785 argsProcessed++;
787 /* If subdirectory search not supplied, just try to remove
788 and report error if it fails (eg if it contains a file) */
789 if (strstr (quals, "/S") == NULL) {
790 if (!RemoveDirectory (thisArg)) WCMD_print_error ();
792 /* Otherwise use ShFileOp to recursively remove a directory */
793 } else {
795 SHFILEOPSTRUCT lpDir;
797 /* Ask first */
798 if (strstr (quals, "/Q") == NULL) {
799 BOOL ok;
800 char question[MAXSTRING];
802 /* Ask for confirmation */
803 sprintf(question, "%s, ", thisArg);
804 ok = WCMD_ask_confirm(question, TRUE);
806 /* Abort if answer is 'N' */
807 if (!ok) return;
810 /* Do the delete */
811 lpDir.hwnd = NULL;
812 lpDir.pTo = NULL;
813 lpDir.pFrom = thisArg;
814 lpDir.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI;
815 lpDir.wFunc = FO_DELETE;
816 if (SHFileOperationA(&lpDir)) WCMD_print_error ();
821 /* Handle no valid args */
822 if (argsProcessed == 0) {
823 WCMD_output ("Argument missing\n");
824 return;
829 /****************************************************************************
830 * WCMD_rename
832 * Rename a file.
833 * FIXME: Needs input and output files to be fully specified.
836 void WCMD_rename (void) {
838 int status;
840 if (param1[0] == 0x00 || param2[0] == 0x00) {
841 WCMD_output ("Argument missing\n");
842 return;
844 if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
845 WCMD_output ("Wildcards not yet supported\n");
846 return;
848 status = MoveFile (param1, param2);
849 if (!status) WCMD_print_error ();
852 /*****************************************************************************
853 * WCMD_dupenv
855 * Make a copy of the environment.
857 static WCHAR *WCMD_dupenv( const WCHAR *env )
859 WCHAR *env_copy;
860 int len;
862 if( !env )
863 return NULL;
865 len = 0;
866 while ( env[len] )
867 len += (lstrlenW(&env[len]) + 1);
869 env_copy = LocalAlloc (LMEM_FIXED, (len+1) * sizeof (WCHAR) );
870 if (!env_copy)
872 WCMD_output ("out of memory\n");
873 return env_copy;
875 memcpy (env_copy, env, len*sizeof (WCHAR));
876 env_copy[len] = 0;
878 return env_copy;
881 /*****************************************************************************
882 * WCMD_setlocal
884 * setlocal pushes the environment onto a stack
885 * Save the environment as unicode so we don't screw anything up.
887 void WCMD_setlocal (const char *s) {
888 WCHAR *env;
889 struct env_stack *env_copy;
891 /* DISABLEEXTENSIONS ignored */
893 env_copy = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
894 if( !env_copy )
896 WCMD_output ("out of memory\n");
897 return;
900 env = GetEnvironmentStringsW ();
902 env_copy->strings = WCMD_dupenv (env);
903 if (env_copy->strings)
905 env_copy->next = saved_environment;
906 saved_environment = env_copy;
908 else
909 LocalFree (env_copy);
911 FreeEnvironmentStringsW (env);
914 /*****************************************************************************
915 * WCMD_strchrW
917 static inline WCHAR *WCMD_strchrW(WCHAR *str, WCHAR ch)
919 while(*str)
921 if(*str == ch)
922 return str;
923 str++;
925 return NULL;
928 /*****************************************************************************
929 * WCMD_endlocal
931 * endlocal pops the environment off a stack
933 void WCMD_endlocal (void) {
934 WCHAR *env, *old, *p;
935 struct env_stack *temp;
936 int len, n;
938 if (!saved_environment)
939 return;
941 /* pop the old environment from the stack */
942 temp = saved_environment;
943 saved_environment = temp->next;
945 /* delete the current environment, totally */
946 env = GetEnvironmentStringsW ();
947 old = WCMD_dupenv (GetEnvironmentStringsW ());
948 len = 0;
949 while (old[len]) {
950 n = lstrlenW(&old[len]) + 1;
951 p = WCMD_strchrW(&old[len], '=');
952 if (p)
954 *p++ = 0;
955 SetEnvironmentVariableW (&old[len], NULL);
957 len += n;
959 LocalFree (old);
960 FreeEnvironmentStringsW (env);
962 /* restore old environment */
963 env = temp->strings;
964 len = 0;
965 while (env[len]) {
966 n = lstrlenW(&env[len]) + 1;
967 p = WCMD_strchrW(&env[len], '=');
968 if (p)
970 *p++ = 0;
971 SetEnvironmentVariableW (&env[len], p);
973 len += n;
975 LocalFree (env);
976 LocalFree (temp);
979 /*****************************************************************************
980 * WCMD_setshow_attrib
982 * Display and optionally sets DOS attributes on a file or directory
984 * FIXME: Wine currently uses the Unix stat() function to get file attributes.
985 * As a result only the Readonly flag is correctly reported, the Archive bit
986 * is always set and the rest are not implemented. We do the Right Thing anyway.
988 * FIXME: No SET functionality.
992 void WCMD_setshow_attrib (void) {
994 DWORD count;
995 HANDLE hff;
996 WIN32_FIND_DATA fd;
997 char flags[9] = {" "};
999 if (param1[0] == '-') {
1000 WCMD_output (nyi);
1001 return;
1004 if (lstrlen(param1) == 0) {
1005 GetCurrentDirectory (sizeof(param1), param1);
1006 strcat (param1, "\\*");
1009 hff = FindFirstFile (param1, &fd);
1010 if (hff == INVALID_HANDLE_VALUE) {
1011 WCMD_output ("%s: File Not Found\n",param1);
1013 else {
1014 do {
1015 if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1016 if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
1017 flags[0] = 'H';
1019 if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
1020 flags[1] = 'S';
1022 if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
1023 flags[2] = 'A';
1025 if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
1026 flags[3] = 'R';
1028 if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
1029 flags[4] = 'T';
1031 if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
1032 flags[5] = 'C';
1034 WCMD_output ("%s %s\n", flags, fd.cFileName);
1035 for (count=0; count < 8; count++) flags[count] = ' ';
1037 } while (FindNextFile(hff, &fd) != 0);
1039 FindClose (hff);
1042 /*****************************************************************************
1043 * WCMD_setshow_default
1045 * Set/Show the current default directory
1048 void WCMD_setshow_default (char *command) {
1050 BOOL status;
1051 char string[1024];
1052 char *pos;
1053 WIN32_FIND_DATA fd;
1054 HANDLE hff;
1056 WINE_TRACE("Request change to directory '%s'\n", command);
1057 if (strlen(command) == 0) {
1058 GetCurrentDirectory (sizeof(string), string);
1059 strcat (string, "\n");
1060 WCMD_output (string);
1062 else {
1063 /* Remove any double quotes, which may be in the
1064 middle, eg. cd "C:\Program Files"\Microsoft is ok */
1065 pos = string;
1066 while (*command) {
1067 if (*command != '"') *pos++ = *command;
1068 command++;
1070 *pos = 0x00;
1072 /* Search for approprate directory */
1073 WINE_TRACE("Looking for directory '%s'\n", string);
1074 hff = FindFirstFile (string, &fd);
1075 while (hff != INVALID_HANDLE_VALUE) {
1076 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1077 char fpath[MAX_PATH];
1078 char drive[10];
1079 char dir[MAX_PATH];
1080 char fname[MAX_PATH];
1081 char ext[MAX_PATH];
1083 /* Convert path into actual directory spec */
1084 GetFullPathName (string, sizeof(fpath), fpath, NULL);
1085 WCMD_splitpath(fpath, drive, dir, fname, ext);
1087 /* Rebuild path */
1088 sprintf(string, "%s%s%s", drive, dir, fd.cFileName);
1090 FindClose(hff);
1091 hff = INVALID_HANDLE_VALUE;
1092 break;
1095 /* Step on to next match */
1096 if (FindNextFile(hff, &fd) == 0) {
1097 FindClose(hff);
1098 hff = INVALID_HANDLE_VALUE;
1099 break;
1103 /* Change to that directory */
1104 WINE_TRACE("Really changing to directory '%s'\n", string);
1105 status = SetCurrentDirectory (string);
1106 if (!status) {
1107 errorlevel = 1;
1108 WCMD_print_error ();
1109 return;
1112 return;
1115 /****************************************************************************
1116 * WCMD_setshow_date
1118 * Set/Show the system date
1119 * FIXME: Can't change date yet
1122 void WCMD_setshow_date (void) {
1124 char curdate[64], buffer[64];
1125 DWORD count;
1127 if (lstrlen(param1) == 0) {
1128 if (GetDateFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL,
1129 curdate, sizeof(curdate))) {
1130 WCMD_output ("Current Date is %s\nEnter new date: ", curdate);
1131 ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1132 if (count > 2) {
1133 WCMD_output (nyi);
1136 else WCMD_print_error ();
1138 else {
1139 WCMD_output (nyi);
1143 /****************************************************************************
1144 * WCMD_compare
1146 static int WCMD_compare( const void *a, const void *b )
1148 int r;
1149 const char * const *str_a = a, * const *str_b = b;
1150 r = CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1151 *str_a, -1, *str_b, -1 );
1152 if( r == CSTR_LESS_THAN ) return -1;
1153 if( r == CSTR_GREATER_THAN ) return 1;
1154 return 0;
1157 /****************************************************************************
1158 * WCMD_setshow_sortenv
1160 * sort variables into order for display
1161 * Optionally only display those who start with a stub
1162 * returns the count displayed
1164 static int WCMD_setshow_sortenv(const char *s, const char *stub)
1166 UINT count=0, len=0, i, displayedcount=0, stublen=0;
1167 const char **str;
1169 if (stub) stublen = strlen(stub);
1171 /* count the number of strings, and the total length */
1172 while ( s[len] ) {
1173 len += (lstrlen(&s[len]) + 1);
1174 count++;
1177 /* add the strings to an array */
1178 str = LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, count * sizeof (char*) );
1179 if( !str )
1180 return 0;
1181 str[0] = s;
1182 for( i=1; i<count; i++ )
1183 str[i] = str[i-1] + lstrlen(str[i-1]) + 1;
1185 /* sort the array */
1186 qsort( str, count, sizeof (char*), WCMD_compare );
1188 /* print it */
1189 for( i=0; i<count; i++ ) {
1190 if (!stub || CompareString (LOCALE_USER_DEFAULT,
1191 NORM_IGNORECASE | SORT_STRINGSORT,
1192 str[i], stublen, stub, -1) == 2) {
1193 WCMD_output_asis(str[i]);
1194 WCMD_output_asis("\n");
1195 displayedcount++;
1199 LocalFree( str );
1200 return displayedcount;
1203 /****************************************************************************
1204 * WCMD_setshow_env
1206 * Set/Show the environment variables
1209 void WCMD_setshow_env (char *s) {
1211 LPVOID env;
1212 char *p;
1213 int status;
1215 if (strlen(param1) == 0) {
1216 env = GetEnvironmentStrings ();
1217 WCMD_setshow_sortenv( env, NULL );
1219 else {
1220 p = strchr (s, '=');
1221 if (p == NULL) {
1222 env = GetEnvironmentStrings ();
1223 if (WCMD_setshow_sortenv( env, s ) == 0) {
1224 WCMD_output ("Environment variable %s not defined\n", s);
1226 return;
1228 *p++ = '\0';
1230 if (strlen(p) == 0) p = NULL;
1231 status = SetEnvironmentVariable (s, p);
1232 if ((!status) & (GetLastError() != ERROR_ENVVAR_NOT_FOUND)) WCMD_print_error();
1236 /****************************************************************************
1237 * WCMD_setshow_path
1239 * Set/Show the path environment variable
1242 void WCMD_setshow_path (char *command) {
1244 char string[1024];
1245 DWORD status;
1247 if (strlen(param1) == 0) {
1248 status = GetEnvironmentVariable ("PATH", string, sizeof(string));
1249 if (status != 0) {
1250 WCMD_output_asis ( "PATH=");
1251 WCMD_output_asis ( string);
1252 WCMD_output_asis ( "\n");
1254 else {
1255 WCMD_output ("PATH not found\n");
1258 else {
1259 if (*command == '=') command++; /* Skip leading '=' */
1260 status = SetEnvironmentVariable ("PATH", command);
1261 if (!status) WCMD_print_error();
1265 /****************************************************************************
1266 * WCMD_setshow_prompt
1268 * Set or show the command prompt.
1271 void WCMD_setshow_prompt (void) {
1273 char *s;
1275 if (strlen(param1) == 0) {
1276 SetEnvironmentVariable ("PROMPT", NULL);
1278 else {
1279 s = param1;
1280 while ((*s == '=') || (*s == ' ')) s++;
1281 if (strlen(s) == 0) {
1282 SetEnvironmentVariable ("PROMPT", NULL);
1284 else SetEnvironmentVariable ("PROMPT", s);
1288 /****************************************************************************
1289 * WCMD_setshow_time
1291 * Set/Show the system time
1292 * FIXME: Can't change time yet
1295 void WCMD_setshow_time (void) {
1297 char curtime[64], buffer[64];
1298 DWORD count;
1299 SYSTEMTIME st;
1301 if (strlen(param1) == 0) {
1302 GetLocalTime(&st);
1303 if (GetTimeFormat (LOCALE_USER_DEFAULT, 0, &st, NULL,
1304 curtime, sizeof(curtime))) {
1305 WCMD_output ("Current Time is %s\nEnter new time: ", curtime);
1306 ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1307 if (count > 2) {
1308 WCMD_output (nyi);
1311 else WCMD_print_error ();
1313 else {
1314 WCMD_output (nyi);
1318 /****************************************************************************
1319 * WCMD_shift
1321 * Shift batch parameters.
1324 void WCMD_shift (void) {
1326 if (context != NULL) context -> shift_count++;
1330 /****************************************************************************
1331 * WCMD_title
1333 * Set the console title
1335 void WCMD_title (char *command) {
1336 SetConsoleTitle(command);
1339 /****************************************************************************
1340 * WCMD_type
1342 * Copy a file to standard output.
1345 void WCMD_type (void) {
1347 HANDLE h;
1348 char buffer[512];
1349 DWORD count;
1351 if (param1[0] == 0x00) {
1352 WCMD_output ("Argument missing\n");
1353 return;
1355 h = CreateFile (param1, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1356 FILE_ATTRIBUTE_NORMAL, NULL);
1357 if (h == INVALID_HANDLE_VALUE) {
1358 WCMD_print_error ();
1359 return;
1361 while (ReadFile (h, buffer, sizeof(buffer), &count, NULL)) {
1362 if (count == 0) break; /* ReadFile reports success on EOF! */
1363 buffer[count] = 0;
1364 WCMD_output_asis (buffer);
1366 CloseHandle (h);
1369 /****************************************************************************
1370 * WCMD_verify
1372 * Display verify flag.
1373 * FIXME: We don't actually do anything with the verify flag other than toggle
1374 * it...
1377 void WCMD_verify (char *command) {
1379 static const char von[] = "Verify is ON\n", voff[] = "Verify is OFF\n";
1380 int count;
1382 count = strlen(command);
1383 if (count == 0) {
1384 if (verify_mode) WCMD_output (von);
1385 else WCMD_output (voff);
1386 return;
1388 if (lstrcmpi(command, "ON") == 0) {
1389 verify_mode = 1;
1390 return;
1392 else if (lstrcmpi(command, "OFF") == 0) {
1393 verify_mode = 0;
1394 return;
1396 else WCMD_output ("Verify must be ON or OFF\n");
1399 /****************************************************************************
1400 * WCMD_version
1402 * Display version info.
1405 void WCMD_version (void) {
1407 WCMD_output (version_string);
1411 /****************************************************************************
1412 * WCMD_volume
1414 * Display volume info and/or set volume label. Returns 0 if error.
1417 int WCMD_volume (int mode, char *path) {
1419 DWORD count, serial;
1420 char string[MAX_PATH], label[MAX_PATH], curdir[MAX_PATH];
1421 BOOL status;
1423 if (lstrlen(path) == 0) {
1424 status = GetCurrentDirectory (sizeof(curdir), curdir);
1425 if (!status) {
1426 WCMD_print_error ();
1427 return 0;
1429 status = GetVolumeInformation (NULL, label, sizeof(label), &serial, NULL,
1430 NULL, NULL, 0);
1432 else {
1433 if ((path[1] != ':') || (lstrlen(path) != 2)) {
1434 WCMD_output_asis("Syntax Error\n\n");
1435 return 0;
1437 wsprintf (curdir, "%s\\", path);
1438 status = GetVolumeInformation (curdir, label, sizeof(label), &serial, NULL,
1439 NULL, NULL, 0);
1441 if (!status) {
1442 WCMD_print_error ();
1443 return 0;
1445 WCMD_output ("Volume in drive %c is %s\nVolume Serial Number is %04x-%04x\n\n",
1446 curdir[0], label, HIWORD(serial), LOWORD(serial));
1447 if (mode) {
1448 WCMD_output ("Volume label (11 characters, ENTER for none)?");
1449 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
1450 if (count > 1) {
1451 string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
1452 if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
1454 if (lstrlen(path) != 0) {
1455 if (!SetVolumeLabel (curdir, string)) WCMD_print_error ();
1457 else {
1458 if (!SetVolumeLabel (NULL, string)) WCMD_print_error ();
1461 return 1;
1464 /**************************************************************************
1465 * WCMD_exit
1467 * Exit either the process, or just this batch program
1471 void WCMD_exit (void) {
1473 int rc = atoi(param1); /* Note: atoi of empty parameter is 0 */
1475 if (context && lstrcmpi(quals, "/B") == 0) {
1476 errorlevel = rc;
1477 context -> skip_rest = TRUE;
1478 } else {
1479 ExitProcess(rc);
1483 /**************************************************************************
1484 * WCMD_ask_confirm
1486 * Issue a message and ask 'Are you sure (Y/N)', waiting on a valid
1487 * answer.
1489 * Returns True if Y answer is selected
1492 BOOL WCMD_ask_confirm (char *message, BOOL showSureText) {
1494 char msgbuffer[MAXSTRING];
1495 char Ybuffer[MAXSTRING];
1496 char Nbuffer[MAXSTRING];
1497 char answer[MAX_PATH] = "";
1498 DWORD count = 0;
1500 /* Load the translated 'Are you sure', plus valid answers */
1501 LoadString (hinst, WCMD_CONFIRM, msgbuffer, sizeof(msgbuffer));
1502 LoadString (hinst, WCMD_YES, Ybuffer, sizeof(Ybuffer));
1503 LoadString (hinst, WCMD_NO, Nbuffer, sizeof(Nbuffer));
1505 /* Loop waiting on a Y or N */
1506 while (answer[0] != Ybuffer[0] && answer[0] != Nbuffer[0]) {
1507 WCMD_output_asis (message);
1508 if (showSureText) {
1509 WCMD_output_asis (msgbuffer);
1511 WCMD_output_asis (" (");
1512 WCMD_output_asis (Ybuffer);
1513 WCMD_output_asis ("/");
1514 WCMD_output_asis (Nbuffer);
1515 WCMD_output_asis (")?");
1516 ReadFile (GetStdHandle(STD_INPUT_HANDLE), answer, sizeof(answer),
1517 &count, NULL);
1518 answer[0] = toupper(answer[0]);
1521 /* Return the answer */
1522 return (answer[0] == Ybuffer[0]);
1525 /*****************************************************************************
1526 * WCMD_assoc
1528 * Lists or sets file associations
1530 void WCMD_assoc (char *command) {
1532 HKEY key;
1533 DWORD accessOptions = KEY_READ;
1534 char *newValue;
1535 LONG rc = ERROR_SUCCESS;
1536 char keyValue[MAXSTRING];
1537 DWORD valueLen = MAXSTRING;
1538 HKEY readKey;
1541 /* See if parameter includes '=' */
1542 errorlevel = 0;
1543 newValue = strchr(command, '=');
1544 if (newValue) accessOptions |= KEY_WRITE;
1546 /* Open a key to HKEY_CLASSES_ROOT for enumerating */
1547 if (RegOpenKeyEx(HKEY_CLASSES_ROOT, "", 0,
1548 accessOptions, &key) != ERROR_SUCCESS) {
1549 WINE_FIXME("Unexpected failure opening HKCR key: %d\n", GetLastError());
1550 return;
1553 /* If no parameters then list all associations */
1554 if (*command == 0x00) {
1555 int index = 0;
1557 /* Enumerate all the keys */
1558 while (rc != ERROR_NO_MORE_ITEMS) {
1559 char keyName[MAXSTRING];
1560 DWORD nameLen;
1562 /* Find the next value */
1563 nameLen = MAXSTRING;
1564 rc = RegEnumKeyEx(key, index++,
1565 keyName, &nameLen,
1566 NULL, NULL, NULL, NULL);
1568 if (rc == ERROR_SUCCESS) {
1570 /* Only interested in extension ones */
1571 if (keyName[0] == '.') {
1573 if (RegOpenKeyEx(key, keyName, 0,
1574 accessOptions, &readKey) == ERROR_SUCCESS) {
1576 rc = RegQueryValueEx(readKey, NULL, NULL, NULL,
1577 (LPBYTE)keyValue, &valueLen);
1578 WCMD_output_asis(keyName);
1579 WCMD_output_asis("=");
1580 /* If no default value found, leave line empty after '=' */
1581 if (rc == ERROR_SUCCESS) {
1582 WCMD_output_asis(keyValue);
1584 WCMD_output_asis("\n");
1589 RegCloseKey(readKey);
1591 } else {
1593 /* Parameter supplied - if no '=' on command line, its a query */
1594 if (newValue == NULL) {
1595 char *space;
1597 /* Query terminates the parameter at the first space */
1598 strcpy(keyValue, command);
1599 space = strchr(keyValue, ' ');
1600 if (space) *space=0x00;
1602 if (RegOpenKeyEx(key, keyValue, 0,
1603 accessOptions, &readKey) == ERROR_SUCCESS) {
1605 rc = RegQueryValueEx(readKey, NULL, NULL, NULL,
1606 (LPBYTE)keyValue, &valueLen);
1607 WCMD_output_asis(command);
1608 WCMD_output_asis("=");
1609 /* If no default value found, leave line empty after '=' */
1610 if (rc == ERROR_SUCCESS) WCMD_output_asis(keyValue);
1611 WCMD_output_asis("\n");
1612 RegCloseKey(readKey);
1614 } else {
1615 char msgbuffer[MAXSTRING];
1616 char outbuffer[MAXSTRING];
1618 /* Load the translated 'File association not found' */
1619 LoadString (hinst, WCMD_NOASSOC, msgbuffer, sizeof(msgbuffer));
1620 sprintf(outbuffer, msgbuffer, keyValue);
1621 WCMD_output_asis(outbuffer);
1622 errorlevel = 2;
1625 /* Not a query - its a set or clear of a value */
1626 } else {
1628 /* Get pointer to new value */
1629 *newValue = 0x00;
1630 newValue++;
1632 /* If nothing after '=' then clear value */
1633 if (*newValue == 0x00) {
1635 rc = RegDeleteKey(key, command);
1636 if (rc == ERROR_SUCCESS) {
1637 WINE_TRACE("HKCR Key '%s' deleted\n", command);
1639 } else if (rc != ERROR_FILE_NOT_FOUND) {
1640 WCMD_print_error();
1641 errorlevel = 2;
1643 } else {
1644 char msgbuffer[MAXSTRING];
1645 char outbuffer[MAXSTRING];
1647 /* Load the translated 'File association not found' */
1648 LoadString (hinst, WCMD_NOASSOC, msgbuffer, sizeof(msgbuffer));
1649 sprintf(outbuffer, msgbuffer, keyValue);
1650 WCMD_output_asis(outbuffer);
1651 errorlevel = 2;
1654 /* It really is a set value = contents */
1655 } else {
1656 rc = RegCreateKeyEx(key, command, 0, NULL, REG_OPTION_NON_VOLATILE,
1657 accessOptions, NULL, &readKey, NULL);
1658 if (rc == ERROR_SUCCESS) {
1659 rc = RegSetValueEx(readKey, NULL, 0, REG_SZ,
1660 (LPBYTE)newValue, strlen(newValue));
1661 RegCloseKey(readKey);
1664 if (rc != ERROR_SUCCESS) {
1665 WCMD_print_error();
1666 errorlevel = 2;
1667 } else {
1668 WCMD_output_asis(command);
1669 WCMD_output_asis("=");
1670 WCMD_output_asis(newValue);
1671 WCMD_output_asis("\n");
1677 /* Clean up */
1678 RegCloseKey(key);
1681 /****************************************************************************
1682 * WCMD_color
1684 * Clear the terminal screen.
1687 void WCMD_color (void) {
1689 /* Emulate by filling the screen from the top left to bottom right with
1690 spaces, then moving the cursor to the top left afterwards */
1691 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
1692 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1694 if (param1[0] != 0x00 && strlen(param1) > 2) {
1695 WCMD_output ("Argument invalid\n");
1696 return;
1699 if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
1701 COORD topLeft;
1702 DWORD screenSize;
1703 DWORD color = 0;
1705 screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
1707 topLeft.X = 0;
1708 topLeft.Y = 0;
1710 /* Convert the color hex digits */
1711 if (param1[0] == 0x00) {
1712 color = defaultColor;
1713 } else {
1714 color = strtoul(param1, NULL, 16);
1717 /* Fail if fg == bg color */
1718 if (((color & 0xF0) >> 4) == (color & 0x0F)) {
1719 errorlevel = 1;
1720 return;
1723 /* Set the current screen contents and ensure all future writes
1724 remain this color */
1725 FillConsoleOutputAttribute(hStdOut, color, screenSize, topLeft, &screenSize);
1726 SetConsoleTextAttribute(hStdOut, color);