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