Handle generic column width changes.
[wine] / programs / wcmd / wcmdmain.c
1 /*
2  * WCMD - Wine-compatible command line interface.
3  *
4  * Copyright (C) 1999 - 2001 D A Pickles
5  *
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.
10  *
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.
15  *
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /*
22  * FIXME:
23  * - Cannot handle parameters in quotes
24  * - Lots of functionality missing from builtins
25  */
26
27 #include "wcmd.h"
28
29 char *inbuilt[] = {"ATTRIB", "CALL", "CD", "CHDIR", "CLS", "COPY", "CTTY",
30                 "DATE", "DEL", "DIR", "ECHO", "ERASE", "FOR", "GOTO",
31                 "HELP", "IF", "LABEL", "MD", "MKDIR", "MOVE", "PATH", "PAUSE",
32                 "PROMPT", "REM", "REN", "RENAME", "RD", "RMDIR", "SET", "SHIFT",
33                 "TIME", "TITLE", "TYPE", "VERIFY", "VER", "VOL", "EXIT"  };
34
35 HINSTANCE hinst;
36 DWORD errorlevel;
37 int echo_mode = 1, verify_mode = 0;
38 char nyi[] = "Not Yet Implemented\n\n";
39 char newline[] = "\n";
40 char version_string[] = "WCMD Version 0.17\n\n";
41 char anykey[] = "Press any key to continue: ";
42 char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
43 BATCH_CONTEXT *context = NULL;
44
45 /*****************************************************************************
46  * Main entry point. This is a console application so we have a main() not a
47  * winmain().
48  */
49
50 int main (int argc, char *argv[]) {
51
52 char string[1024], args[MAX_PATH], param[MAX_PATH];
53 int status, i;
54 DWORD count;
55 HANDLE h;
56
57   args[0] = param[0] = '\0';
58   if (argc > 1) {
59     for (i=1; i<argc; i++) {
60       if (argv[i][0] == '/') {
61         strcat (args, argv[i]);
62       }
63       else {
64         strcat (param, argv[i]);
65         strcat (param, " ");
66       }
67     }
68   }
69
70 /*
71  *      Allocate a console and set it up.
72  */
73
74   status = FreeConsole ();
75   if (!status) WCMD_print_error();
76   status = AllocConsole();
77   if (!status) WCMD_print_error();
78   SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT |
79         ENABLE_PROCESSED_INPUT);
80   SetConsoleTitle("Wine Command Prompt");
81
82 /*
83  *      Execute any command-line options.
84  */
85
86   if (strstr(args, "/q") != NULL) {
87     WCMD_echo ("OFF");
88   }
89
90   if (strstr(args, "/c") != NULL) {
91     WCMD_process_command (param);
92     return 0;
93   }
94
95   if (strstr(args, "/k") != NULL) {
96     WCMD_process_command (param);
97   }
98
99 /*
100  *      If there is an AUTOEXEC.BAT file, try to execute it.
101  */
102
103   GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
104   h = CreateFile (string, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
105   if (h != INVALID_HANDLE_VALUE) {
106     CloseHandle (h);
107 #if 0
108     WCMD_batch (string, " ");
109 #endif
110   }
111
112 /*
113  *      Loop forever getting commands and executing them.
114  */
115
116   WCMD_version ();
117   while (TRUE) {
118     WCMD_show_prompt ();
119     ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
120     if (count > 1) {
121       string[count-1] = '\0';           /* ReadFile output is not null-terminated! */
122       if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
123       if (lstrlen (string) != 0) {
124         if (strchr(string,'|') != NULL) {
125           WCMD_pipe (string);
126         }
127         else {
128           WCMD_process_command (string);
129         }
130       }
131     }
132   }
133 }
134
135
136 /*****************************************************************************
137  * Process one command. If the command is EXIT this routine does not return.
138  * We will recurse through here executing batch files.
139  */
140
141
142 void WCMD_process_command (char *command) {
143
144 char cmd[1024];
145 char *p;
146 int status, i;
147 DWORD count;
148 HANDLE old_stdin = 0, old_stdout = 0, h;
149 char *whichcmd;
150
151
152 /*
153  *      Expand up environment variables.
154  */
155
156     status = ExpandEnvironmentStrings (command, cmd, sizeof(cmd));
157     if (!status) {
158       WCMD_print_error ();
159       return;
160     }
161
162 /*
163  *      Changing default drive has to be handled as a special case.
164  */
165
166     if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
167       status = SetCurrentDirectory (cmd);
168       if (!status) WCMD_print_error ();
169       return;
170     }
171
172     /* Dont issue newline WCMD_output (newline);           @JED*/
173
174 /*
175  *      Redirect stdin and/or stdout if required.
176  */
177
178     if ((p = strchr(cmd,'<')) != NULL) {
179       h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, 0, NULL, OPEN_EXISTING,
180                 FILE_ATTRIBUTE_NORMAL, NULL);
181       if (h == INVALID_HANDLE_VALUE) {
182         WCMD_print_error ();
183         return;
184       }
185       old_stdin = GetStdHandle (STD_INPUT_HANDLE);
186       SetStdHandle (STD_INPUT_HANDLE, h);
187     }
188     if ((p = strchr(cmd,'>')) != NULL) {
189       h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
190                 FILE_ATTRIBUTE_NORMAL, NULL);
191       if (h == INVALID_HANDLE_VALUE) {
192         WCMD_print_error ();
193         return;
194       }
195       old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
196       SetStdHandle (STD_OUTPUT_HANDLE, h);
197       *--p = '\0';
198     }
199     if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
200
201 /*
202  * Strip leading whitespaces, and a '@' if supplied
203  */
204     whichcmd = WCMD_strtrim_leading_spaces(cmd);
205     if (whichcmd[0] == '@') whichcmd++;
206
207 /*
208  *      Check if the command entered is internal. If it is, pass the rest of the
209  *      line down to the command. If not try to run a program.
210  */
211
212     count = 0;
213     while (IsCharAlphaNumeric(whichcmd[count])) {
214       count++;
215     }
216     for (i=0; i<=WCMD_EXIT; i++) {
217       if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
218           whichcmd, count, inbuilt[i], -1) == 2) break;
219     }
220     p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
221     WCMD_parse (p, quals, param1, param2);
222     switch (i) {
223
224       case WCMD_ATTRIB:
225         WCMD_setshow_attrib ();
226         break;
227       case WCMD_CALL:
228         WCMD_batch (param1, p, 1);
229         break;
230       case WCMD_CD:
231       case WCMD_CHDIR:
232         WCMD_setshow_default ();
233         break;
234       case WCMD_CLS:
235         WCMD_clear_screen ();
236         break;
237       case WCMD_COPY:
238         WCMD_copy ();
239         break;
240       case WCMD_CTTY:
241         WCMD_change_tty ();
242         break;
243       case WCMD_DATE:
244         WCMD_setshow_date ();
245         break;
246       case WCMD_DEL:
247       case WCMD_ERASE:
248         WCMD_delete (0);
249         break;
250       case WCMD_DIR:
251         WCMD_directory ();
252         break;
253       case WCMD_ECHO:
254         /* Use the unstripped version of the following data - step over the space */
255         /* but only if a parameter follows                                        */
256         if (strlen(&whichcmd[count]) > 0)
257           WCMD_echo(&whichcmd[count+1]);
258         else
259           WCMD_echo(&whichcmd[count]);
260         break;
261       case WCMD_FOR:
262         WCMD_for (p);
263         break;
264       case WCMD_GOTO:
265         WCMD_goto ();
266         break;
267       case WCMD_HELP:
268         WCMD_give_help (p);
269         break;
270       case WCMD_IF:
271         WCMD_if (p);
272         break;
273       case WCMD_LABEL:
274         WCMD_volume (1, p);
275         break;
276       case WCMD_MD:
277       case WCMD_MKDIR:
278         WCMD_create_dir ();
279         break;
280       case WCMD_MOVE:
281         WCMD_move ();
282         break;
283       case WCMD_PATH:
284         WCMD_setshow_path ();
285         break;
286       case WCMD_PAUSE:
287         WCMD_pause ();
288         break;
289       case WCMD_PROMPT:
290         WCMD_setshow_prompt ();
291         break;
292       case WCMD_REM:
293         break;
294       case WCMD_REN:
295       case WCMD_RENAME:
296         WCMD_rename ();
297         break;
298       case WCMD_RD:
299       case WCMD_RMDIR:
300         WCMD_remove_dir ();
301         break;
302       case WCMD_SET:
303         WCMD_setshow_env (p);
304         break;
305       case WCMD_SHIFT:
306         WCMD_shift ();
307         break;
308       case WCMD_TIME:
309         WCMD_setshow_time ();
310         break;
311       case WCMD_TITLE:
312         if (strlen(&whichcmd[count]) > 0)
313           WCMD_title(&whichcmd[count+1]);
314         break;
315       case WCMD_TYPE:
316         WCMD_type ();
317         break;
318       case WCMD_VER:
319         WCMD_version ();
320         break;
321       case WCMD_VERIFY:
322         WCMD_verify (p);
323         break;
324       case WCMD_VOL:
325         WCMD_volume (0, p);
326         break;
327       case WCMD_EXIT:
328         ExitProcess (0);
329       default:
330         WCMD_run_program (whichcmd);
331     };
332     if (old_stdin) {
333       CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
334       SetStdHandle (STD_INPUT_HANDLE, old_stdin);
335     }
336     if (old_stdout) {
337       CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
338       SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
339     }
340   }
341
342 /******************************************************************************
343  * WCMD_run_program
344  *
345  *      Execute a command line as an external program. If no extension given then
346  *      precedence is given to .BAT files. Must allow recursion.
347  *
348  *      FIXME: Case sensitivity in suffixes!
349  */
350
351 void WCMD_run_program (char *command) {
352
353 STARTUPINFO st;
354 PROCESS_INFORMATION pe;
355 SHFILEINFO psfi;
356 DWORD console;
357 BOOL status;
358 HANDLE h;
359 HINSTANCE hinst;
360 char filetorun[MAX_PATH];
361
362   WCMD_parse (command, quals, param1, param2);  /* Quick way to get the filename */
363   if (!(*param1) && !(*param2))
364     return;
365   if (strpbrk (param1, "\\:") == NULL) {        /* No explicit path given */
366     if ((strchr (param1, '.') == NULL) || (strstr (param1, ".bat") != NULL)) {
367       if (SearchPath (NULL, param1, ".bat", sizeof(filetorun), filetorun, NULL)) {
368         WCMD_batch (filetorun, command, 0);
369         return;
370       }
371     }
372   }
373   else {                                        /* Explicit path given */
374     if (strstr (param1, ".bat") != NULL) {
375       WCMD_batch (param1, command, 0);
376       return;
377     }
378     if (strchr (param1, '.') == NULL) {
379       strcpy (filetorun, param1);
380       strcat (filetorun, ".bat");
381       h = CreateFile (filetorun, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
382       if (h != INVALID_HANDLE_VALUE) {
383         CloseHandle (h);
384         WCMD_batch (param1, command, 0);
385         return;
386       }
387     }
388   }
389
390         /* No batch file found, assume executable */
391
392   hinst = FindExecutable (param1, NULL, filetorun);
393   if ((int)hinst < 32) {
394     WCMD_print_error ();
395     return;
396   }
397   console = SHGetFileInfo (filetorun, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
398   ZeroMemory (&st, sizeof(STARTUPINFO));
399   st.cb = sizeof(STARTUPINFO);
400   status = CreateProcess (NULL, command, NULL, NULL, FALSE,
401                  0, NULL, NULL, &st, &pe);
402   if (!status) {
403     WCMD_print_error ();
404     return;
405   }
406   if (!console) errorlevel = 0;
407   else
408   {
409       if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
410       GetExitCodeProcess (pe.hProcess, &errorlevel);
411       if (errorlevel == STILL_ACTIVE) errorlevel = 0;
412   }
413 }
414
415 /******************************************************************************
416  * WCMD_show_prompt
417  *
418  *      Display the prompt on STDout
419  *
420  */
421
422 void WCMD_show_prompt () {
423
424 int status;
425 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
426 char *p, *q;
427
428   status = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
429   if ((status == 0) || (status > sizeof(prompt_string))) {
430     lstrcpy (prompt_string, "$N$G");
431   }
432   p = prompt_string;
433   q = out_string;
434   *q = '\0';
435   while (*p != '\0') {
436     if (*p != '$') {
437       *q++ = *p++;
438       *q = '\0';
439     }
440     else {
441       p++;
442       switch (toupper(*p)) {
443         case '$':
444           *q++ = '$';
445           break;
446         case 'B':
447           *q++ = '|';
448           break;
449         case 'D':
450           GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
451           while (*q) q++;
452           break;
453         case 'E':
454           *q++ = '\E';
455           break;
456         case 'G':
457           *q++ = '>';
458           break;
459         case 'L':
460           *q++ = '<';
461           break;
462         case 'N':
463           status = GetCurrentDirectory (sizeof(curdir), curdir);
464           if (status) {
465             *q++ = curdir[0];
466           }
467           break;
468         case 'P':
469           status = GetCurrentDirectory (sizeof(curdir), curdir);
470           if (status) {
471             lstrcat (q, curdir);
472             while (*q) q++;
473           }
474           break;
475         case 'Q':
476           *q++ = '=';
477           break;
478         case 'T':
479           GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
480           while (*q) q++;
481           break;
482         case '_':
483           *q++ = '\n';
484           break;
485       }
486       p++;
487       *q = '\0';
488     }
489   }
490   WCMD_output (out_string);
491 }
492
493 /****************************************************************************
494  * WCMD_print_error
495  *
496  * Print the message for GetLastError
497  */
498
499 void WCMD_print_error () {
500 LPVOID lpMsgBuf;
501 DWORD error_code;
502 int status;
503
504   error_code = GetLastError ();
505   status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
506                         NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
507   if (!status) {
508     WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
509                         error_code, GetLastError());
510     return;
511   }
512   WCMD_output (lpMsgBuf);
513   LocalFree ((HLOCAL)lpMsgBuf);
514   WCMD_output (newline);
515   return;
516 }
517
518 /*******************************************************************
519  * WCMD_parse - parse a command into parameters and qualifiers.
520  *
521  *      On exit, all qualifiers are concatenated into q, the first string
522  *      not beginning with "/" is in p1 and the
523  *      second in p2. Any subsequent non-qualifier strings are lost.
524  *      Parameters in quotes are handled.
525  */
526
527 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
528
529 int p = 0;
530
531   *q = *p1 = *p2 = '\0';
532   while (TRUE) {
533     switch (*s) {
534       case '/':
535         *q++ = *s++;
536         while ((*s != '\0') && (*s != ' ') && *s != '/') {
537           *q++ = toupper (*s++);
538         }
539         *q = '\0';
540         break;
541       case ' ':
542         s++;
543         break;
544       case '"':
545         s++;
546         while ((*s != '\0') && (*s != '"')) {
547           if (p == 0) *p1++ = *s++;
548           else if (p == 1) *p2++ = *s++;
549           else s++;
550         }
551         if (p == 0) *p1 = '\0';
552         if (p == 1) *p2 = '\0';
553         p++;
554         if (*s == '"') s++;
555         break;
556       case '\0':
557         return;
558       default:
559         while ((*s != '\0') && (*s != ' ')) {
560           if (p == 0) *p1++ = *s++;
561           else if (p == 1) *p2++ = *s++;
562           else s++;
563         }
564         if (p == 0) *p1 = '\0';
565         if (p == 1) *p2 = '\0';
566         p++;
567     }
568   }
569 }
570
571 /*******************************************************************
572  * WCMD_output - send output to current standard output device.
573  *
574  */
575
576 void WCMD_output (char *format, ...) {
577
578 va_list ap;
579 char string[1024];
580 DWORD count;
581
582   va_start(ap,format);
583   vsprintf (string, format, ap);
584   WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), string, lstrlen(string), &count, NULL);
585   va_end(ap);
586 }
587
588 /*******************************************************************
589  * WCMD_output_asis - send output to current standard output device.
590  *        without formatting eg. when message contains '%'
591  */
592
593 void WCMD_output_asis (char *message) {
594   DWORD count;
595   WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
596 }
597
598
599
600 /***************************************************************************
601  * WCMD_strtrim_leading_spaces
602  *
603  *      Remove leading spaces from a string. Return a pointer to the first
604  *      non-space character. Does not modify the input string
605  */
606
607 char *WCMD_strtrim_leading_spaces (char *string) {
608
609 char *ptr;
610
611   ptr = string;
612   while (*ptr == ' ') ptr++;
613   return ptr;
614 }
615
616 /*************************************************************************
617  * WCMD_strtrim_trailing_spaces
618  *
619  *      Remove trailing spaces from a string. This routine modifies the input
620  *      string by placing a null after the last non-space character
621  */
622
623 void WCMD_strtrim_trailing_spaces (char *string) {
624
625 char *ptr;
626
627   ptr = string + lstrlen (string) - 1;
628   while ((*ptr == ' ') && (ptr >= string)) {
629     *ptr = '\0';
630     ptr--;
631   }
632 }
633
634 /*************************************************************************
635  * WCMD_pipe
636  *
637  *      Handle pipes within a command - the DOS way using temporary files.
638  */
639
640 void WCMD_pipe (char *command) {
641
642 char *p;
643 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
644
645   GetTempPath (sizeof(temp_path), temp_path);
646   GetTempFileName (temp_path, "WCMD", 0, temp_file);
647   p = strchr(command, '|');
648   *p++ = '\0';
649   wsprintf (temp_cmd, "%s > %s", command, temp_file);
650   WCMD_process_command (temp_cmd);
651   command = p;
652   while ((p = strchr(command, '|'))) {
653     *p++ = '\0';
654     GetTempFileName (temp_path, "WCMD", 0, temp_file2);
655     wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
656     WCMD_process_command (temp_cmd);
657     DeleteFile (temp_file);
658     lstrcpy (temp_file, temp_file2);
659     command = p;
660   }
661   wsprintf (temp_cmd, "%s < %s", command, temp_file);
662   WCMD_process_command (temp_cmd);
663   DeleteFile (temp_file);
664 }