kernel32: Improve parameter validation for WriteConsoleOutputCharacterW.
[wine] / dlls / kernel32 / console.c
1 /*
2  * Win32 console functions
3  *
4  * Copyright 1995 Martin von Loewis and Cameron Heide
5  * Copyright 1997 Karl Garrison
6  * Copyright 1998 John Richardson
7  * Copyright 1998 Marcus Meissner
8  * Copyright 2001,2002,2004,2005 Eric Pouech
9  * Copyright 2001 Alexandre Julliard
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 /* Reference applications:
27  * -  IDA (interactive disassembler) full version 3.75. Works.
28  * -  LYNX/W32. Works mostly, some keys crash it.
29  */
30
31 #include "config.h"
32 #include "wine/port.h"
33
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <string.h>
37 #ifdef HAVE_UNISTD_H
38 # include <unistd.h>
39 #endif
40 #include <assert.h>
41 #ifdef HAVE_TERMIOS_H
42 # include <termios.h>
43 #endif
44 #ifdef HAVE_SYS_POLL_H
45 # include <sys/poll.h>
46 #endif
47
48 #include "ntstatus.h"
49 #define WIN32_NO_STATUS
50 #include "windef.h"
51 #include "winbase.h"
52 #include "winnls.h"
53 #include "winerror.h"
54 #include "wincon.h"
55 #include "wine/server.h"
56 #include "wine/exception.h"
57 #include "wine/unicode.h"
58 #include "wine/debug.h"
59 #include "excpt.h"
60 #include "console_private.h"
61 #include "kernel_private.h"
62
63 WINE_DEFAULT_DEBUG_CHANNEL(console);
64
65 static CRITICAL_SECTION CONSOLE_CritSect;
66 static CRITICAL_SECTION_DEBUG critsect_debug =
67 {
68     0, 0, &CONSOLE_CritSect,
69     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
70       0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
71 };
72 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
73
74 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
75 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
76
77 /* FIXME: this is not thread safe */
78 static HANDLE console_wait_event;
79
80 /* map input records to ASCII */
81 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
82 {
83     int i;
84     char ch;
85
86     for (i = 0; i < count; i++)
87     {
88         if (buffer[i].EventType != KEY_EVENT) continue;
89         WideCharToMultiByte( GetConsoleCP(), 0,
90                              &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
91         buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
92     }
93 }
94
95 /* map input records to Unicode */
96 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
97 {
98     int i;
99     WCHAR ch;
100
101     for (i = 0; i < count; i++)
102     {
103         if (buffer[i].EventType != KEY_EVENT) continue;
104         MultiByteToWideChar( GetConsoleCP(), 0,
105                              &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
106         buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
107     }
108 }
109
110 /* map char infos to ASCII */
111 static void char_info_WtoA( CHAR_INFO *buffer, int count )
112 {
113     char ch;
114
115     while (count-- > 0)
116     {
117         WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
118                              &ch, 1, NULL, NULL );
119         buffer->Char.AsciiChar = ch;
120         buffer++;
121     }
122 }
123
124 /* map char infos to Unicode */
125 static void char_info_AtoW( CHAR_INFO *buffer, int count )
126 {
127     WCHAR ch;
128
129     while (count-- > 0)
130     {
131         MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
132         buffer->Char.UnicodeChar = ch;
133         buffer++;
134     }
135 }
136
137 static struct termios S_termios;        /* saved termios for bare consoles */
138 static BOOL S_termios_raw /* = FALSE */;
139
140 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
141  * - a bare console is created for all CUI programs started from command line (without
142  *   wineconsole) (let's call those PS)
143  * - of course, every child of a PS which requires console inheritance will get it
144  * - the console termios attributes are saved at the start of program which is attached to be
145  *   bare console
146  * - if any program attached to a bare console requests input from console, the console is
147  *   turned into raw mode
148  * - when the program which created the bare console (the program started from command line)
149  *   exits, it will restore the console termios attributes it saved at startup (this
150  *   will put back the console into cooked mode if it had been put in raw mode)
151  * - if any other program attached to this bare console is still alive, the Unix shell will put
152  *   it in the background, hence forbidding access to the console. Therefore, reading console
153  *   input will not be available when the bare console creator has died.
154  *   FIXME: This is a limitation of current implementation
155  */
156
157 /* returns the fd for a bare console (-1 otherwise) */
158 static int  get_console_bare_fd(HANDLE hin)
159 {
160     int         fd;
161
162     if (wine_server_handle_to_fd(wine_server_ptr_handle(console_handle_unmap(hin)),
163                                  0, &fd, NULL) == STATUS_SUCCESS)
164         return fd;
165     return -1;
166 }
167
168 static BOOL save_console_mode(HANDLE hin)
169 {
170     int         fd;
171     BOOL        ret;
172
173     if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
174     ret = tcgetattr(fd, &S_termios) >= 0;
175     close(fd);
176     return ret;
177 }
178
179 static BOOL put_console_into_raw_mode(int fd)
180 {
181     RtlEnterCriticalSection(&CONSOLE_CritSect);
182     if (!S_termios_raw)
183     {
184         struct termios term = S_termios;
185
186         term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
187         term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
188         term.c_cflag &= ~(CSIZE | PARENB);
189         term.c_cflag |= CS8;
190         /* FIXME: we should actually disable output processing here
191          * and let kernel32/console.c do the job (with support of enable/disable of
192          * processed output)
193          */
194         /* term.c_oflag &= ~(OPOST); */
195         term.c_cc[VMIN] = 1;
196         term.c_cc[VTIME] = 0;
197         S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
198     }
199     RtlLeaveCriticalSection(&CONSOLE_CritSect);
200
201     return S_termios_raw;
202 }
203
204 /* put back the console in cooked mode iff we're the process which created the bare console
205  * we don't test if thie process has set the console in raw mode as it could be one of its
206  * child who did it
207  */
208 static BOOL restore_console_mode(HANDLE hin)
209 {
210     int         fd;
211     BOOL        ret;
212
213     if (!S_termios_raw ||
214         RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
215         return TRUE;
216     if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
217     ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
218     close(fd);
219     return ret;
220 }
221
222 /******************************************************************************
223  * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
224  *
225  * RETURNS
226  *   Success: hwnd of the console window.
227  *   Failure: NULL
228  */
229 HWND WINAPI GetConsoleWindow(VOID)
230 {
231     HWND hWnd = NULL;
232
233     SERVER_START_REQ(get_console_input_info)
234     {
235         req->handle = 0;
236         if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
237     }
238     SERVER_END_REQ;
239
240     return hWnd;
241 }
242
243
244 /******************************************************************************
245  * GetConsoleCP [KERNEL32.@]  Returns the OEM code page for the console
246  *
247  * RETURNS
248  *    Code page code
249  */
250 UINT WINAPI GetConsoleCP(VOID)
251 {
252     BOOL ret;
253     UINT codepage = GetOEMCP(); /* default value */
254
255     SERVER_START_REQ(get_console_input_info)
256     {
257         req->handle = 0;
258         ret = !wine_server_call_err(req);
259         if (ret && reply->input_cp)
260             codepage = reply->input_cp;
261     }
262     SERVER_END_REQ;
263
264     return codepage;
265 }
266
267
268 /******************************************************************************
269  *  SetConsoleCP         [KERNEL32.@]
270  */
271 BOOL WINAPI SetConsoleCP(UINT cp)
272 {
273     BOOL ret;
274
275     if (!IsValidCodePage(cp))
276     {
277         SetLastError(ERROR_INVALID_PARAMETER);
278         return FALSE;
279     }
280
281     SERVER_START_REQ(set_console_input_info)
282     {
283         req->handle   = 0;
284         req->mask     = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
285         req->input_cp = cp;
286         ret = !wine_server_call_err(req);
287     }
288     SERVER_END_REQ;
289
290     return ret;
291 }
292
293
294 /***********************************************************************
295  *            GetConsoleOutputCP   (KERNEL32.@)
296  */
297 UINT WINAPI GetConsoleOutputCP(VOID)
298 {
299     BOOL ret;
300     UINT codepage = GetOEMCP(); /* default value */
301
302     SERVER_START_REQ(get_console_input_info)
303     {
304         req->handle = 0;
305         ret = !wine_server_call_err(req);
306         if (ret && reply->output_cp)
307             codepage = reply->output_cp;
308     }
309     SERVER_END_REQ;
310
311     return codepage;
312 }
313
314
315 /******************************************************************************
316  * SetConsoleOutputCP [KERNEL32.@]  Set the output codepage used by the console
317  *
318  * PARAMS
319  *    cp [I] code page to set
320  *
321  * RETURNS
322  *    Success: TRUE
323  *    Failure: FALSE
324  */
325 BOOL WINAPI SetConsoleOutputCP(UINT cp)
326 {
327     BOOL ret;
328
329     if (!IsValidCodePage(cp))
330     {
331         SetLastError(ERROR_INVALID_PARAMETER);
332         return FALSE;
333     }
334
335     SERVER_START_REQ(set_console_input_info)
336     {
337         req->handle   = 0;
338         req->mask     = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
339         req->output_cp = cp;
340         ret = !wine_server_call_err(req);
341     }
342     SERVER_END_REQ;
343
344     return ret;
345 }
346
347
348 /***********************************************************************
349  *           Beep   (KERNEL32.@)
350  */
351 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
352 {
353     static const char beep = '\a';
354     /* dwFreq and dwDur are ignored by Win95 */
355     if (isatty(2)) write( 2, &beep, 1 );
356     return TRUE;
357 }
358
359
360 /******************************************************************
361  *              OpenConsoleW            (KERNEL32.@)
362  *
363  * Undocumented
364  *      Open a handle to the current process console.
365  *      Returns INVALID_HANDLE_VALUE on failure.
366  */
367 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
368 {
369     HANDLE      output = INVALID_HANDLE_VALUE;
370     HANDLE      ret;
371
372     TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
373
374     if (name)
375     {
376         if (strcmpiW(coninW, name) == 0)
377             output = (HANDLE) FALSE;
378         else if (strcmpiW(conoutW, name) == 0)
379             output = (HANDLE) TRUE;
380     }
381
382     if (output == INVALID_HANDLE_VALUE)
383     {
384         SetLastError(ERROR_INVALID_PARAMETER);
385         return INVALID_HANDLE_VALUE;
386     }
387     else if (creation != OPEN_EXISTING)
388     {
389         if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
390             SetLastError(ERROR_SHARING_VIOLATION);
391         else
392             SetLastError(ERROR_INVALID_PARAMETER);
393         return INVALID_HANDLE_VALUE;
394     }
395
396     SERVER_START_REQ( open_console )
397     {
398         req->from       = wine_server_obj_handle( output );
399         req->access     = access;
400         req->attributes = inherit ? OBJ_INHERIT : 0;
401         req->share      = FILE_SHARE_READ | FILE_SHARE_WRITE;
402         wine_server_call_err( req );
403         ret = wine_server_ptr_handle( reply->handle );
404     }
405     SERVER_END_REQ;
406     if (ret)
407         ret = console_handle_map(ret);
408
409     return ret;
410 }
411
412 /******************************************************************
413  *              VerifyConsoleIoHandle            (KERNEL32.@)
414  *
415  * Undocumented
416  */
417 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
418 {
419     BOOL ret;
420
421     if (!is_console_handle(handle)) return FALSE;
422     SERVER_START_REQ(get_console_mode)
423     {
424         req->handle = console_handle_unmap(handle);
425         ret = !wine_server_call( req );
426     }
427     SERVER_END_REQ;
428     return ret;
429 }
430
431 /******************************************************************
432  *              DuplicateConsoleHandle            (KERNEL32.@)
433  *
434  * Undocumented
435  */
436 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
437                                      DWORD options)
438 {
439     HANDLE      ret;
440
441     if (!is_console_handle(handle) ||
442         !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
443                          GetCurrentProcess(), &ret, access, inherit, options))
444         return INVALID_HANDLE_VALUE;
445     return console_handle_map(ret);
446 }
447
448 /******************************************************************
449  *              CloseConsoleHandle            (KERNEL32.@)
450  *
451  * Undocumented
452  */
453 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
454 {
455     if (!is_console_handle(handle)) 
456     {
457         SetLastError(ERROR_INVALID_PARAMETER);
458         return FALSE;
459     }
460     return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
461 }
462
463 /******************************************************************
464  *              GetConsoleInputWaitHandle            (KERNEL32.@)
465  *
466  * Undocumented
467  */
468 HANDLE WINAPI GetConsoleInputWaitHandle(void)
469 {
470     if (!console_wait_event)
471     {
472         SERVER_START_REQ(get_console_wait_event)
473         {
474             if (!wine_server_call_err( req ))
475                 console_wait_event = wine_server_ptr_handle( reply->handle );
476         }
477         SERVER_END_REQ;
478     }
479     return console_wait_event;
480 }
481
482
483 /******************************************************************************
484  * WriteConsoleInputA [KERNEL32.@]
485  */
486 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
487                                 DWORD count, LPDWORD written )
488 {
489     INPUT_RECORD *recW = NULL;
490     BOOL ret;
491
492     if (count > 0)
493     {
494         if (!buffer)
495         {
496             SetLastError( ERROR_INVALID_ACCESS );
497             return FALSE;
498         }
499
500         if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) )))
501         {
502             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
503             return FALSE;
504         }
505
506         memcpy( recW, buffer, count * sizeof(*recW) );
507         input_records_AtoW( recW, count );
508     }
509
510     ret = WriteConsoleInputW( handle, recW, count, written );
511     HeapFree( GetProcessHeap(), 0, recW );
512     return ret;
513 }
514
515
516 /******************************************************************************
517  * WriteConsoleInputW [KERNEL32.@]
518  */
519 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
520                                 DWORD count, LPDWORD written )
521 {
522     DWORD events_written = 0;
523     BOOL ret;
524
525     TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
526
527     if (count > 0 && !buffer)
528     {
529         SetLastError(ERROR_INVALID_ACCESS);
530         return FALSE;
531     }
532
533     SERVER_START_REQ( write_console_input )
534     {
535         req->handle = console_handle_unmap(handle);
536         wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
537         if ((ret = !wine_server_call_err( req )))
538             events_written = reply->written;
539     }
540     SERVER_END_REQ;
541
542     if (written) *written = events_written;
543     else
544     {
545         SetLastError(ERROR_INVALID_ACCESS);
546         ret = FALSE;
547     }
548     return ret;
549 }
550
551
552 /***********************************************************************
553  *            WriteConsoleOutputA   (KERNEL32.@)
554  */
555 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
556                                  COORD size, COORD coord, LPSMALL_RECT region )
557 {
558     int y;
559     BOOL ret;
560     COORD new_size, new_coord;
561     CHAR_INFO *ciw;
562
563     new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
564     new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
565
566     if (new_size.X <= 0 || new_size.Y <= 0)
567     {
568         region->Bottom = region->Top + new_size.Y - 1;
569         region->Right = region->Left + new_size.X - 1;
570         return TRUE;
571     }
572
573     /* only copy the useful rectangle */
574     if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
575         return FALSE;
576     for (y = 0; y < new_size.Y; y++)
577     {
578         memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
579                 new_size.X * sizeof(CHAR_INFO) );
580         char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
581     }
582     new_coord.X = new_coord.Y = 0;
583     ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
584     HeapFree( GetProcessHeap(), 0, ciw );
585     return ret;
586 }
587
588
589 /***********************************************************************
590  *            WriteConsoleOutputW   (KERNEL32.@)
591  */
592 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
593                                  COORD size, COORD coord, LPSMALL_RECT region )
594 {
595     int width, height, y;
596     BOOL ret = TRUE;
597
598     TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
599           hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
600           region->Left, region->Top, region->Right, region->Bottom);
601
602     width = min( region->Right - region->Left + 1, size.X - coord.X );
603     height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
604
605     if (width > 0 && height > 0)
606     {
607         for (y = 0; y < height; y++)
608         {
609             SERVER_START_REQ( write_console_output )
610             {
611                 req->handle = console_handle_unmap(hConsoleOutput);
612                 req->x      = region->Left;
613                 req->y      = region->Top + y;
614                 req->mode   = CHAR_INFO_MODE_TEXTATTR;
615                 req->wrap   = FALSE;
616                 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
617                                       width * sizeof(CHAR_INFO));
618                 if ((ret = !wine_server_call_err( req )))
619                 {
620                     width  = min( width, reply->width - region->Left );
621                     height = min( height, reply->height - region->Top );
622                 }
623             }
624             SERVER_END_REQ;
625             if (!ret) break;
626         }
627     }
628     region->Bottom = region->Top + height - 1;
629     region->Right = region->Left + width - 1;
630     return ret;
631 }
632
633
634 /******************************************************************************
635  * WriteConsoleOutputCharacterA [KERNEL32.@]
636  *
637  * See WriteConsoleOutputCharacterW.
638  */
639 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
640                                           COORD coord, LPDWORD lpNumCharsWritten )
641 {
642     BOOL ret;
643     LPWSTR strW;
644     DWORD lenW;
645
646     TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
647           debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
648
649     lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
650
651     if (lpNumCharsWritten) *lpNumCharsWritten = 0;
652
653     if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
654     MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
655
656     ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
657     HeapFree( GetProcessHeap(), 0, strW );
658     return ret;
659 }
660
661
662 /******************************************************************************
663  * WriteConsoleOutputAttribute [KERNEL32.@]  Sets attributes for some cells in
664  *                                           the console screen buffer
665  *
666  * PARAMS
667  *    hConsoleOutput    [I] Handle to screen buffer
668  *    attr              [I] Pointer to buffer with write attributes
669  *    length            [I] Number of cells to write to
670  *    coord             [I] Coords of first cell
671  *    lpNumAttrsWritten [O] Pointer to number of cells written
672  *
673  * RETURNS
674  *    Success: TRUE
675  *    Failure: FALSE
676  *
677  */
678 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
679                                          COORD coord, LPDWORD lpNumAttrsWritten )
680 {
681     BOOL ret;
682
683     TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
684
685     SERVER_START_REQ( write_console_output )
686     {
687         req->handle = console_handle_unmap(hConsoleOutput);
688         req->x      = coord.X;
689         req->y      = coord.Y;
690         req->mode   = CHAR_INFO_MODE_ATTR;
691         req->wrap   = TRUE;
692         wine_server_add_data( req, attr, length * sizeof(WORD) );
693         if ((ret = !wine_server_call_err( req )))
694         {
695             if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
696         }
697     }
698     SERVER_END_REQ;
699     return ret;
700 }
701
702
703 /******************************************************************************
704  * FillConsoleOutputCharacterA [KERNEL32.@]
705  *
706  * See FillConsoleOutputCharacterW.
707  */
708 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
709                                          COORD coord, LPDWORD lpNumCharsWritten )
710 {
711     WCHAR wch;
712
713     MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
714     return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
715 }
716
717
718 /******************************************************************************
719  * FillConsoleOutputCharacterW [KERNEL32.@]  Writes characters to console
720  *
721  * PARAMS
722  *    hConsoleOutput    [I] Handle to screen buffer
723  *    ch                [I] Character to write
724  *    length            [I] Number of cells to write to
725  *    coord             [I] Coords of first cell
726  *    lpNumCharsWritten [O] Pointer to number of cells written
727  *
728  * RETURNS
729  *    Success: TRUE
730  *    Failure: FALSE
731  */
732 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
733                                          COORD coord, LPDWORD lpNumCharsWritten)
734 {
735     BOOL ret;
736
737     TRACE("(%p,%s,%d,(%dx%d),%p)\n",
738           hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
739
740     SERVER_START_REQ( fill_console_output )
741     {
742         req->handle  = console_handle_unmap(hConsoleOutput);
743         req->x       = coord.X;
744         req->y       = coord.Y;
745         req->mode    = CHAR_INFO_MODE_TEXT;
746         req->wrap    = TRUE;
747         req->data.ch = ch;
748         req->count   = length;
749         if ((ret = !wine_server_call_err( req )))
750         {
751             if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
752         }
753     }
754     SERVER_END_REQ;
755     return ret;
756 }
757
758
759 /******************************************************************************
760  * FillConsoleOutputAttribute [KERNEL32.@]  Sets attributes for console
761  *
762  * PARAMS
763  *    hConsoleOutput    [I] Handle to screen buffer
764  *    attr              [I] Color attribute to write
765  *    length            [I] Number of cells to write to
766  *    coord             [I] Coords of first cell
767  *    lpNumAttrsWritten [O] Pointer to number of cells written
768  *
769  * RETURNS
770  *    Success: TRUE
771  *    Failure: FALSE
772  */
773 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
774                                         COORD coord, LPDWORD lpNumAttrsWritten )
775 {
776     BOOL ret;
777
778     TRACE("(%p,%d,%d,(%dx%d),%p)\n",
779           hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
780
781     SERVER_START_REQ( fill_console_output )
782     {
783         req->handle    = console_handle_unmap(hConsoleOutput);
784         req->x         = coord.X;
785         req->y         = coord.Y;
786         req->mode      = CHAR_INFO_MODE_ATTR;
787         req->wrap      = TRUE;
788         req->data.attr = attr;
789         req->count     = length;
790         if ((ret = !wine_server_call_err( req )))
791         {
792             if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
793         }
794     }
795     SERVER_END_REQ;
796     return ret;
797 }
798
799
800 /******************************************************************************
801  * ReadConsoleOutputCharacterA [KERNEL32.@]
802  *
803  */
804 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
805                                         COORD coord, LPDWORD read_count)
806 {
807     DWORD read;
808     BOOL ret;
809     LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
810
811     if (read_count) *read_count = 0;
812     if (!wptr) return FALSE;
813
814     if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
815     {
816         read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
817         if (read_count) *read_count = read;
818     }
819     HeapFree( GetProcessHeap(), 0, wptr );
820     return ret;
821 }
822
823
824 /******************************************************************************
825  * ReadConsoleOutputCharacterW [KERNEL32.@]
826  *
827  */
828 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
829                                          COORD coord, LPDWORD read_count )
830 {
831     BOOL ret;
832
833     TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
834
835     SERVER_START_REQ( read_console_output )
836     {
837         req->handle = console_handle_unmap(hConsoleOutput);
838         req->x      = coord.X;
839         req->y      = coord.Y;
840         req->mode   = CHAR_INFO_MODE_TEXT;
841         req->wrap   = TRUE;
842         wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
843         if ((ret = !wine_server_call_err( req )))
844         {
845             if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
846         }
847     }
848     SERVER_END_REQ;
849     return ret;
850 }
851
852
853 /******************************************************************************
854  *  ReadConsoleOutputAttribute [KERNEL32.@]
855  */
856 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
857                                        COORD coord, LPDWORD read_count)
858 {
859     BOOL ret;
860
861     TRACE("(%p,%p,%d,%dx%d,%p)\n",
862           hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
863
864     SERVER_START_REQ( read_console_output )
865     {
866         req->handle = console_handle_unmap(hConsoleOutput);
867         req->x      = coord.X;
868         req->y      = coord.Y;
869         req->mode   = CHAR_INFO_MODE_ATTR;
870         req->wrap   = TRUE;
871         wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
872         if ((ret = !wine_server_call_err( req )))
873         {
874             if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
875         }
876     }
877     SERVER_END_REQ;
878     return ret;
879 }
880
881
882 /******************************************************************************
883  *  ReadConsoleOutputA [KERNEL32.@]
884  *
885  */
886 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
887                                 COORD coord, LPSMALL_RECT region )
888 {
889     BOOL ret;
890     int y;
891
892     ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
893     if (ret && region->Right >= region->Left)
894     {
895         for (y = 0; y <= region->Bottom - region->Top; y++)
896         {
897             char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
898                             region->Right - region->Left + 1 );
899         }
900     }
901     return ret;
902 }
903
904
905 /******************************************************************************
906  *  ReadConsoleOutputW [KERNEL32.@]
907  *
908  * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
909  * think we need to be *that* compatible.  -- AJ
910  */
911 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
912                                 COORD coord, LPSMALL_RECT region )
913 {
914     int width, height, y;
915     BOOL ret = TRUE;
916
917     width = min( region->Right - region->Left + 1, size.X - coord.X );
918     height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
919
920     if (width > 0 && height > 0)
921     {
922         for (y = 0; y < height; y++)
923         {
924             SERVER_START_REQ( read_console_output )
925             {
926                 req->handle = console_handle_unmap(hConsoleOutput);
927                 req->x      = region->Left;
928                 req->y      = region->Top + y;
929                 req->mode   = CHAR_INFO_MODE_TEXTATTR;
930                 req->wrap   = FALSE;
931                 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
932                                        width * sizeof(CHAR_INFO) );
933                 if ((ret = !wine_server_call_err( req )))
934                 {
935                     width  = min( width, reply->width - region->Left );
936                     height = min( height, reply->height - region->Top );
937                 }
938             }
939             SERVER_END_REQ;
940             if (!ret) break;
941         }
942     }
943     region->Bottom = region->Top + height - 1;
944     region->Right = region->Left + width - 1;
945     return ret;
946 }
947
948
949 /******************************************************************************
950  * ReadConsoleInputA [KERNEL32.@]  Reads data from a console
951  *
952  * PARAMS
953  *    handle   [I] Handle to console input buffer
954  *    buffer   [O] Address of buffer for read data
955  *    count    [I] Number of records to read
956  *    pRead    [O] Address of number of records read
957  *
958  * RETURNS
959  *    Success: TRUE
960  *    Failure: FALSE
961  */
962 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
963 {
964     DWORD read;
965
966     if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
967     input_records_WtoA( buffer, read );
968     if (pRead) *pRead = read;
969     return TRUE;
970 }
971
972
973 /***********************************************************************
974  *            PeekConsoleInputA   (KERNEL32.@)
975  *
976  * Gets 'count' first events (or less) from input queue.
977  */
978 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
979 {
980     DWORD read;
981
982     if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
983     input_records_WtoA( buffer, read );
984     if (pRead) *pRead = read;
985     return TRUE;
986 }
987
988
989 /***********************************************************************
990  *            PeekConsoleInputW   (KERNEL32.@)
991  */
992 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
993 {
994     BOOL ret;
995     SERVER_START_REQ( read_console_input )
996     {
997         req->handle = console_handle_unmap(handle);
998         req->flush  = FALSE;
999         wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1000         if ((ret = !wine_server_call_err( req )))
1001         {
1002             if (read) *read = count ? reply->read : 0;
1003         }
1004     }
1005     SERVER_END_REQ;
1006     return ret;
1007 }
1008
1009
1010 /***********************************************************************
1011  *            GetNumberOfConsoleInputEvents   (KERNEL32.@)
1012  */
1013 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1014 {
1015     BOOL ret;
1016     SERVER_START_REQ( read_console_input )
1017     {
1018         req->handle = console_handle_unmap(handle);
1019         req->flush  = FALSE;
1020         if ((ret = !wine_server_call_err( req )))
1021         {
1022             if (nrofevents)
1023                 *nrofevents = reply->read;
1024             else
1025             {
1026                 SetLastError(ERROR_INVALID_ACCESS);
1027                 ret = FALSE;
1028             }
1029         }
1030     }
1031     SERVER_END_REQ;
1032     return ret;
1033 }
1034
1035
1036 /******************************************************************************
1037  * read_console_input
1038  *
1039  * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1040  *
1041  * Returns
1042  *      0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1043  */
1044 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1045 static const int vkkeyscan_table[256] =
1046 {
1047      0,0,0,0,0,0,0,0,8,9,0,0,0,13,0,0,0,0,0,19,145,556,0,0,0,0,0,27,0,0,0,
1048      0,32,305,478,307,308,309,311,222,313,304,312,443,188,189,190,191,48,
1049      49,50,51,52,53,54,55,56,57,442,186,444,187,446,447,306,321,322,323,
1050      324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,
1051      341,342,343,344,345,346,219,220,221,310,445,192,65,66,67,68,69,70,71,
1052      72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,475,476,477,
1053      448,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1054      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1055      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1056      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,400,0,0,0,0,0,0
1057 };
1058
1059 static const int mapvkey_0[256] =
1060 {
1061      0,0,0,0,0,0,0,0,14,15,0,0,0,28,0,0,42,29,56,69,58,0,0,0,0,0,0,1,0,0,
1062      0,0,57,73,81,79,71,75,72,77,80,0,0,0,55,82,83,0,11,2,3,4,5,6,7,8,9,
1063      10,0,0,0,0,0,0,0,30,48,46,32,18,33,34,35,23,36,37,38,50,49,24,25,16,
1064      19,31,20,22,47,17,45,21,44,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,55,78,0,74,
1065      0,53,59,60,61,62,63,64,65,66,67,68,87,88,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1066      0,0,0,0,0,0,69,70,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1067      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,39,13,51,12,52,53,41,0,0,0,0,0,0,0,0,0,
1068      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,43,27,40,76,96,0,0,0,0,0,0,0,0,
1069      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
1070 };
1071
1072 static inline void init_complex_char(INPUT_RECORD* ir, BOOL down, WORD vk, WORD kc, DWORD cks)
1073 {
1074     ir->EventType                        = KEY_EVENT;
1075     ir->Event.KeyEvent.bKeyDown          = down;
1076     ir->Event.KeyEvent.wRepeatCount      = 1;
1077     ir->Event.KeyEvent.wVirtualScanCode  = vk;
1078     ir->Event.KeyEvent.wVirtualKeyCode   = kc;
1079     ir->Event.KeyEvent.dwControlKeyState = cks;
1080     ir->Event.KeyEvent.uChar.UnicodeChar = 0;
1081 }
1082
1083 /******************************************************************
1084  *              handle_simple_char
1085  *
1086  *
1087  */
1088 static BOOL handle_simple_char(HANDLE conin, unsigned real_inchar)
1089 {
1090     unsigned            vk;
1091     unsigned            inchar;
1092     char                ch;
1093     unsigned            numEvent = 0;
1094     DWORD               cks = 0, written;
1095     INPUT_RECORD        ir[8];
1096
1097     switch (real_inchar)
1098     {
1099     case   9: inchar = real_inchar;
1100         real_inchar = 27; /* so that we don't think key is ctrl- something */
1101         break;
1102     case  13:
1103     case  10: inchar = '\r';
1104         real_inchar = 27; /* Fixme: so that we don't think key is ctrl- something */
1105         break;
1106     case 127: inchar = '\b';
1107         break;
1108     default:
1109         inchar = real_inchar;
1110         break;
1111     }
1112     if ((inchar & ~0xFF) != 0) FIXME("What a char (%u)\n", inchar);
1113     vk = vkkeyscan_table[inchar];
1114     if (vk & 0x0100)
1115         init_complex_char(&ir[numEvent++], 1, 0x2a, 0x10, SHIFT_PRESSED);
1116     if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1117         init_complex_char(&ir[numEvent++], 1, 0x1d, 0x11, LEFT_CTRL_PRESSED);
1118     if (vk & 0x0400)
1119         init_complex_char(&ir[numEvent++], 1, 0x38, 0x12, LEFT_ALT_PRESSED);
1120
1121     ir[numEvent].EventType                        = KEY_EVENT;
1122     ir[numEvent].Event.KeyEvent.bKeyDown          = 1;
1123     ir[numEvent].Event.KeyEvent.wRepeatCount      = 1;
1124     ir[numEvent].Event.KeyEvent.dwControlKeyState = cks;
1125     if (vk & 0x0100)
1126         ir[numEvent].Event.KeyEvent.dwControlKeyState |= SHIFT_PRESSED;
1127     if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1128         ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_CTRL_PRESSED;
1129     if (vk & 0x0400)
1130         ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_ALT_PRESSED;
1131     ir[numEvent].Event.KeyEvent.wVirtualKeyCode = vk;
1132     ir[numEvent].Event.KeyEvent.wVirtualScanCode = mapvkey_0[vk & 0x00ff]; /* VirtualKeyCodes to ScanCode */
1133
1134     ch = inchar;
1135     MultiByteToWideChar(CP_UNIXCP, 0, &ch, 1, &ir[numEvent].Event.KeyEvent.uChar.UnicodeChar, 1);
1136     ir[numEvent + 1] = ir[numEvent];
1137     ir[numEvent + 1].Event.KeyEvent.bKeyDown = 0;
1138
1139     numEvent += 2;
1140
1141     if (vk & 0x0400)
1142         init_complex_char(&ir[numEvent++], 0, 0x38, 0x12, LEFT_ALT_PRESSED);
1143     if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1144         init_complex_char(&ir[numEvent++], 0, 0x1d, 0x11, 0);
1145     if (vk & 0x0100)
1146         init_complex_char(&ir[numEvent++], 0, 0x2a, 0x10, 0);
1147
1148     return WriteConsoleInputW(conin, ir, numEvent, &written);
1149 }
1150
1151 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1152 {
1153     struct pollfd pollfd;
1154     char          ch;
1155     enum read_console_input_return ret;
1156
1157     pollfd.fd = fd;
1158     pollfd.events = POLLIN;
1159     pollfd.revents = 0;
1160
1161     switch (poll(&pollfd, 1, timeout))
1162     {
1163     case 1:
1164         RtlEnterCriticalSection(&CONSOLE_CritSect);
1165         switch (read(fd, &ch, 1))
1166         {
1167         case 1: ret = handle_simple_char(handle, ch) ? rci_gotone : rci_error; break;
1168         /* actually another thread likely beat us to reading the char
1169          * return gotone, while not perfect, it should work in most of the cases (as the new event
1170          * should be now in the queue)
1171          */
1172         case 0: ret = rci_gotone; break;
1173         default: ret = rci_error; break;
1174         }
1175         RtlLeaveCriticalSection(&CONSOLE_CritSect);
1176         return ret;
1177     case 0: return rci_timeout;
1178     default: return rci_error;
1179     }
1180 }
1181
1182 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1183 {
1184     int fd;
1185     enum read_console_input_return      ret;
1186
1187     if ((fd = get_console_bare_fd(handle)) != -1)
1188     {
1189         put_console_into_raw_mode(fd);
1190         if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1191         {
1192             ret = bare_console_fetch_input(handle, fd, timeout);
1193         }
1194         else ret = rci_gotone;
1195         close(fd);
1196         if (ret != rci_gotone) return ret;
1197     }
1198     else
1199     {
1200         if (!VerifyConsoleIoHandle(handle)) return rci_error;
1201
1202         if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1203             return rci_timeout;
1204     }
1205
1206     SERVER_START_REQ( read_console_input )
1207     {
1208         req->handle = console_handle_unmap(handle);
1209         req->flush = TRUE;
1210         wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1211         if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1212         else ret = rci_gotone;
1213     }
1214     SERVER_END_REQ;
1215
1216     return ret;
1217 }
1218
1219
1220 /***********************************************************************
1221  *            FlushConsoleInputBuffer   (KERNEL32.@)
1222  */
1223 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1224 {
1225     enum read_console_input_return      last;
1226     INPUT_RECORD                        ir;
1227
1228     while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1229
1230     return last == rci_timeout;
1231 }
1232
1233
1234 /***********************************************************************
1235  *            SetConsoleTitleA   (KERNEL32.@)
1236  */
1237 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1238 {
1239     LPWSTR titleW;
1240     BOOL ret;
1241
1242     DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1243     if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1244     MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1245     ret = SetConsoleTitleW(titleW);
1246     HeapFree(GetProcessHeap(), 0, titleW);
1247     return ret;
1248 }
1249
1250
1251 /***********************************************************************
1252  *            GetConsoleKeyboardLayoutNameA   (KERNEL32.@)
1253  */
1254 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1255 {
1256     FIXME( "stub %p\n", layoutName);
1257     return TRUE;
1258 }
1259
1260 /***********************************************************************
1261  *            GetConsoleKeyboardLayoutNameW   (KERNEL32.@)
1262  */
1263 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1264 {
1265     FIXME( "stub %p\n", layoutName);
1266     return TRUE;
1267 }
1268
1269 static WCHAR input_exe[MAX_PATH + 1];
1270
1271 /***********************************************************************
1272  *            GetConsoleInputExeNameW   (KERNEL32.@)
1273  */
1274 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1275 {
1276     TRACE("%u %p\n", buflen, buffer);
1277
1278     RtlEnterCriticalSection(&CONSOLE_CritSect);
1279     if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1280     else SetLastError(ERROR_BUFFER_OVERFLOW);
1281     RtlLeaveCriticalSection(&CONSOLE_CritSect);
1282
1283     return TRUE;
1284 }
1285
1286 /***********************************************************************
1287  *            GetConsoleInputExeNameA   (KERNEL32.@)
1288  */
1289 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1290 {
1291     TRACE("%u %p\n", buflen, buffer);
1292
1293     RtlEnterCriticalSection(&CONSOLE_CritSect);
1294     if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1295         WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1296     else SetLastError(ERROR_BUFFER_OVERFLOW);
1297     RtlLeaveCriticalSection(&CONSOLE_CritSect);
1298
1299     return TRUE;
1300 }
1301
1302 /***********************************************************************
1303  *            GetConsoleTitleA   (KERNEL32.@)
1304  *
1305  * See GetConsoleTitleW.
1306  */
1307 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1308 {
1309     WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1310     DWORD ret;
1311
1312     if (!ptr) return 0;
1313     ret = GetConsoleTitleW( ptr, size );
1314     if (ret)
1315     {
1316         WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1317         ret = strlen(title);
1318     }
1319     HeapFree(GetProcessHeap(), 0, ptr);
1320     return ret;
1321 }
1322
1323
1324 /******************************************************************************
1325  * GetConsoleTitleW [KERNEL32.@]  Retrieves title string for console
1326  *
1327  * PARAMS
1328  *    title [O] Address of buffer for title
1329  *    size  [I] Size of buffer
1330  *
1331  * RETURNS
1332  *    Success: Length of string copied
1333  *    Failure: 0
1334  */
1335 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1336 {
1337     DWORD ret = 0;
1338
1339     SERVER_START_REQ( get_console_input_info )
1340     {
1341         req->handle = 0;
1342         wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1343         if (!wine_server_call_err( req ))
1344         {
1345             ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1346             title[ret] = 0;
1347         }
1348     }
1349     SERVER_END_REQ;
1350     return ret;
1351 }
1352
1353
1354 /***********************************************************************
1355  *            GetLargestConsoleWindowSize   (KERNEL32.@)
1356  *
1357  * NOTE
1358  *      This should return a COORD, but calling convention for returning
1359  *      structures is different between Windows and gcc on i386.
1360  *
1361  * VERSION: [i386]
1362  */
1363 #ifdef __i386__
1364 #undef GetLargestConsoleWindowSize
1365 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1366 {
1367     union {
1368         COORD c;
1369         DWORD w;
1370     } x;
1371     x.c.X = 80;
1372     x.c.Y = 24;
1373     TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1374     return x.w;
1375 }
1376 #endif /* defined(__i386__) */
1377
1378
1379 /***********************************************************************
1380  *            GetLargestConsoleWindowSize   (KERNEL32.@)
1381  *
1382  * NOTE
1383  *      This should return a COORD, but calling convention for returning
1384  *      structures is different between Windows and gcc on i386.
1385  *
1386  * VERSION: [!i386]
1387  */
1388 #ifndef __i386__
1389 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1390 {
1391     COORD c;
1392     c.X = 80;
1393     c.Y = 24;
1394     TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1395     return c;
1396 }
1397 #endif /* defined(__i386__) */
1398
1399 static WCHAR*   S_EditString /* = NULL */;
1400 static unsigned S_EditStrPos /* = 0 */;
1401
1402 /***********************************************************************
1403  *            FreeConsole (KERNEL32.@)
1404  */
1405 BOOL WINAPI FreeConsole(VOID)
1406 {
1407     BOOL ret;
1408
1409     /* invalidate local copy of input event handle */
1410     console_wait_event = 0;
1411
1412     SERVER_START_REQ(free_console)
1413     {
1414         ret = !wine_server_call_err( req );
1415     }
1416     SERVER_END_REQ;
1417     return ret;
1418 }
1419
1420 /******************************************************************
1421  *              start_console_renderer
1422  *
1423  * helper for AllocConsole
1424  * starts the renderer process
1425  */
1426 static  BOOL    start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1427                                               HANDLE hEvent)
1428 {
1429     char                buffer[1024];
1430     int                 ret;
1431     PROCESS_INFORMATION pi;
1432
1433     /* FIXME: use dynamic allocation for most of the buffers below */
1434     ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1435     if ((ret > -1) && (ret < sizeof(buffer)) &&
1436         CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1437                        NULL, NULL, si, &pi))
1438     {
1439         HANDLE  wh[2];
1440         DWORD   ret;
1441
1442         wh[0] = hEvent;
1443         wh[1] = pi.hProcess;
1444         ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1445
1446         CloseHandle(pi.hThread);
1447         CloseHandle(pi.hProcess);
1448
1449         if (ret != WAIT_OBJECT_0) return FALSE;
1450
1451         TRACE("Started wineconsole pid=%08x tid=%08x\n",
1452               pi.dwProcessId, pi.dwThreadId);
1453
1454         return TRUE;
1455     }
1456     return FALSE;
1457 }
1458
1459 static  BOOL    start_console_renderer(STARTUPINFOA* si)
1460 {
1461     HANDLE              hEvent = 0;
1462     LPSTR               p;
1463     OBJECT_ATTRIBUTES   attr;
1464     BOOL                ret = FALSE;
1465
1466     attr.Length                   = sizeof(attr);
1467     attr.RootDirectory            = 0;
1468     attr.Attributes               = OBJ_INHERIT;
1469     attr.ObjectName               = NULL;
1470     attr.SecurityDescriptor       = NULL;
1471     attr.SecurityQualityOfService = NULL;
1472
1473     NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1474     if (!hEvent) return FALSE;
1475
1476     /* first try environment variable */
1477     if ((p = getenv("WINECONSOLE")) != NULL)
1478     {
1479         ret = start_console_renderer_helper(p, si, hEvent);
1480         if (!ret)
1481             ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1482                 "trying default access\n", p);
1483     }
1484
1485     /* then try the regular PATH */
1486     if (!ret)
1487         ret = start_console_renderer_helper("wineconsole", si, hEvent);
1488
1489     CloseHandle(hEvent);
1490     return ret;
1491 }
1492
1493 /***********************************************************************
1494  *            AllocConsole (KERNEL32.@)
1495  *
1496  * creates an xterm with a pty to our program
1497  */
1498 BOOL WINAPI AllocConsole(void)
1499 {
1500     HANDLE              handle_in = INVALID_HANDLE_VALUE;
1501     HANDLE              handle_out = INVALID_HANDLE_VALUE;
1502     HANDLE              handle_err = INVALID_HANDLE_VALUE;
1503     STARTUPINFOA        siCurrent;
1504     STARTUPINFOA        siConsole;
1505     char                buffer[1024];
1506
1507     TRACE("()\n");
1508
1509     handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1510                               FALSE, OPEN_EXISTING );
1511
1512     if (VerifyConsoleIoHandle(handle_in))
1513     {
1514         /* we already have a console opened on this process, don't create a new one */
1515         CloseHandle(handle_in);
1516         return FALSE;
1517     }
1518
1519     /* invalidate local copy of input event handle */
1520     console_wait_event = 0;
1521
1522     GetStartupInfoA(&siCurrent);
1523
1524     memset(&siConsole, 0, sizeof(siConsole));
1525     siConsole.cb = sizeof(siConsole);
1526     /* setup a view arguments for wineconsole (it'll use them as default values)  */
1527     if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1528     {
1529         siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1530         siConsole.dwXCountChars = siCurrent.dwXCountChars;
1531         siConsole.dwYCountChars = siCurrent.dwYCountChars;
1532     }
1533     if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1534     {
1535         siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1536         siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1537     }
1538     if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1539     {
1540         siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1541         siConsole.wShowWindow = siCurrent.wShowWindow;
1542     }
1543     /* FIXME (should pass the unicode form) */
1544     if (siCurrent.lpTitle)
1545         siConsole.lpTitle = siCurrent.lpTitle;
1546     else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1547     {
1548         buffer[sizeof(buffer) - 1] = '\0';
1549         siConsole.lpTitle = buffer;
1550     }
1551
1552     if (!start_console_renderer(&siConsole))
1553         goto the_end;
1554
1555     if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1556         /* all std I/O handles are inheritable by default */
1557         handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1558                                   TRUE, OPEN_EXISTING );
1559         if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1560   
1561         handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1562                                    TRUE, OPEN_EXISTING );
1563         if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1564   
1565         if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1566                     &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1567             goto the_end;
1568     } else {
1569         /*  STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1570         handle_in  =  siCurrent.hStdInput;
1571         handle_out =  siCurrent.hStdOutput;
1572         handle_err =  siCurrent.hStdError;
1573     }
1574
1575     /* NT resets the STD_*_HANDLEs on console alloc */
1576     SetStdHandle(STD_INPUT_HANDLE,  handle_in);
1577     SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1578     SetStdHandle(STD_ERROR_HANDLE,  handle_err);
1579
1580     SetLastError(ERROR_SUCCESS);
1581
1582     return TRUE;
1583
1584  the_end:
1585     ERR("Can't allocate console\n");
1586     if (handle_in != INVALID_HANDLE_VALUE)      CloseHandle(handle_in);
1587     if (handle_out != INVALID_HANDLE_VALUE)     CloseHandle(handle_out);
1588     if (handle_err != INVALID_HANDLE_VALUE)     CloseHandle(handle_err);
1589     FreeConsole();
1590     return FALSE;
1591 }
1592
1593
1594 /***********************************************************************
1595  *            ReadConsoleA   (KERNEL32.@)
1596  */
1597 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1598                          LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1599 {
1600     LPWSTR      ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1601     DWORD       ncr = 0;
1602     BOOL        ret;
1603
1604     if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1605         ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1606
1607     if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1608     HeapFree(GetProcessHeap(), 0, ptr);
1609
1610     return ret;
1611 }
1612
1613 /***********************************************************************
1614  *            ReadConsoleW   (KERNEL32.@)
1615  */
1616 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1617                          DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1618 {
1619     DWORD       charsread;
1620     LPWSTR      xbuf = lpBuffer;
1621     DWORD       mode;
1622     BOOL        is_bare = FALSE;
1623     int         fd;
1624
1625     TRACE("(%p,%p,%d,%p,%p)\n",
1626           hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1627
1628     if (!GetConsoleMode(hConsoleInput, &mode))
1629         return FALSE;
1630     if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1631     {
1632         close(fd);
1633         is_bare = TRUE;
1634     }
1635     if (mode & ENABLE_LINE_INPUT)
1636     {
1637         if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1638         {
1639             HeapFree(GetProcessHeap(), 0, S_EditString);
1640             if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1641                 return FALSE;
1642             S_EditStrPos = 0;
1643         }
1644         charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1645         if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1646         memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1647         S_EditStrPos += charsread;
1648     }
1649     else
1650     {
1651         INPUT_RECORD    ir;
1652         DWORD           timeout = INFINITE;
1653
1654         /* FIXME: should we read at least 1 char? The SDK does not say */
1655         /* wait for at least one available input record (it doesn't mean we'll have
1656          * chars stored in xbuf...)
1657          *
1658          * Although SDK doc keeps silence about 1 char, SDK examples assume
1659          * that we should wait for at least one character (not key). --KS
1660          */
1661         charsread = 0;
1662         do 
1663         {
1664             if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1665             if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1666                 ir.Event.KeyEvent.uChar.UnicodeChar)
1667             {
1668                 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1669                 timeout = 0;
1670             }
1671         } while (charsread < nNumberOfCharsToRead);
1672         /* nothing has been read */
1673         if (timeout == INFINITE) return FALSE;
1674     }
1675
1676     if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1677
1678     return TRUE;
1679 }
1680
1681
1682 /***********************************************************************
1683  *            ReadConsoleInputW   (KERNEL32.@)
1684  */
1685 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1686                               DWORD nLength, LPDWORD lpNumberOfEventsRead)
1687 {
1688     DWORD idx = 0;
1689     DWORD timeout = INFINITE;
1690
1691     if (!nLength)
1692     {
1693         if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1694         return TRUE;
1695     }
1696
1697     /* loop until we get at least one event */
1698     while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1699            ++idx < nLength)
1700         timeout = 0;
1701
1702     if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1703     return idx != 0;
1704 }
1705
1706
1707 /******************************************************************************
1708  * WriteConsoleOutputCharacterW [KERNEL32.@]
1709  * 
1710  * Copy character to consecutive cells in the console screen buffer.
1711  *
1712  * PARAMS
1713  *    hConsoleOutput    [I] Handle to screen buffer
1714  *    str               [I] Pointer to buffer with chars to write
1715  *    length            [I] Number of cells to write to
1716  *    coord             [I] Coords of first cell
1717  *    lpNumCharsWritten [O] Pointer to number of cells written
1718  *
1719  * RETURNS
1720  *    Success: TRUE
1721  *    Failure: FALSE
1722  *
1723  */
1724 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1725                                           COORD coord, LPDWORD lpNumCharsWritten )
1726 {
1727     BOOL ret;
1728
1729     TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1730           debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1731
1732     if ((length > 0 && !str) || !lpNumCharsWritten)
1733     {
1734         SetLastError(ERROR_INVALID_ACCESS);
1735         return FALSE;
1736     }
1737
1738     *lpNumCharsWritten = 0;
1739
1740     SERVER_START_REQ( write_console_output )
1741     {
1742         req->handle = console_handle_unmap(hConsoleOutput);
1743         req->x      = coord.X;
1744         req->y      = coord.Y;
1745         req->mode   = CHAR_INFO_MODE_TEXT;
1746         req->wrap   = TRUE;
1747         wine_server_add_data( req, str, length * sizeof(WCHAR) );
1748         if ((ret = !wine_server_call_err( req )))
1749             *lpNumCharsWritten = reply->written;
1750     }
1751     SERVER_END_REQ;
1752     return ret;
1753 }
1754
1755
1756 /******************************************************************************
1757  * SetConsoleTitleW [KERNEL32.@]  Sets title bar string for console
1758  *
1759  * PARAMS
1760  *    title [I] Address of new title
1761  *
1762  * RETURNS
1763  *    Success: TRUE
1764  *    Failure: FALSE
1765  */
1766 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1767 {
1768     BOOL ret;
1769
1770     TRACE("(%s)\n", debugstr_w(title));
1771     SERVER_START_REQ( set_console_input_info )
1772     {
1773         req->handle = 0;
1774         req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1775         wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1776         ret = !wine_server_call_err( req );
1777     }
1778     SERVER_END_REQ;
1779     return ret;
1780 }
1781
1782
1783 /***********************************************************************
1784  *            GetNumberOfConsoleMouseButtons   (KERNEL32.@)
1785  */
1786 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1787 {
1788     FIXME("(%p): stub\n", nrofbuttons);
1789     *nrofbuttons = 2;
1790     return TRUE;
1791 }
1792
1793 /******************************************************************************
1794  *  SetConsoleInputExeNameW      [KERNEL32.@]
1795  */
1796 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1797 {
1798     TRACE("(%s)\n", debugstr_w(name));
1799
1800     if (!name || !name[0])
1801     {
1802         SetLastError(ERROR_INVALID_PARAMETER);
1803         return FALSE;
1804     }
1805
1806     RtlEnterCriticalSection(&CONSOLE_CritSect);
1807     if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1808     RtlLeaveCriticalSection(&CONSOLE_CritSect);
1809
1810     return TRUE;
1811 }
1812
1813 /******************************************************************************
1814  *  SetConsoleInputExeNameA      [KERNEL32.@]
1815  */
1816 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1817 {
1818     int len;
1819     LPWSTR nameW;
1820     BOOL ret;
1821
1822     if (!name || !name[0])
1823     {
1824         SetLastError(ERROR_INVALID_PARAMETER);
1825         return FALSE;
1826     }
1827
1828     len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1829     if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1830
1831     MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1832     ret = SetConsoleInputExeNameW(nameW);
1833     HeapFree(GetProcessHeap(), 0, nameW);
1834
1835     return ret;
1836 }
1837
1838 /******************************************************************
1839  *              CONSOLE_DefaultHandler
1840  *
1841  * Final control event handler
1842  */
1843 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1844 {
1845     FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1846     ExitProcess(0);
1847     /* should never go here */
1848     return TRUE;
1849 }
1850
1851 /******************************************************************************
1852  * SetConsoleCtrlHandler [KERNEL32.@]  Adds function to calling process list
1853  *
1854  * PARAMS
1855  *    func [I] Address of handler function
1856  *    add  [I] Handler to add or remove
1857  *
1858  * RETURNS
1859  *    Success: TRUE
1860  *    Failure: FALSE
1861  */
1862
1863 struct ConsoleHandler
1864 {
1865     PHANDLER_ROUTINE            handler;
1866     struct ConsoleHandler*      next;
1867 };
1868
1869 static struct ConsoleHandler    CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1870 static struct ConsoleHandler*   CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1871
1872 /*****************************************************************************/
1873
1874 /******************************************************************
1875  *              SetConsoleCtrlHandler (KERNEL32.@)
1876  */
1877 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1878 {
1879     BOOL        ret = TRUE;
1880
1881     TRACE("(%p,%i)\n", func, add);
1882
1883     if (!func)
1884     {
1885         RtlEnterCriticalSection(&CONSOLE_CritSect);
1886         if (add)
1887             NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1888         else
1889             NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1890         RtlLeaveCriticalSection(&CONSOLE_CritSect);
1891     }
1892     else if (add)
1893     {
1894         struct ConsoleHandler*  ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1895
1896         if (!ch) return FALSE;
1897         ch->handler = func;
1898         RtlEnterCriticalSection(&CONSOLE_CritSect);
1899         ch->next = CONSOLE_Handlers;
1900         CONSOLE_Handlers = ch;
1901         RtlLeaveCriticalSection(&CONSOLE_CritSect);
1902     }
1903     else
1904     {
1905         struct ConsoleHandler**  ch;
1906         RtlEnterCriticalSection(&CONSOLE_CritSect);
1907         for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1908         {
1909             if ((*ch)->handler == func) break;
1910         }
1911         if (*ch)
1912         {
1913             struct ConsoleHandler*   rch = *ch;
1914
1915             /* sanity check */
1916             if (rch == &CONSOLE_DefaultConsoleHandler)
1917             {
1918                 ERR("Who's trying to remove default handler???\n");
1919                 SetLastError(ERROR_INVALID_PARAMETER);
1920                 ret = FALSE;
1921             }
1922             else
1923             {
1924                 *ch = rch->next;
1925                 HeapFree(GetProcessHeap(), 0, rch);
1926             }
1927         }
1928         else
1929         {
1930             WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1931             SetLastError(ERROR_INVALID_PARAMETER);
1932             ret = FALSE;
1933         }
1934         RtlLeaveCriticalSection(&CONSOLE_CritSect);
1935     }
1936     return ret;
1937 }
1938
1939 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1940 {
1941     TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1942     return EXCEPTION_EXECUTE_HANDLER;
1943 }
1944
1945 /******************************************************************
1946  *              CONSOLE_SendEventThread
1947  *
1948  * Internal helper to pass an event to the list on installed handlers
1949  */
1950 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1951 {
1952     DWORD_PTR                   event = (DWORD_PTR)pmt;
1953     struct ConsoleHandler*      ch;
1954
1955     if (event == CTRL_C_EVENT)
1956     {
1957         BOOL    caught_by_dbg = TRUE;
1958         /* First, try to pass the ctrl-C event to the debugger (if any)
1959          * If it continues, there's nothing more to do
1960          * Otherwise, we need to send the ctrl-C event to the handlers
1961          */
1962         __TRY
1963         {
1964             RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1965         }
1966         __EXCEPT(CONSOLE_CtrlEventHandler)
1967         {
1968             caught_by_dbg = FALSE;
1969         }
1970         __ENDTRY;
1971         if (caught_by_dbg) return 0;
1972         /* the debugger didn't continue... so, pass to ctrl handlers */
1973     }
1974     RtlEnterCriticalSection(&CONSOLE_CritSect);
1975     for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1976     {
1977         if (ch->handler(event)) break;
1978     }
1979     RtlLeaveCriticalSection(&CONSOLE_CritSect);
1980     return 1;
1981 }
1982
1983 /******************************************************************
1984  *              CONSOLE_HandleCtrlC
1985  *
1986  * Check whether the shall manipulate CtrlC events
1987  */
1988 int     CONSOLE_HandleCtrlC(unsigned sig)
1989 {
1990     /* FIXME: better test whether a console is attached to this process ??? */
1991     extern    unsigned CONSOLE_GetNumHistoryEntries(void);
1992     if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1993
1994     /* check if we have to ignore ctrl-C events */
1995     if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1996     {
1997         /* Create a separate thread to signal all the events. 
1998          * This is needed because:
1999          *  - this function can be called in an Unix signal handler (hence on an
2000          *    different stack than the thread that's running). This breaks the 
2001          *    Win32 exception mechanisms (where the thread's stack is checked).
2002          *  - since the current thread, while processing the signal, can hold the
2003          *    console critical section, we need another execution environment where
2004          *    we can wait on this critical section 
2005          */
2006         CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2007     }
2008     return 1;
2009 }
2010
2011 /******************************************************************************
2012  * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2013  *
2014  * PARAMS
2015  *    dwCtrlEvent        [I] Type of event
2016  *    dwProcessGroupID   [I] Process group ID to send event to
2017  *
2018  * RETURNS
2019  *    Success: True
2020  *    Failure: False (and *should* [but doesn't] set LastError)
2021  */
2022 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2023                                      DWORD dwProcessGroupID)
2024 {
2025     BOOL ret;
2026
2027     TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2028
2029     if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2030     {
2031         ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2032         return FALSE;
2033     }
2034
2035     SERVER_START_REQ( send_console_signal )
2036     {
2037         req->signal = dwCtrlEvent;
2038         req->group_id = dwProcessGroupID;
2039         ret = !wine_server_call_err( req );
2040     }
2041     SERVER_END_REQ;
2042
2043     /* FIXME: Shall this function be synchronous, i.e., only return when all events
2044      * have been handled by all processes in the given group?
2045      * As of today, we don't wait...
2046      */
2047     return ret;
2048 }
2049
2050
2051 /******************************************************************************
2052  * CreateConsoleScreenBuffer [KERNEL32.@]  Creates a console screen buffer
2053  *
2054  * PARAMS
2055  *    dwDesiredAccess    [I] Access flag
2056  *    dwShareMode        [I] Buffer share mode
2057  *    sa                 [I] Security attributes
2058  *    dwFlags            [I] Type of buffer to create
2059  *    lpScreenBufferData [I] Reserved
2060  *
2061  * NOTES
2062  *    Should call SetLastError
2063  *
2064  * RETURNS
2065  *    Success: Handle to new console screen buffer
2066  *    Failure: INVALID_HANDLE_VALUE
2067  */
2068 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2069                                         LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2070                                         LPVOID lpScreenBufferData)
2071 {
2072     HANDLE      ret = INVALID_HANDLE_VALUE;
2073
2074     TRACE("(%d,%d,%p,%d,%p)\n",
2075           dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2076
2077     if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2078     {
2079         SetLastError(ERROR_INVALID_PARAMETER);
2080         return INVALID_HANDLE_VALUE;
2081     }
2082
2083     SERVER_START_REQ(create_console_output)
2084     {
2085         req->handle_in  = 0;
2086         req->access     = dwDesiredAccess;
2087         req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2088         req->share      = dwShareMode;
2089         req->fd         = -1;
2090         if (!wine_server_call_err( req ))
2091             ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2092     }
2093     SERVER_END_REQ;
2094
2095     return ret;
2096 }
2097
2098
2099 /***********************************************************************
2100  *           GetConsoleScreenBufferInfo   (KERNEL32.@)
2101  */
2102 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2103 {
2104     BOOL        ret;
2105
2106     SERVER_START_REQ(get_console_output_info)
2107     {
2108         req->handle = console_handle_unmap(hConsoleOutput);
2109         if ((ret = !wine_server_call_err( req )))
2110         {
2111             csbi->dwSize.X              = reply->width;
2112             csbi->dwSize.Y              = reply->height;
2113             csbi->dwCursorPosition.X    = reply->cursor_x;
2114             csbi->dwCursorPosition.Y    = reply->cursor_y;
2115             csbi->wAttributes           = reply->attr;
2116             csbi->srWindow.Left         = reply->win_left;
2117             csbi->srWindow.Right        = reply->win_right;
2118             csbi->srWindow.Top          = reply->win_top;
2119             csbi->srWindow.Bottom       = reply->win_bottom;
2120             csbi->dwMaximumWindowSize.X = reply->max_width;
2121             csbi->dwMaximumWindowSize.Y = reply->max_height;
2122         }
2123     }
2124     SERVER_END_REQ;
2125
2126     TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n", 
2127           hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2128           csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2129           csbi->wAttributes,
2130           csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2131           csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2132
2133     return ret;
2134 }
2135
2136
2137 /******************************************************************************
2138  * SetConsoleActiveScreenBuffer [KERNEL32.@]  Sets buffer to current console
2139  *
2140  * RETURNS
2141  *    Success: TRUE
2142  *    Failure: FALSE
2143  */
2144 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2145 {
2146     BOOL ret;
2147
2148     TRACE("(%p)\n", hConsoleOutput);
2149
2150     SERVER_START_REQ( set_console_input_info )
2151     {
2152         req->handle    = 0;
2153         req->mask      = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2154         req->active_sb = wine_server_obj_handle( hConsoleOutput );
2155         ret = !wine_server_call_err( req );
2156     }
2157     SERVER_END_REQ;
2158     return ret;
2159 }
2160
2161
2162 /***********************************************************************
2163  *            GetConsoleMode   (KERNEL32.@)
2164  */
2165 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2166 {
2167     BOOL ret;
2168
2169     SERVER_START_REQ( get_console_mode )
2170     {
2171         req->handle = console_handle_unmap(hcon);
2172         if ((ret = !wine_server_call_err( req )))
2173         {
2174             if (mode) *mode = reply->mode;
2175         }
2176     }
2177     SERVER_END_REQ;
2178     return ret;
2179 }
2180
2181
2182 /******************************************************************************
2183  * SetConsoleMode [KERNEL32.@]  Sets input mode of console's input buffer
2184  *
2185  * PARAMS
2186  *    hcon [I] Handle to console input or screen buffer
2187  *    mode [I] Input or output mode to set
2188  *
2189  * RETURNS
2190  *    Success: TRUE
2191  *    Failure: FALSE
2192  *
2193  *    mode:
2194  *      ENABLE_PROCESSED_INPUT  0x01
2195  *      ENABLE_LINE_INPUT       0x02
2196  *      ENABLE_ECHO_INPUT       0x04
2197  *      ENABLE_WINDOW_INPUT     0x08
2198  *      ENABLE_MOUSE_INPUT      0x10
2199  */
2200 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2201 {
2202     BOOL ret;
2203
2204     SERVER_START_REQ(set_console_mode)
2205     {
2206         req->handle = console_handle_unmap(hcon);
2207         req->mode = mode;
2208         ret = !wine_server_call_err( req );
2209     }
2210     SERVER_END_REQ;
2211     /* FIXME: when resetting a console input to editline mode, I think we should
2212      * empty the S_EditString buffer
2213      */
2214
2215     TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2216
2217     return ret;
2218 }
2219
2220
2221 /******************************************************************
2222  *              CONSOLE_WriteChars
2223  *
2224  * WriteConsoleOutput helper: hides server call semantics
2225  * writes a string at a given pos with standard attribute
2226  */
2227 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2228 {
2229     int written = -1;
2230
2231     if (!nc) return 0;
2232
2233     SERVER_START_REQ( write_console_output )
2234     {
2235         req->handle = console_handle_unmap(hCon);
2236         req->x      = pos->X;
2237         req->y      = pos->Y;
2238         req->mode   = CHAR_INFO_MODE_TEXTSTDATTR;
2239         req->wrap   = FALSE;
2240         wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2241         if (!wine_server_call_err( req )) written = reply->written;
2242     }
2243     SERVER_END_REQ;
2244
2245     if (written > 0) pos->X += written;
2246     return written;
2247 }
2248
2249 /******************************************************************
2250  *              next_line
2251  *
2252  * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2253  *
2254  */
2255 static int      next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2256 {
2257     SMALL_RECT  src;
2258     CHAR_INFO   ci;
2259     COORD       dst;
2260
2261     csbi->dwCursorPosition.X = 0;
2262     csbi->dwCursorPosition.Y++;
2263
2264     if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2265
2266     src.Top    = 1;
2267     src.Bottom = csbi->dwSize.Y - 1;
2268     src.Left   = 0;
2269     src.Right  = csbi->dwSize.X - 1;
2270
2271     dst.X      = 0;
2272     dst.Y      = 0;
2273
2274     ci.Attributes = csbi->wAttributes;
2275     ci.Char.UnicodeChar = ' ';
2276
2277     csbi->dwCursorPosition.Y--;
2278     if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2279         return 0;
2280     return 1;
2281 }
2282
2283 /******************************************************************
2284  *              write_block
2285  *
2286  * WriteConsoleOutput helper: writes a block of non special characters
2287  * Block can spread on several lines, and wrapping, if needed, is
2288  * handled
2289  *
2290  */
2291 static int      write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2292                             DWORD mode, LPCWSTR ptr, int len)
2293 {
2294     int blk;    /* number of chars to write on current line */
2295     int done;   /* number of chars already written */
2296
2297     if (len <= 0) return 1;
2298
2299     if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2300     {
2301         for (done = 0; done < len; done += blk)
2302         {
2303             blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2304
2305             if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2306                 return 0;
2307             if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2308                 return 0;
2309         }
2310     }
2311     else
2312     {
2313         int     pos = csbi->dwCursorPosition.X;
2314         /* FIXME: we could reduce the number of loops
2315          * but, in most cases we wouldn't gain lots of time (it would only
2316          * happen if we're asked to overwrite more than twice the part of the line,
2317          * which is unlikely
2318          */
2319         for (done = 0; done < len; done += blk)
2320         {
2321             blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2322
2323             csbi->dwCursorPosition.X = pos;
2324             if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2325                 return 0;
2326         }
2327     }
2328
2329     return 1;
2330 }
2331
2332 /***********************************************************************
2333  *            WriteConsoleW   (KERNEL32.@)
2334  */
2335 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2336                           LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2337 {
2338     DWORD                       mode;
2339     DWORD                       nw = 0;
2340     const WCHAR*                psz = lpBuffer;
2341     CONSOLE_SCREEN_BUFFER_INFO  csbi;
2342     int                         k, first = 0, fd;
2343
2344     TRACE("%p %s %d %p %p\n",
2345           hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2346           nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2347
2348     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2349
2350     if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2351     {
2352         char*           ptr;
2353         unsigned        len;
2354         BOOL            ret;
2355
2356         close(fd);
2357         /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2358          * to do the job
2359          */
2360         len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2361         if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2362             return FALSE;
2363
2364         WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2365         ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2366                         ptr, len, lpNumberOfCharsWritten, NULL);
2367         if (ret && lpNumberOfCharsWritten)
2368         {
2369             if (*lpNumberOfCharsWritten == len)
2370                 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2371             else
2372                 FIXME("Conversion not supported yet\n");
2373         }
2374         HeapFree(GetProcessHeap(), 0, ptr);
2375         return ret;
2376     }
2377
2378     if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2379         return FALSE;
2380
2381     if (!nNumberOfCharsToWrite) return TRUE;
2382
2383     if (mode & ENABLE_PROCESSED_OUTPUT)
2384     {
2385         unsigned int    i;
2386
2387         for (i = 0; i < nNumberOfCharsToWrite; i++)
2388         {
2389             switch (psz[i])
2390             {
2391             case '\b': case '\t': case '\n': case '\a': case '\r':
2392                 /* don't handle here the i-th char... done below */
2393                 if ((k = i - first) > 0)
2394                 {
2395                     if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2396                         goto the_end;
2397                     nw += k;
2398                 }
2399                 first = i + 1;
2400                 nw++;
2401             }
2402             switch (psz[i])
2403             {
2404             case '\b':
2405                 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2406                 break;
2407             case '\t':
2408                 {
2409                     WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2410
2411                     if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2412                                      ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2413                         goto the_end;
2414                 }
2415                 break;
2416             case '\n':
2417                 next_line(hConsoleOutput, &csbi);
2418                 break;
2419             case '\a':
2420                 Beep(400, 300);
2421                 break;
2422             case '\r':
2423                 csbi.dwCursorPosition.X = 0;
2424                 break;
2425             default:
2426                 break;
2427             }
2428         }
2429     }
2430
2431     /* write the remaining block (if any) if processed output is enabled, or the
2432      * entire buffer otherwise
2433      */
2434     if ((k = nNumberOfCharsToWrite - first) > 0)
2435     {
2436         if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2437             goto the_end;
2438         nw += k;
2439     }
2440
2441  the_end:
2442     SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2443     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2444     return nw != 0;
2445 }
2446
2447
2448 /***********************************************************************
2449  *            WriteConsoleA   (KERNEL32.@)
2450  */
2451 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2452                           LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2453 {
2454     BOOL        ret;
2455     LPWSTR      xstring;
2456     DWORD       n;
2457
2458     n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2459
2460     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2461     xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2462     if (!xstring) return 0;
2463
2464     MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2465
2466     ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2467
2468     HeapFree(GetProcessHeap(), 0, xstring);
2469
2470     return ret;
2471 }
2472
2473 /******************************************************************************
2474  * SetConsoleCursorPosition [KERNEL32.@]
2475  * Sets the cursor position in console
2476  *
2477  * PARAMS
2478  *    hConsoleOutput   [I] Handle of console screen buffer
2479  *    dwCursorPosition [I] New cursor position coordinates
2480  *
2481  * RETURNS
2482  *    Success: TRUE
2483  *    Failure: FALSE
2484  */
2485 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2486 {
2487     BOOL                        ret;
2488     CONSOLE_SCREEN_BUFFER_INFO  csbi;
2489     int                         do_move = 0;
2490     int                         w, h;
2491
2492     TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2493
2494     SERVER_START_REQ(set_console_output_info)
2495     {
2496         req->handle         = console_handle_unmap(hcon);
2497         req->cursor_x       = pos.X;
2498         req->cursor_y       = pos.Y;
2499         req->mask           = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2500         ret = !wine_server_call_err( req );
2501     }
2502     SERVER_END_REQ;
2503
2504     if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2505         return FALSE;
2506
2507     /* if cursor is no longer visible, scroll the visible window... */
2508     w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2509     h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2510     if (pos.X < csbi.srWindow.Left)
2511     {
2512         csbi.srWindow.Left   = min(pos.X, csbi.dwSize.X - w);
2513         do_move++;
2514     }
2515     else if (pos.X > csbi.srWindow.Right)
2516     {
2517         csbi.srWindow.Left   = max(pos.X, w) - w + 1;
2518         do_move++;
2519     }
2520     csbi.srWindow.Right  = csbi.srWindow.Left + w - 1;
2521
2522     if (pos.Y < csbi.srWindow.Top)
2523     {
2524         csbi.srWindow.Top    = min(pos.Y, csbi.dwSize.Y - h);
2525         do_move++;
2526     }
2527     else if (pos.Y > csbi.srWindow.Bottom)
2528     {
2529         csbi.srWindow.Top   = max(pos.Y, h) - h + 1;
2530         do_move++;
2531     }
2532     csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2533
2534     ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2535
2536     return ret;
2537 }
2538
2539 /******************************************************************************
2540  * GetConsoleCursorInfo [KERNEL32.@]  Gets size and visibility of console
2541  *
2542  * PARAMS
2543  *    hcon  [I] Handle to console screen buffer
2544  *    cinfo [O] Address of cursor information
2545  *
2546  * RETURNS
2547  *    Success: TRUE
2548  *    Failure: FALSE
2549  */
2550 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2551 {
2552     BOOL ret;
2553
2554     SERVER_START_REQ(get_console_output_info)
2555     {
2556         req->handle = console_handle_unmap(hCon);
2557         ret = !wine_server_call_err( req );
2558         if (ret && cinfo)
2559         {
2560             cinfo->dwSize = reply->cursor_size;
2561             cinfo->bVisible = reply->cursor_visible;
2562         }
2563     }
2564     SERVER_END_REQ;
2565
2566     if (!ret) return FALSE;
2567
2568     if (!cinfo)
2569     {
2570         SetLastError(ERROR_INVALID_ACCESS);
2571         ret = FALSE;
2572     }
2573     else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2574
2575     return ret;
2576 }
2577
2578
2579 /******************************************************************************
2580  * SetConsoleCursorInfo [KERNEL32.@]  Sets size and visibility of cursor
2581  *
2582  * PARAMS
2583  *      hcon    [I] Handle to console screen buffer
2584  *      cinfo   [I] Address of cursor information
2585  * RETURNS
2586  *    Success: TRUE
2587  *    Failure: FALSE
2588  */
2589 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2590 {
2591     BOOL ret;
2592
2593     TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2594     SERVER_START_REQ(set_console_output_info)
2595     {
2596         req->handle         = console_handle_unmap(hCon);
2597         req->cursor_size    = cinfo->dwSize;
2598         req->cursor_visible = cinfo->bVisible;
2599         req->mask           = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2600         ret = !wine_server_call_err( req );
2601     }
2602     SERVER_END_REQ;
2603     return ret;
2604 }
2605
2606
2607 /******************************************************************************
2608  * SetConsoleWindowInfo [KERNEL32.@]  Sets size and position of console
2609  *
2610  * PARAMS
2611  *      hcon            [I] Handle to console screen buffer
2612  *      bAbsolute       [I] Coordinate type flag
2613  *      window          [I] Address of new window rectangle
2614  * RETURNS
2615  *    Success: TRUE
2616  *    Failure: FALSE
2617  */
2618 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2619 {
2620     SMALL_RECT  p = *window;
2621     BOOL        ret;
2622
2623     TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2624
2625     if (!bAbsolute)
2626     {
2627         CONSOLE_SCREEN_BUFFER_INFO      csbi;
2628
2629         if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2630             return FALSE;
2631         p.Left   += csbi.srWindow.Left;
2632         p.Top    += csbi.srWindow.Top;
2633         p.Right  += csbi.srWindow.Right;
2634         p.Bottom += csbi.srWindow.Bottom;
2635     }
2636     SERVER_START_REQ(set_console_output_info)
2637     {
2638         req->handle         = console_handle_unmap(hCon);
2639         req->win_left       = p.Left;
2640         req->win_top        = p.Top;
2641         req->win_right      = p.Right;
2642         req->win_bottom     = p.Bottom;
2643         req->mask           = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2644         ret = !wine_server_call_err( req );
2645     }
2646     SERVER_END_REQ;
2647
2648     return ret;
2649 }
2650
2651
2652 /******************************************************************************
2653  * SetConsoleTextAttribute [KERNEL32.@]  Sets colors for text
2654  *
2655  * Sets the foreground and background color attributes of characters
2656  * written to the screen buffer.
2657  *
2658  * RETURNS
2659  *    Success: TRUE
2660  *    Failure: FALSE
2661  */
2662 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2663 {
2664     BOOL ret;
2665
2666     TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2667     SERVER_START_REQ(set_console_output_info)
2668     {
2669         req->handle = console_handle_unmap(hConsoleOutput);
2670         req->attr   = wAttr;
2671         req->mask   = SET_CONSOLE_OUTPUT_INFO_ATTR;
2672         ret = !wine_server_call_err( req );
2673     }
2674     SERVER_END_REQ;
2675     return ret;
2676 }
2677
2678
2679 /******************************************************************************
2680  * SetConsoleScreenBufferSize [KERNEL32.@]  Changes size of console
2681  *
2682  * PARAMS
2683  *    hConsoleOutput [I] Handle to console screen buffer
2684  *    dwSize         [I] New size in character rows and cols
2685  *
2686  * RETURNS
2687  *    Success: TRUE
2688  *    Failure: FALSE
2689  */
2690 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2691 {
2692     BOOL ret;
2693
2694     TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2695     SERVER_START_REQ(set_console_output_info)
2696     {
2697         req->handle = console_handle_unmap(hConsoleOutput);
2698         req->width  = dwSize.X;
2699         req->height = dwSize.Y;
2700         req->mask   = SET_CONSOLE_OUTPUT_INFO_SIZE;
2701         ret = !wine_server_call_err( req );
2702     }
2703     SERVER_END_REQ;
2704     return ret;
2705 }
2706
2707
2708 /******************************************************************************
2709  * ScrollConsoleScreenBufferA [KERNEL32.@]
2710  *
2711  */
2712 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2713                                        LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2714                                        LPCHAR_INFO lpFill)
2715 {
2716     CHAR_INFO   ciw;
2717
2718     ciw.Attributes = lpFill->Attributes;
2719     MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2720
2721     return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2722                                       dwDestOrigin, &ciw);
2723 }
2724
2725 /******************************************************************
2726  *              CONSOLE_FillLineUniform
2727  *
2728  * Helper function for ScrollConsoleScreenBufferW
2729  * Fills a part of a line with a constant character info
2730  */
2731 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2732 {
2733     SERVER_START_REQ( fill_console_output )
2734     {
2735         req->handle    = console_handle_unmap(hConsoleOutput);
2736         req->mode      = CHAR_INFO_MODE_TEXTATTR;
2737         req->x         = i;
2738         req->y         = j;
2739         req->count     = len;
2740         req->wrap      = FALSE;
2741         req->data.ch   = lpFill->Char.UnicodeChar;
2742         req->data.attr = lpFill->Attributes;
2743         wine_server_call_err( req );
2744     }
2745     SERVER_END_REQ;
2746 }
2747
2748 /******************************************************************************
2749  * ScrollConsoleScreenBufferW [KERNEL32.@]
2750  *
2751  */
2752
2753 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2754                                        LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2755                                        LPCHAR_INFO lpFill)
2756 {
2757     SMALL_RECT                  dst;
2758     DWORD                       ret;
2759     int                         i, j;
2760     int                         start = -1;
2761     SMALL_RECT                  clip;
2762     CONSOLE_SCREEN_BUFFER_INFO  csbi;
2763     BOOL                        inside;
2764     COORD                       src;
2765
2766     if (lpClipRect)
2767         TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2768               lpScrollRect->Left, lpScrollRect->Top,
2769               lpScrollRect->Right, lpScrollRect->Bottom,
2770               lpClipRect->Left, lpClipRect->Top,
2771               lpClipRect->Right, lpClipRect->Bottom,
2772               dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2773     else
2774         TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2775               lpScrollRect->Left, lpScrollRect->Top,
2776               lpScrollRect->Right, lpScrollRect->Bottom,
2777               dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2778
2779     if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2780         return FALSE;
2781
2782     src.X = lpScrollRect->Left;
2783     src.Y = lpScrollRect->Top;
2784
2785     /* step 1: get dst rect */
2786     dst.Left = dwDestOrigin.X;
2787     dst.Top = dwDestOrigin.Y;
2788     dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2789     dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2790
2791     /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2792     if (lpClipRect)
2793     {
2794         clip.Left   = max(0, lpClipRect->Left);
2795         clip.Right  = min(csbi.dwSize.X - 1, lpClipRect->Right);
2796         clip.Top    = max(0, lpClipRect->Top);
2797         clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2798     }
2799     else
2800     {
2801         clip.Left   = 0;
2802         clip.Right  = csbi.dwSize.X - 1;
2803         clip.Top    = 0;
2804         clip.Bottom = csbi.dwSize.Y - 1;
2805     }
2806     if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2807
2808     /* step 2b: clip dst rect */
2809     if (dst.Left   < clip.Left  ) {src.X += clip.Left - dst.Left; dst.Left   = clip.Left;}
2810     if (dst.Top    < clip.Top   ) {src.Y += clip.Top  - dst.Top;  dst.Top    = clip.Top;}
2811     if (dst.Right  > clip.Right ) dst.Right  = clip.Right;
2812     if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2813
2814     /* step 3: transfer the bits */
2815     SERVER_START_REQ(move_console_output)
2816     {
2817         req->handle = console_handle_unmap(hConsoleOutput);
2818         req->x_src = src.X;
2819         req->y_src = src.Y;
2820         req->x_dst = dst.Left;
2821         req->y_dst = dst.Top;
2822         req->w = dst.Right - dst.Left + 1;
2823         req->h = dst.Bottom - dst.Top + 1;
2824         ret = !wine_server_call_err( req );
2825     }
2826     SERVER_END_REQ;
2827
2828     if (!ret) return FALSE;
2829
2830     /* step 4: clean out the exposed part */
2831
2832     /* have to write cell [i,j] if it is not in dst rect (because it has already
2833      * been written to by the scroll) and is in clip (we shall not write
2834      * outside of clip)
2835      */
2836     for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2837     {
2838         inside = dst.Top <= j && j <= dst.Bottom;
2839         start = -1;
2840         for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2841         {
2842             if (inside && dst.Left <= i && i <= dst.Right)
2843             {
2844                 if (start != -1)
2845                 {
2846                     CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2847                     start = -1;
2848                 }
2849             }
2850             else
2851             {
2852                 if (start == -1) start = i;
2853             }
2854         }
2855         if (start != -1)
2856             CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2857     }
2858
2859     return TRUE;
2860 }
2861
2862 /******************************************************************
2863  *              AttachConsole  (KERNEL32.@)
2864  */
2865 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2866 {
2867     FIXME("stub %x\n",dwProcessId);
2868     return TRUE;
2869 }
2870
2871 /******************************************************************
2872  *              GetConsoleDisplayMode  (KERNEL32.@)
2873  */
2874 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2875 {
2876     TRACE("semi-stub: %p\n", lpModeFlags);
2877     /* It is safe to successfully report windowed mode */
2878     *lpModeFlags = 0;
2879     return TRUE;
2880 }
2881
2882 /******************************************************************
2883  *              SetConsoleDisplayMode  (KERNEL32.@)
2884  */
2885 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2886                                   COORD *lpNewScreenBufferDimensions)
2887 {
2888     TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2889           lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2890     if (dwFlags == 1)
2891     {
2892         /* We cannot switch to fullscreen */
2893         return FALSE;
2894     }
2895     return TRUE;
2896 }
2897
2898
2899 /* ====================================================================
2900  *
2901  * Console manipulation functions
2902  *
2903  * ====================================================================*/
2904
2905 /* some missing functions...
2906  * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2907  * should get the right API and implement them
2908  *      GetConsoleCommandHistory[AW] (dword dword dword)
2909  *      GetConsoleCommandHistoryLength[AW]
2910  *      SetConsoleCommandHistoryMode
2911  *      SetConsoleNumberOfCommands[AW]
2912  */
2913 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2914 {
2915     int len = 0;
2916
2917     SERVER_START_REQ( get_console_input_history )
2918     {
2919         req->handle = 0;
2920         req->index = idx;
2921         if (buf && buf_len > 1)
2922         {
2923             wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2924         }
2925         if (!wine_server_call_err( req ))
2926         {
2927             if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2928             len = reply->total / sizeof(WCHAR) + 1;
2929         }
2930     }
2931     SERVER_END_REQ;
2932     return len;
2933 }
2934
2935 /******************************************************************
2936  *              CONSOLE_AppendHistory
2937  *
2938  *
2939  */
2940 BOOL    CONSOLE_AppendHistory(const WCHAR* ptr)
2941 {
2942     size_t      len = strlenW(ptr);
2943     BOOL        ret;
2944
2945     while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2946     if (!len) return FALSE;
2947
2948     SERVER_START_REQ( append_console_input_history )
2949     {
2950         req->handle = 0;
2951         wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2952         ret = !wine_server_call_err( req );
2953     }
2954     SERVER_END_REQ;
2955     return ret;
2956 }
2957
2958 /******************************************************************
2959  *              CONSOLE_GetNumHistoryEntries
2960  *
2961  *
2962  */
2963 unsigned CONSOLE_GetNumHistoryEntries(void)
2964 {
2965     unsigned ret = -1;
2966     SERVER_START_REQ(get_console_input_info)
2967     {
2968         req->handle = 0;
2969         if (!wine_server_call_err( req )) ret = reply->history_index;
2970     }
2971     SERVER_END_REQ;
2972     return ret;
2973 }
2974
2975 /******************************************************************
2976  *              CONSOLE_GetEditionMode
2977  *
2978  *
2979  */
2980 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2981 {
2982     unsigned ret = FALSE;
2983     SERVER_START_REQ(get_console_input_info)
2984     {
2985         req->handle = console_handle_unmap(hConIn);
2986         if ((ret = !wine_server_call_err( req )))
2987             *mode = reply->edition_mode;
2988     }
2989     SERVER_END_REQ;
2990     return ret;
2991 }
2992
2993 /******************************************************************
2994  *              GetConsoleAliasW
2995  *
2996  *
2997  * RETURNS
2998  *    0 if an error occurred, non-zero for success
2999  *
3000  */
3001 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3002                               DWORD TargetBufferLength, LPWSTR lpExename)
3003 {
3004     FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3005     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3006     return 0;
3007 }
3008
3009 /******************************************************************
3010  *              GetConsoleProcessList  (KERNEL32.@)
3011  */
3012 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3013 {
3014     FIXME("(%p,%d): stub\n", processlist, processcount);
3015
3016     if (!processlist || processcount < 1)
3017     {
3018         SetLastError(ERROR_INVALID_PARAMETER);
3019         return 0;
3020     }
3021
3022     return 0;
3023 }
3024
3025 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3026 {
3027     memset(&S_termios, 0, sizeof(S_termios));
3028     if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3029     {
3030         HANDLE  conin;
3031
3032         /* FIXME: to be done even if program is a GUI ? */
3033         /* This is wine specific: we have no parent (we're started from unix)
3034          * so, create a simple console with bare handles
3035          */
3036         wine_server_send_fd(0);
3037         SERVER_START_REQ( alloc_console )
3038         {
3039             req->access     = GENERIC_READ | GENERIC_WRITE;
3040             req->attributes = OBJ_INHERIT;
3041             req->pid        = 0xffffffff;
3042             req->input_fd   = 0;
3043             wine_server_call( req );
3044             conin = wine_server_ptr_handle( reply->handle_in );
3045             /* reply->event shouldn't be created by server */
3046         }
3047         SERVER_END_REQ;
3048
3049         if (!params->hStdInput)
3050             params->hStdInput = conin;
3051
3052         if (!params->hStdOutput)
3053         {
3054             wine_server_send_fd(1);
3055             SERVER_START_REQ( create_console_output )
3056             {
3057                 req->handle_in  = wine_server_obj_handle(conin);
3058                 req->access     = GENERIC_WRITE|GENERIC_READ;
3059                 req->attributes = OBJ_INHERIT;
3060                 req->share      = FILE_SHARE_READ|FILE_SHARE_WRITE;
3061                 req->fd         = 1;
3062                 wine_server_call(req);
3063                 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3064             }
3065             SERVER_END_REQ;
3066         }
3067         if (!params->hStdError)
3068         {
3069             wine_server_send_fd(2);
3070             SERVER_START_REQ( create_console_output )
3071             {
3072                 req->handle_in  = wine_server_obj_handle(conin);
3073                 req->access     = GENERIC_WRITE|GENERIC_READ;
3074                 req->attributes = OBJ_INHERIT;
3075                 req->share      = FILE_SHARE_READ|FILE_SHARE_WRITE;
3076                 req->fd         = 2;
3077                 wine_server_call(req);
3078                 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3079             }
3080             SERVER_END_REQ;
3081         }
3082     }
3083
3084     /* convert value from server:
3085      * + 0 => INVALID_HANDLE_VALUE
3086      * + console handle needs to be mapped
3087      */
3088     if (!params->hStdInput)
3089         params->hStdInput = INVALID_HANDLE_VALUE;
3090     else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3091     {
3092         params->hStdInput = console_handle_map(params->hStdInput);
3093         save_console_mode(params->hStdInput);
3094     }
3095
3096     if (!params->hStdOutput)
3097         params->hStdOutput = INVALID_HANDLE_VALUE;
3098     else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3099         params->hStdOutput = console_handle_map(params->hStdOutput);
3100
3101     if (!params->hStdError)
3102         params->hStdError = INVALID_HANDLE_VALUE;
3103     else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3104         params->hStdError = console_handle_map(params->hStdError);
3105
3106     return TRUE;
3107 }
3108
3109 BOOL CONSOLE_Exit(void)
3110 {
3111     /* the console is in raw mode, put it back in cooked mode */
3112     return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));
3113 }