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