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