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