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