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