Support for nonstandard baud rate in SetCommState.
[wine] / dlls / msvcrt / console.c
1 /*
2  * msvcrt.dll console functions
3  *
4  * Copyright 2000 Jon Griffiths
5  *
6  * Note: init and free don't need MT locking since they are called at DLL
7  * (de)attachment time, which is syncronised for us
8  */
9 #include "msvcrt.h"
10 #include "wincon.h"
11
12 #include "msvcrt/conio.h"
13 #include "msvcrt/malloc.h"
14 #include "msvcrt/stdio.h"
15
16 #include "wine/debug.h"
17
18 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
19
20
21
22 /* MT */
23 extern CRITICAL_SECTION MSVCRT_console_cs;
24 #define LOCK_CONSOLE   EnterCriticalSection(&MSVCRT_console_cs)
25 #define UNLOCK_CONSOLE LeaveCriticalSection(&MSVCRT_console_cs)
26
27 static HANDLE MSVCRT_console_in = INVALID_HANDLE_VALUE;
28 static HANDLE MSVCRT_console_out= INVALID_HANDLE_VALUE;
29 static int __MSVCRT_console_buffer = MSVCRT_EOF;
30
31 /* INTERNAL: Initialise console handles */
32 void msvcrt_init_console(void)
33 {
34   TRACE(":Opening console handles\n");
35
36   MSVCRT_console_in = GetStdHandle(STD_INPUT_HANDLE);
37
38   /* FIXME: Should be initialised with:
39    * CreateFileA("CONIN$", GENERIC_READ, FILE_SHARE_READ,
40    * NULL, OPEN_EXISTING, 0, (HANDLE)NULL);
41    */
42
43   MSVCRT_console_out= CreateFileA("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE,
44                                     NULL, OPEN_EXISTING, 0, (HANDLE)NULL);
45
46   if ((MSVCRT_console_in == INVALID_HANDLE_VALUE) ||
47       (MSVCRT_console_out== INVALID_HANDLE_VALUE))
48     WARN(":Console handle Initialisation FAILED!\n");
49 }
50
51 /* INTERNAL: Free console handles */
52 void msvcrt_free_console(void)
53 {
54   TRACE(":Closing console handles\n");
55   CloseHandle(MSVCRT_console_in);
56   CloseHandle(MSVCRT_console_out);
57 }
58
59 /*********************************************************************
60  *              _cputs (MSVCRT.@)
61  */
62 int _cputs(const char* str)
63 {
64   DWORD count;
65   int retval = MSVCRT_EOF;
66
67   LOCK_CONSOLE;
68   if (WriteConsoleA(MSVCRT_console_out, str, strlen(str), &count, NULL)
69       && count == 1)
70     retval = 0;
71   UNLOCK_CONSOLE;
72   return retval;
73 }
74
75 /*********************************************************************
76  *              _getch (MSVCRT.@)
77  */
78 int _getch(void)
79 {
80   int retval = MSVCRT_EOF;
81
82   LOCK_CONSOLE;
83   if (__MSVCRT_console_buffer != MSVCRT_EOF)
84   {
85     retval = __MSVCRT_console_buffer;
86     __MSVCRT_console_buffer = MSVCRT_EOF;
87   }
88   else
89   {
90     INPUT_RECORD ir;
91     DWORD count;
92     DWORD mode = 0;
93
94     GetConsoleMode(MSVCRT_console_in, &mode);
95     if(mode)
96       SetConsoleMode(MSVCRT_console_in, 0);
97
98     do {
99       if (ReadConsoleInputA(MSVCRT_console_in, &ir, 1, &count))
100       {
101         /* Only interested in ASCII chars */
102         if (ir.EventType == KEY_EVENT &&
103             ir.Event.KeyEvent.bKeyDown &&
104             ir.Event.KeyEvent.uChar.AsciiChar)
105         {
106           retval = ir.Event.KeyEvent.uChar.AsciiChar;
107           break;
108         }
109       }
110       else
111         break;
112     } while(1);
113     if (mode)
114       SetConsoleMode(MSVCRT_console_in, mode);
115   }
116   UNLOCK_CONSOLE;
117   return retval;
118 }
119
120 /*********************************************************************
121  *              _putch (MSVCRT.@)
122  */
123 int _putch(int c)
124 {
125   int retval = MSVCRT_EOF;
126   DWORD count;
127   LOCK_CONSOLE;
128   if (WriteConsoleA(MSVCRT_console_out, &c, 1, &count, NULL) && count == 1)
129     retval = c;
130   UNLOCK_CONSOLE;
131   return retval;
132 }
133
134 /*********************************************************************
135  *              _getche (MSVCRT.@)
136  */
137 int _getche(void)
138 {
139   int retval;
140   LOCK_CONSOLE;
141   retval = _getch();
142   if (retval != MSVCRT_EOF)
143     retval = _putch(retval);
144   UNLOCK_CONSOLE;
145   return retval;
146 }
147
148 /*********************************************************************
149  *              _cgets (MSVCRT.@)
150  */
151 char* _cgets(char* str)
152 {
153   char *buf = str + 2;
154   int c;
155   str[1] = 0; /* Length */
156   /* FIXME: No editing of string supported */
157   LOCK_CONSOLE;
158   do
159   {
160     if (str[1] >= str[0] || (str[1]++, c = _getche()) == MSVCRT_EOF || c == '\n')
161       break;
162     *buf++ = c & 0xff;
163   } while (1);
164   UNLOCK_CONSOLE;
165   *buf = '\0';
166   return str + 2;
167 }
168
169 /*********************************************************************
170  *              _ungetch (MSVCRT.@)
171  */
172 int _ungetch(int c)
173 {
174   int retval = MSVCRT_EOF;
175   LOCK_CONSOLE;
176   if (c != MSVCRT_EOF && __MSVCRT_console_buffer == MSVCRT_EOF)
177     retval = __MSVCRT_console_buffer = c;
178   UNLOCK_CONSOLE;
179   return retval;
180 }
181
182 /* helper function for _cscanf.  Returns the value of character c in the
183  * given base, or -1 if the given character is not a digit of the base.
184  */
185 static int char2digit(char c, int base) {
186     if ((c>='0') && (c<='9') && (c<='0'+base-1)) return (c-'0');
187     if (base<=10) return -1;
188     if ((c>='A') && (c<='Z') && (c<='A'+base-11)) return (c-'A'+10);
189     if ((c>='a') && (c<='z') && (c<='a'+base-11)) return (c-'a'+10);
190     return -1;
191 }
192
193 /*********************************************************************
194  *              _cscanf (MSVCRT.@)
195  */
196 int _cscanf(const char* format, ...)
197 {
198     /* NOTE: If you extend this function, extend MSVCRT_fscanf in file.c too */
199     int rd = 0;
200     int nch;
201     va_list ap;
202     if (!*format) return 0;
203     WARN("\"%s\": semi-stub\n", format);
204     va_start(ap, format);
205   LOCK_CONSOLE;
206     nch = _getch();
207     while (*format) {
208         /* a whitespace character in the format string causes scanf to read,
209          * but not store, all consecutive white-space characters in the input
210          * up to the next non-white-space character.  One white space character
211          * in the input matches any number (including zero) and combination of
212          * white-space characters in the input. */
213         if (isspace(*format)) {
214             /* skip whitespace */
215             while ((nch!=MSVCRT_EOF) && isspace(nch))
216                 nch = _getch();
217         }
218         /* a format specification causes scanf to read and convert characters
219          * in the input into values of a specified type.  The value is assigned
220          * to an argument in the argument list.  Format specifications have
221          * the form %[*][width][{h | l | I64 | L}]type */
222         /* FIXME: unimplemented: h/l/I64/L modifiers and some type specs. */
223         else if (*format == '%') {
224             int st = 0; int suppress = 0; int width = 0;
225             int base, number_signed;
226             format++;
227             /* look for leading asterisk, which means 'suppress assignment of
228              * this field'. */
229             if (*format=='*') {
230                 format++;
231                 suppress=1;
232             }
233             /* look for width specification */
234             while (isdigit(*format)) {
235                 width*=10;
236                 width+=*format++ - '0';
237             }
238             if (width==0) width=-1; /* no width spec seen */
239             switch(*format) {
240             case '%': /* read a percent symbol */
241                 if (nch!='%') break;
242                 nch = _getch();
243                 break;
244             case 'x':
245             case 'X': /* hexadecimal integer. */
246                 base = 16; number_signed = 0;
247                 goto number;
248             case 'o': /* octal integer */
249                 base = 8; number_signed = 0;
250                 goto number;
251             case 'u': /* unsigned decimal integer */
252                 base = 10; number_signed = 0;
253                 goto number;
254             case 'd': /* signed decimal integer */
255                 base = 10; number_signed = 1;
256                 goto number;
257             case 'i': /* generic integer */
258                 base = 0; number_signed = 1;
259             number: {
260                     /* read an integer */
261                     int*val = suppress ? NULL : va_arg(ap, int*);
262                     int cur = 0; int negative = 0; int seendigit=0;
263                     /* skip initial whitespace */
264                     while ((nch!=MSVCRT_EOF) && isspace(nch))
265                         nch = _getch();
266                     /* get sign */
267                     if (number_signed && (nch == '-' || nch == '+')) {
268                         negative = (nch=='-');
269                         nch = _getch();
270                         if (width>0) width--;
271                     }
272                     /* look for leading indication of base */
273                     if (width!=0 && nch == '0') {
274                         nch = _getch();
275                         if (width>0) width--;
276                         seendigit=1;
277                         if (width!=0 && (nch=='x' || nch=='X')) {
278                             if (base==0)
279                                 base=16;
280                             if (base==16) {
281                                 nch = _getch();
282                                 if (width>0) width--;
283                                 seendigit=0;
284                             }
285                         } else if (base==0)
286                             base = 8;
287                     }
288                     if (base==0)
289                         base=10;
290                     /* throw away leading zeros */
291                     while (width!=0 && nch=='0') {
292                         nch = _getch();
293                         if (width>0) width--;
294                         seendigit=1;
295                     }
296                     /* get first digit.  Keep working copy negative, as the
297                      * range of negative numbers in two's complement notation
298                      * is one larger than the range of positive numbers. */
299                     if (width!=0 && char2digit(nch, base)!=-1) {
300                         cur = -char2digit(nch, base);
301                         nch = _getch();
302                         if (width>0) width--;
303                         seendigit=1;
304                     }
305                     /* read until no more digits */
306                     while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
307                         cur = cur*base + char2digit(nch, base);
308                         nch = _getch();
309                         if (width>0) width--;
310                         seendigit=1;
311                     }
312                     /* negate parsed number if non-negative */
313                     if (!negative) cur=-cur;
314                     /* okay, done! */
315                     if (!seendigit) break; /* not a valid number */
316                     st = 1;
317                     if (!suppress) *val = cur;
318                 }
319                 break;
320             case 'e':
321             case 'E':
322             case 'f':
323             case 'g':
324             case 'G': { /* read a float */
325                     float*val = suppress ? NULL : va_arg(ap, float*);
326                     float cur = 0;
327                     int negative = 0;
328                     /* skip initial whitespace */
329                     while ((nch!=MSVCRT_EOF) && isspace(nch))
330                         nch = _getch();
331                     /* get sign. */
332                     if (nch == '-' || nch == '+') {
333                         negative = (nch=='-');
334                         if (width>0) width--;
335                         if (width==0) break;
336                         nch = _getch();
337                     }
338                     /* get first digit. */
339                     if (!isdigit(nch)) break;
340                     cur = (nch - '0') * (negative ? -1 : 1);
341                     nch = _getch();
342                     if (width>0) width--;
343                     /* read until no more digits */
344                     while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
345                         cur = cur*10 + (nch - '0');
346                         nch = _getch();
347                         if (width>0) width--;
348                     }
349                     /* handle decimals */
350                     if (width!=0 && nch == '.') {
351                         float dec = 1;
352                         nch = _getch();
353                         if (width>0) width--;
354                         while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
355                             dec /= 10;
356                             cur += dec * (nch - '0');
357                             nch = _getch();
358                             if (width>0) width--;
359                         }
360                     }
361                     /* handle exponent */
362                     if (width!=0 && (nch == 'e' || nch == 'E')) {
363                         int exponent = 0, negexp = 0;
364                         float expcnt;
365                         nch = _getch();
366                         if (width>0) width--;
367                         /* possible sign on the exponent */
368                         if (width!=0 && (nch=='+' || nch=='-')) {
369                             negexp = (nch=='-');
370                             nch = _getch();
371                             if (width>0) width--;
372                         }
373                         /* exponent digits */
374                         while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
375                             exponent *= 10;
376                             exponent += (nch - '0');
377                             nch = _getch();
378                             if (width>0) width--;
379                         }
380                         /* update 'cur' with this exponent. */
381                         expcnt =  negexp ? .1 : 10;
382                         while (exponent!=0) {
383                             if (exponent&1)
384                                 cur*=expcnt;
385                             exponent/=2;
386                             expcnt=expcnt*expcnt;
387                         }
388                     }
389                     st = 1;
390                     if (!suppress) *val = cur;
391                 }
392                 break;
393             case 's': { /* read a word */
394                     char*str = suppress ? NULL : va_arg(ap, char*);
395                     char*sptr = str;
396                     /* skip initial whitespace */
397                     while ((nch!=MSVCRT_EOF) && isspace(nch))
398                         nch = _getch();
399                     /* read until whitespace */
400                     while (width!=0 && (nch!=MSVCRT_EOF) && !isspace(nch)) {
401                         if (!suppress) *sptr++ = nch;
402                         st++;
403                         nch = _getch();
404                         if (width>0) width--;
405                     }
406                     /* terminate */
407                     if (!suppress) *sptr = 0;
408                     TRACE("read word: %s\n", str);
409                 }
410                 break;
411             default: FIXME("unhandled: %%%c\n", *format);
412                 /* From spec: "if a percent sign is followed by a character
413                  * that has no meaning as a format-control character, that
414                  * character and the following characters are treated as
415                  * an ordinary sequence of characters, that is, a sequence
416                  * of characters that must match the input.  For example,
417                  * to specify that a percent-sign character is to be input,
418                  * use %%."
419                  * LEAVING AS-IS because we catch bugs better that way. */
420             }
421             if (st && !suppress) rd++;
422             else break;
423         }
424         /* a non-white-space character causes scanf to read, but not store,
425          * a matching non-white-space character. */
426         else {
427             /* check for character match */
428             if (nch == *format)
429                nch = _getch();
430             else break;
431         }
432         format++;
433     }
434     if (nch != MSVCRT_EOF)
435       _ungetch(nch);
436     UNLOCK_CONSOLE;
437     va_end(ap);
438     TRACE("returning %d\n", rd);
439     return rd;
440 }
441
442 /*********************************************************************
443  *              _kbhit (MSVCRT.@)
444  */
445 int _kbhit(void)
446 {
447   int retval = 0;
448
449   LOCK_CONSOLE;
450   if (__MSVCRT_console_buffer != MSVCRT_EOF)
451     retval = 1;
452   else
453   {
454     /* FIXME: There has to be a faster way than this in Win32.. */
455     INPUT_RECORD *ir = NULL;
456     DWORD count = 0, i;
457
458     GetNumberOfConsoleInputEvents(MSVCRT_console_in, &count);
459
460     if (count && (ir = MSVCRT_malloc(count * sizeof(INPUT_RECORD))) &&
461         PeekConsoleInputA(MSVCRT_console_in, ir, count, &count))
462       for(i = 0; i < count - 1; i++)
463       {
464         if (ir[i].EventType == KEY_EVENT &&
465             ir[i].Event.KeyEvent.bKeyDown &&
466             ir[i].Event.KeyEvent.uChar.AsciiChar)
467         {
468           retval = 1;
469           break;
470         }
471       }
472     if (ir)
473       MSVCRT_free(ir);
474   }
475   UNLOCK_CONSOLE;
476   return retval;
477 }
478
479
480 /*********************************************************************
481  *              _cprintf (MSVCRT.@)
482  */
483 int _cprintf(const char* format, ...)
484 {
485   char buf[2048], *mem = buf;
486   int written, resize = sizeof(buf), retval;
487   va_list valist;
488
489   va_start( valist, format );
490   /* There are two conventions for snprintf failing:
491    * Return -1 if we truncated, or
492    * Return the number of bytes that would have been written
493    * The code below handles both cases
494    */
495   while ((written = _snprintf( mem, resize, format, valist )) == -1 ||
496           written > resize)
497   {
498     resize = (written == -1 ? resize * 2 : written + 1);
499     if (mem != buf)
500       MSVCRT_free (mem);
501     if (!(mem = (char *)MSVCRT_malloc(resize)))
502       return MSVCRT_EOF;
503     va_start( valist, format );
504   }
505   va_end(valist);
506   LOCK_CONSOLE;
507   retval = _cputs( mem );
508   UNLOCK_CONSOLE;
509   if (mem != buf)
510     MSVCRT_free (mem);
511   return retval;
512 }