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