wined3d: Move the GL info structure into the adapter.
[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 /* map input records to ASCII */
71 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
72 {
73     int i;
74     char ch;
75
76     for (i = 0; i < count; i++)
77     {
78         if (buffer[i].EventType != KEY_EVENT) continue;
79         WideCharToMultiByte( GetConsoleCP(), 0,
80                              &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
81         buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
82     }
83 }
84
85 /* map input records to Unicode */
86 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
87 {
88     int i;
89     WCHAR ch;
90
91     for (i = 0; i < count; i++)
92     {
93         if (buffer[i].EventType != KEY_EVENT) continue;
94         MultiByteToWideChar( GetConsoleCP(), 0,
95                              &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
96         buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
97     }
98 }
99
100 /* map char infos to ASCII */
101 static void char_info_WtoA( CHAR_INFO *buffer, int count )
102 {
103     char ch;
104
105     while (count-- > 0)
106     {
107         WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
108                              &ch, 1, NULL, NULL );
109         buffer->Char.AsciiChar = ch;
110         buffer++;
111     }
112 }
113
114 /* map char infos to Unicode */
115 static void char_info_AtoW( CHAR_INFO *buffer, int count )
116 {
117     WCHAR ch;
118
119     while (count-- > 0)
120     {
121         MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
122         buffer->Char.UnicodeChar = ch;
123         buffer++;
124     }
125 }
126
127
128 /******************************************************************************
129  * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
130  *
131  * RETURNS
132  *   Success: hwnd of the console window.
133  *   Failure: NULL
134  */
135 HWND WINAPI GetConsoleWindow(VOID)
136 {
137     HWND hWnd = NULL;
138
139     SERVER_START_REQ(get_console_input_info)
140     {
141         req->handle = 0;
142         if (!wine_server_call_err(req)) hWnd = reply->win;
143     }
144     SERVER_END_REQ;
145
146     return hWnd;
147 }
148
149
150 /******************************************************************************
151  * GetConsoleCP [KERNEL32.@]  Returns the OEM code page for the console
152  *
153  * RETURNS
154  *    Code page code
155  */
156 UINT WINAPI GetConsoleCP(VOID)
157 {
158     BOOL ret;
159     UINT codepage = GetOEMCP(); /* default value */
160
161     SERVER_START_REQ(get_console_input_info)
162     {
163         req->handle = 0;
164         ret = !wine_server_call_err(req);
165         if (ret && reply->input_cp)
166             codepage = reply->input_cp;
167     }
168     SERVER_END_REQ;
169
170     return codepage;
171 }
172
173
174 /******************************************************************************
175  *  SetConsoleCP         [KERNEL32.@]
176  */
177 BOOL WINAPI SetConsoleCP(UINT cp)
178 {
179     BOOL ret;
180
181     if (!IsValidCodePage(cp))
182     {
183         SetLastError(ERROR_INVALID_PARAMETER);
184         return FALSE;
185     }
186
187     SERVER_START_REQ(set_console_input_info)
188     {
189         req->handle   = 0;
190         req->mask     = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
191         req->input_cp = cp;
192         ret = !wine_server_call_err(req);
193     }
194     SERVER_END_REQ;
195
196     return ret;
197 }
198
199
200 /***********************************************************************
201  *            GetConsoleOutputCP   (KERNEL32.@)
202  */
203 UINT WINAPI GetConsoleOutputCP(VOID)
204 {
205     BOOL ret;
206     UINT codepage = GetOEMCP(); /* default value */
207
208     SERVER_START_REQ(get_console_input_info)
209     {
210         req->handle = 0;
211         ret = !wine_server_call_err(req);
212         if (ret && reply->output_cp)
213             codepage = reply->output_cp;
214     }
215     SERVER_END_REQ;
216
217     return codepage;
218 }
219
220
221 /******************************************************************************
222  * SetConsoleOutputCP [KERNEL32.@]  Set the output codepage used by the console
223  *
224  * PARAMS
225  *    cp [I] code page to set
226  *
227  * RETURNS
228  *    Success: TRUE
229  *    Failure: FALSE
230  */
231 BOOL WINAPI SetConsoleOutputCP(UINT cp)
232 {
233     BOOL ret;
234
235     if (!IsValidCodePage(cp))
236     {
237         SetLastError(ERROR_INVALID_PARAMETER);
238         return FALSE;
239     }
240
241     SERVER_START_REQ(set_console_input_info)
242     {
243         req->handle   = 0;
244         req->mask     = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
245         req->output_cp = cp;
246         ret = !wine_server_call_err(req);
247     }
248     SERVER_END_REQ;
249
250     return ret;
251 }
252
253
254 /***********************************************************************
255  *           Beep   (KERNEL32.@)
256  */
257 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
258 {
259     static const char beep = '\a';
260     /* dwFreq and dwDur are ignored by Win95 */
261     if (isatty(2)) write( 2, &beep, 1 );
262     return TRUE;
263 }
264
265
266 /******************************************************************
267  *              OpenConsoleW            (KERNEL32.@)
268  *
269  * Undocumented
270  *      Open a handle to the current process console.
271  *      Returns INVALID_HANDLE_VALUE on failure.
272  */
273 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
274 {
275     HANDLE      output;
276     HANDLE      ret;
277
278     if (strcmpiW(coninW, name) == 0) 
279         output = (HANDLE) FALSE;
280     else if (strcmpiW(conoutW, name) == 0) 
281         output = (HANDLE) TRUE;
282     else
283     {
284         SetLastError(ERROR_INVALID_NAME);
285         return INVALID_HANDLE_VALUE;
286     }
287     if (creation != OPEN_EXISTING)
288     {
289         SetLastError(ERROR_INVALID_PARAMETER);
290         return INVALID_HANDLE_VALUE;
291     }
292
293     SERVER_START_REQ( open_console )
294     {
295         req->from       = output;
296         req->access     = access;
297         req->attributes = inherit ? OBJ_INHERIT : 0;
298         req->share      = FILE_SHARE_READ | FILE_SHARE_WRITE;
299         SetLastError(0);
300         wine_server_call_err( req );
301         ret = reply->handle;
302     }
303     SERVER_END_REQ;
304     if (ret)
305         ret = console_handle_map(ret);
306     else
307     {
308         /* likely, we're not attached to wineconsole
309          * let's try to return a handle to the unix-console
310          */
311         int fd = open("/dev/tty", output ? O_WRONLY : O_RDONLY);
312         ret = INVALID_HANDLE_VALUE;
313         if (fd != -1)
314         {
315             DWORD access = (output ? GENERIC_WRITE : GENERIC_READ) | SYNCHRONIZE;
316             wine_server_fd_to_handle(fd, access, inherit ? OBJ_INHERIT : 0, &ret);
317             close(fd);
318         }
319     }
320     return ret;
321 }
322
323 /******************************************************************
324  *              VerifyConsoleIoHandle            (KERNEL32.@)
325  *
326  * Undocumented
327  */
328 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
329 {
330     BOOL ret;
331
332     if (!is_console_handle(handle)) return FALSE;
333     SERVER_START_REQ(get_console_mode)
334     {
335         req->handle = console_handle_unmap(handle);
336         ret = !wine_server_call_err( req );
337     }
338     SERVER_END_REQ;
339     return ret;
340 }
341
342 /******************************************************************
343  *              DuplicateConsoleHandle            (KERNEL32.@)
344  *
345  * Undocumented
346  */
347 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
348                                      DWORD options)
349 {
350     HANDLE      ret;
351
352     if (!is_console_handle(handle) ||
353         !DuplicateHandle(GetCurrentProcess(), console_handle_unmap(handle), 
354                          GetCurrentProcess(), &ret, access, inherit, options))
355         return INVALID_HANDLE_VALUE;
356     return console_handle_map(ret);
357 }
358
359 /******************************************************************
360  *              CloseConsoleHandle            (KERNEL32.@)
361  *
362  * Undocumented
363  */
364 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
365 {
366     if (!is_console_handle(handle)) 
367     {
368         SetLastError(ERROR_INVALID_PARAMETER);
369         return FALSE;
370     }
371     return CloseHandle(console_handle_unmap(handle));
372 }
373
374 /******************************************************************
375  *              GetConsoleInputWaitHandle            (KERNEL32.@)
376  *
377  * Undocumented
378  */
379 HANDLE WINAPI GetConsoleInputWaitHandle(void)
380 {
381     static HANDLE console_wait_event;
382  
383     /* FIXME: this is not thread safe */
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     SERVER_START_REQ(free_console)
1135     {
1136         ret = !wine_server_call_err( req );
1137     }
1138     SERVER_END_REQ;
1139     return ret;
1140 }
1141
1142 /******************************************************************
1143  *              start_console_renderer
1144  *
1145  * helper for AllocConsole
1146  * starts the renderer process
1147  */
1148 static  BOOL    start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1149                                               HANDLE hEvent)
1150 {
1151     char                buffer[1024];
1152     int                 ret;
1153     PROCESS_INFORMATION pi;
1154
1155     /* FIXME: use dynamic allocation for most of the buffers below */
1156     ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1157     if ((ret > -1) && (ret < sizeof(buffer)) &&
1158         CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1159                        NULL, NULL, si, &pi))
1160     {
1161         if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
1162
1163         TRACE("Started wineconsole pid=%08x tid=%08x\n",
1164               pi.dwProcessId, pi.dwThreadId);
1165
1166         return TRUE;
1167     }
1168     return FALSE;
1169 }
1170
1171 static  BOOL    start_console_renderer(STARTUPINFOA* si)
1172 {
1173     HANDLE              hEvent = 0;
1174     LPSTR               p;
1175     OBJECT_ATTRIBUTES   attr;
1176     BOOL                ret = FALSE;
1177
1178     attr.Length                   = sizeof(attr);
1179     attr.RootDirectory            = 0;
1180     attr.Attributes               = OBJ_INHERIT;
1181     attr.ObjectName               = NULL;
1182     attr.SecurityDescriptor       = NULL;
1183     attr.SecurityQualityOfService = NULL;
1184
1185     NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
1186     if (!hEvent) return FALSE;
1187
1188     /* first try environment variable */
1189     if ((p = getenv("WINECONSOLE")) != NULL)
1190     {
1191         ret = start_console_renderer_helper(p, si, hEvent);
1192         if (!ret)
1193             ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1194                 "trying default access\n", p);
1195     }
1196
1197     /* then try the regular PATH */
1198     if (!ret)
1199         ret = start_console_renderer_helper("wineconsole", si, hEvent);
1200
1201     CloseHandle(hEvent);
1202     return ret;
1203 }
1204
1205 /***********************************************************************
1206  *            AllocConsole (KERNEL32.@)
1207  *
1208  * creates an xterm with a pty to our program
1209  */
1210 BOOL WINAPI AllocConsole(void)
1211 {
1212     HANDLE              handle_in = INVALID_HANDLE_VALUE;
1213     HANDLE              handle_out = INVALID_HANDLE_VALUE;
1214     HANDLE              handle_err = INVALID_HANDLE_VALUE;
1215     STARTUPINFOA        siCurrent;
1216     STARTUPINFOA        siConsole;
1217     char                buffer[1024];
1218
1219     TRACE("()\n");
1220
1221     handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1222                               FALSE, OPEN_EXISTING );
1223
1224     if (VerifyConsoleIoHandle(handle_in))
1225     {
1226         /* we already have a console opened on this process, don't create a new one */
1227         CloseHandle(handle_in);
1228         return FALSE;
1229     }
1230     /* happens when we're running on a Unix console */
1231     if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1232
1233     GetStartupInfoA(&siCurrent);
1234
1235     memset(&siConsole, 0, sizeof(siConsole));
1236     siConsole.cb = sizeof(siConsole);
1237     /* setup a view arguments for wineconsole (it'll use them as default values)  */
1238     if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1239     {
1240         siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1241         siConsole.dwXCountChars = siCurrent.dwXCountChars;
1242         siConsole.dwYCountChars = siCurrent.dwYCountChars;
1243     }
1244     if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1245     {
1246         siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1247         siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1248     }
1249     if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1250     {
1251         siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1252         siConsole.wShowWindow = siCurrent.wShowWindow;
1253     }
1254     /* FIXME (should pass the unicode form) */
1255     if (siCurrent.lpTitle)
1256         siConsole.lpTitle = siCurrent.lpTitle;
1257     else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1258     {
1259         buffer[sizeof(buffer) - 1] = '\0';
1260         siConsole.lpTitle = buffer;
1261     }
1262
1263     if (!start_console_renderer(&siConsole))
1264         goto the_end;
1265
1266     if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1267         /* all std I/O handles are inheritable by default */
1268         handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1269                                   TRUE, OPEN_EXISTING );
1270         if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1271   
1272         handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1273                                    TRUE, OPEN_EXISTING );
1274         if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1275   
1276         if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1277                     &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1278             goto the_end;
1279     } else {
1280         /*  STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1281         handle_in  =  siCurrent.hStdInput;
1282         handle_out =  siCurrent.hStdOutput;
1283         handle_err =  siCurrent.hStdError;
1284     }
1285
1286     /* NT resets the STD_*_HANDLEs on console alloc */
1287     SetStdHandle(STD_INPUT_HANDLE,  handle_in);
1288     SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1289     SetStdHandle(STD_ERROR_HANDLE,  handle_err);
1290
1291     SetLastError(ERROR_SUCCESS);
1292
1293     return TRUE;
1294
1295  the_end:
1296     ERR("Can't allocate console\n");
1297     if (handle_in != INVALID_HANDLE_VALUE)      CloseHandle(handle_in);
1298     if (handle_out != INVALID_HANDLE_VALUE)     CloseHandle(handle_out);
1299     if (handle_err != INVALID_HANDLE_VALUE)     CloseHandle(handle_err);
1300     FreeConsole();
1301     return FALSE;
1302 }
1303
1304
1305 /***********************************************************************
1306  *            ReadConsoleA   (KERNEL32.@)
1307  */
1308 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1309                          LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1310 {
1311     LPWSTR      ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1312     DWORD       ncr = 0;
1313     BOOL        ret;
1314
1315     if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1316         ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1317
1318     if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1319     HeapFree(GetProcessHeap(), 0, ptr);
1320
1321     return ret;
1322 }
1323
1324 /***********************************************************************
1325  *            ReadConsoleW   (KERNEL32.@)
1326  */
1327 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1328                          DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1329 {
1330     DWORD       charsread;
1331     LPWSTR      xbuf = (LPWSTR)lpBuffer;
1332     DWORD       mode;
1333
1334     TRACE("(%p,%p,%d,%p,%p)\n",
1335           hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1336
1337     if (!GetConsoleMode(hConsoleInput, &mode))
1338         return FALSE;
1339
1340     if (mode & ENABLE_LINE_INPUT)
1341     {
1342         if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1343         {
1344             HeapFree(GetProcessHeap(), 0, S_EditString);
1345             if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1346                 return FALSE;
1347             S_EditStrPos = 0;
1348         }
1349         charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1350         if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1351         memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1352         S_EditStrPos += charsread;
1353     }
1354     else
1355     {
1356         INPUT_RECORD    ir;
1357         DWORD           timeout = INFINITE;
1358
1359         /* FIXME: should we read at least 1 char? The SDK does not say */
1360         /* wait for at least one available input record (it doesn't mean we'll have
1361          * chars stored in xbuf...)
1362          *
1363          * Although SDK doc keeps silence about 1 char, SDK examples assume
1364          * that we should wait for at least one character (not key). --KS
1365          */
1366         charsread = 0;
1367         do 
1368         {
1369             if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1370             if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1371                 ir.Event.KeyEvent.uChar.UnicodeChar &&
1372                 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
1373             {
1374                 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1375                 timeout = 0;
1376             }
1377         } while (charsread < nNumberOfCharsToRead);
1378         /* nothing has been read */
1379         if (timeout == INFINITE) return FALSE;
1380     }
1381
1382     if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1383
1384     return TRUE;
1385 }
1386
1387
1388 /***********************************************************************
1389  *            ReadConsoleInputW   (KERNEL32.@)
1390  */
1391 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1392                               DWORD nLength, LPDWORD lpNumberOfEventsRead)
1393 {
1394     DWORD idx = 0;
1395     DWORD timeout = INFINITE;
1396
1397     if (!nLength)
1398     {
1399         if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1400         return TRUE;
1401     }
1402
1403     /* loop until we get at least one event */
1404     while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1405            ++idx < nLength)
1406         timeout = 0;
1407
1408     if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1409     return idx != 0;
1410 }
1411
1412
1413 /******************************************************************************
1414  * WriteConsoleOutputCharacterW [KERNEL32.@]
1415  * 
1416  * Copy character to consecutive cells in the console screen buffer.
1417  *
1418  * PARAMS
1419  *    hConsoleOutput    [I] Handle to screen buffer
1420  *    str               [I] Pointer to buffer with chars to write
1421  *    length            [I] Number of cells to write to
1422  *    coord             [I] Coords of first cell
1423  *    lpNumCharsWritten [O] Pointer to number of cells written
1424  *
1425  * RETURNS
1426  *    Success: TRUE
1427  *    Failure: FALSE
1428  *
1429  */
1430 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1431                                           COORD coord, LPDWORD lpNumCharsWritten )
1432 {
1433     BOOL ret;
1434
1435     TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1436           debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1437
1438     SERVER_START_REQ( write_console_output )
1439     {
1440         req->handle = console_handle_unmap(hConsoleOutput);
1441         req->x      = coord.X;
1442         req->y      = coord.Y;
1443         req->mode   = CHAR_INFO_MODE_TEXT;
1444         req->wrap   = TRUE;
1445         wine_server_add_data( req, str, length * sizeof(WCHAR) );
1446         if ((ret = !wine_server_call_err( req )))
1447         {
1448             if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1449         }
1450     }
1451     SERVER_END_REQ;
1452     return ret;
1453 }
1454
1455
1456 /******************************************************************************
1457  * SetConsoleTitleW [KERNEL32.@]  Sets title bar string for console
1458  *
1459  * PARAMS
1460  *    title [I] Address of new title
1461  *
1462  * RETURNS
1463  *    Success: TRUE
1464  *    Failure: FALSE
1465  */
1466 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1467 {
1468     BOOL ret;
1469
1470     TRACE("(%s)\n", debugstr_w(title));
1471     SERVER_START_REQ( set_console_input_info )
1472     {
1473         req->handle = 0;
1474         req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1475         wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1476         ret = !wine_server_call_err( req );
1477     }
1478     SERVER_END_REQ;
1479     return ret;
1480 }
1481
1482
1483 /***********************************************************************
1484  *            GetNumberOfConsoleMouseButtons   (KERNEL32.@)
1485  */
1486 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1487 {
1488     FIXME("(%p): stub\n", nrofbuttons);
1489     *nrofbuttons = 2;
1490     return TRUE;
1491 }
1492
1493 /******************************************************************************
1494  *  SetConsoleInputExeNameW      [KERNEL32.@]
1495  */
1496 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1497 {
1498     TRACE("(%s)\n", debugstr_w(name));
1499
1500     if (!name || !name[0])
1501     {
1502         SetLastError(ERROR_INVALID_PARAMETER);
1503         return FALSE;
1504     }
1505
1506     RtlEnterCriticalSection(&CONSOLE_CritSect);
1507     if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1508     RtlLeaveCriticalSection(&CONSOLE_CritSect);
1509
1510     return TRUE;
1511 }
1512
1513 /******************************************************************************
1514  *  SetConsoleInputExeNameA      [KERNEL32.@]
1515  */
1516 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1517 {
1518     int len;
1519     LPWSTR nameW;
1520     BOOL ret;
1521
1522     if (!name || !name[0])
1523     {
1524         SetLastError(ERROR_INVALID_PARAMETER);
1525         return FALSE;
1526     }
1527
1528     len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1529     if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1530
1531     MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1532     ret = SetConsoleInputExeNameW(nameW);
1533     HeapFree(GetProcessHeap(), 0, nameW);
1534
1535     return ret;
1536 }
1537
1538 /******************************************************************
1539  *              CONSOLE_DefaultHandler
1540  *
1541  * Final control event handler
1542  */
1543 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1544 {
1545     FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1546     ExitProcess(0);
1547     /* should never go here */
1548     return TRUE;
1549 }
1550
1551 /******************************************************************************
1552  * SetConsoleCtrlHandler [KERNEL32.@]  Adds function to calling process list
1553  *
1554  * PARAMS
1555  *    func [I] Address of handler function
1556  *    add  [I] Handler to add or remove
1557  *
1558  * RETURNS
1559  *    Success: TRUE
1560  *    Failure: FALSE
1561  */
1562
1563 struct ConsoleHandler
1564 {
1565     PHANDLER_ROUTINE            handler;
1566     struct ConsoleHandler*      next;
1567 };
1568
1569 static struct ConsoleHandler    CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1570 static struct ConsoleHandler*   CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1571
1572 /*****************************************************************************/
1573
1574 /******************************************************************
1575  *              SetConsoleCtrlHandler (KERNEL32.@)
1576  */
1577 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1578 {
1579     BOOL        ret = TRUE;
1580
1581     TRACE("(%p,%i)\n", func, add);
1582
1583     if (!func)
1584     {
1585         RtlEnterCriticalSection(&CONSOLE_CritSect);
1586         if (add)
1587             NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1588         else
1589             NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1590         RtlLeaveCriticalSection(&CONSOLE_CritSect);
1591     }
1592     else if (add)
1593     {
1594         struct ConsoleHandler*  ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1595
1596         if (!ch) return FALSE;
1597         ch->handler = func;
1598         RtlEnterCriticalSection(&CONSOLE_CritSect);
1599         ch->next = CONSOLE_Handlers;
1600         CONSOLE_Handlers = ch;
1601         RtlLeaveCriticalSection(&CONSOLE_CritSect);
1602     }
1603     else
1604     {
1605         struct ConsoleHandler**  ch;
1606         RtlEnterCriticalSection(&CONSOLE_CritSect);
1607         for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1608         {
1609             if ((*ch)->handler == func) break;
1610         }
1611         if (*ch)
1612         {
1613             struct ConsoleHandler*   rch = *ch;
1614
1615             /* sanity check */
1616             if (rch == &CONSOLE_DefaultConsoleHandler)
1617             {
1618                 ERR("Who's trying to remove default handler???\n");
1619                 SetLastError(ERROR_INVALID_PARAMETER);
1620                 ret = FALSE;
1621             }
1622             else
1623             {
1624                 *ch = rch->next;
1625                 HeapFree(GetProcessHeap(), 0, rch);
1626             }
1627         }
1628         else
1629         {
1630             WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1631             SetLastError(ERROR_INVALID_PARAMETER);
1632             ret = FALSE;
1633         }
1634         RtlLeaveCriticalSection(&CONSOLE_CritSect);
1635     }
1636     return ret;
1637 }
1638
1639 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
1640 {
1641     TRACE("(%x)\n", GetExceptionCode());
1642     return EXCEPTION_EXECUTE_HANDLER;
1643 }
1644
1645 /******************************************************************
1646  *              CONSOLE_SendEventThread
1647  *
1648  * Internal helper to pass an event to the list on installed handlers
1649  */
1650 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1651 {
1652     DWORD_PTR                   event = (DWORD_PTR)pmt;
1653     struct ConsoleHandler*      ch;
1654
1655     if (event == CTRL_C_EVENT)
1656     {
1657         BOOL    caught_by_dbg = TRUE;
1658         /* First, try to pass the ctrl-C event to the debugger (if any)
1659          * If it continues, there's nothing more to do
1660          * Otherwise, we need to send the ctrl-C event to the handlers
1661          */
1662         __TRY
1663         {
1664             RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1665         }
1666         __EXCEPT(CONSOLE_CtrlEventHandler)
1667         {
1668             caught_by_dbg = FALSE;
1669         }
1670         __ENDTRY;
1671         if (caught_by_dbg) return 0;
1672         /* the debugger didn't continue... so, pass to ctrl handlers */
1673     }
1674     RtlEnterCriticalSection(&CONSOLE_CritSect);
1675     for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1676     {
1677         if (ch->handler(event)) break;
1678     }
1679     RtlLeaveCriticalSection(&CONSOLE_CritSect);
1680     return 1;
1681 }
1682
1683 /******************************************************************
1684  *              CONSOLE_HandleCtrlC
1685  *
1686  * Check whether the shall manipulate CtrlC events
1687  */
1688 int     CONSOLE_HandleCtrlC(unsigned sig)
1689 {
1690     /* FIXME: better test whether a console is attached to this process ??? */
1691     extern    unsigned CONSOLE_GetNumHistoryEntries(void);
1692     if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1693
1694     /* check if we have to ignore ctrl-C events */
1695     if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1696     {
1697         /* Create a separate thread to signal all the events. 
1698          * This is needed because:
1699          *  - this function can be called in an Unix signal handler (hence on an
1700          *    different stack than the thread that's running). This breaks the 
1701          *    Win32 exception mechanisms (where the thread's stack is checked).
1702          *  - since the current thread, while processing the signal, can hold the
1703          *    console critical section, we need another execution environment where
1704          *    we can wait on this critical section 
1705          */
1706         CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1707     }
1708     return 1;
1709 }
1710
1711 /******************************************************************************
1712  * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1713  *
1714  * PARAMS
1715  *    dwCtrlEvent        [I] Type of event
1716  *    dwProcessGroupID   [I] Process group ID to send event to
1717  *
1718  * RETURNS
1719  *    Success: True
1720  *    Failure: False (and *should* [but doesn't] set LastError)
1721  */
1722 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1723                                      DWORD dwProcessGroupID)
1724 {
1725     BOOL ret;
1726
1727     TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
1728
1729     if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1730     {
1731         ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
1732         return FALSE;
1733     }
1734
1735     SERVER_START_REQ( send_console_signal )
1736     {
1737         req->signal = dwCtrlEvent;
1738         req->group_id = dwProcessGroupID;
1739         ret = !wine_server_call_err( req );
1740     }
1741     SERVER_END_REQ;
1742
1743     /* FIXME: shall this function be synchronous, ie only return when all events
1744      * have been handled by all processes in the given group ?
1745      * As of today, we don't wait...
1746      */
1747     return ret;
1748 }
1749
1750
1751 /******************************************************************************
1752  * CreateConsoleScreenBuffer [KERNEL32.@]  Creates a console screen buffer
1753  *
1754  * PARAMS
1755  *    dwDesiredAccess    [I] Access flag
1756  *    dwShareMode        [I] Buffer share mode
1757  *    sa                 [I] Security attributes
1758  *    dwFlags            [I] Type of buffer to create
1759  *    lpScreenBufferData [I] Reserved
1760  *
1761  * NOTES
1762  *    Should call SetLastError
1763  *
1764  * RETURNS
1765  *    Success: Handle to new console screen buffer
1766  *    Failure: INVALID_HANDLE_VALUE
1767  */
1768 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1769                                         LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1770                                         LPVOID lpScreenBufferData)
1771 {
1772     HANDLE      ret = INVALID_HANDLE_VALUE;
1773
1774     TRACE("(%d,%d,%p,%d,%p)\n",
1775           dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1776
1777     if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1778     {
1779         SetLastError(ERROR_INVALID_PARAMETER);
1780         return INVALID_HANDLE_VALUE;
1781     }
1782
1783     SERVER_START_REQ(create_console_output)
1784     {
1785         req->handle_in  = 0;
1786         req->access     = dwDesiredAccess;
1787         req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
1788         req->share      = dwShareMode;
1789         if (!wine_server_call_err( req )) ret = reply->handle_out;
1790     }
1791     SERVER_END_REQ;
1792
1793     return ret;
1794 }
1795
1796
1797 /***********************************************************************
1798  *           GetConsoleScreenBufferInfo   (KERNEL32.@)
1799  */
1800 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1801 {
1802     BOOL        ret;
1803
1804     SERVER_START_REQ(get_console_output_info)
1805     {
1806         req->handle = console_handle_unmap(hConsoleOutput);
1807         if ((ret = !wine_server_call_err( req )))
1808         {
1809             csbi->dwSize.X              = reply->width;
1810             csbi->dwSize.Y              = reply->height;
1811             csbi->dwCursorPosition.X    = reply->cursor_x;
1812             csbi->dwCursorPosition.Y    = reply->cursor_y;
1813             csbi->wAttributes           = reply->attr;
1814             csbi->srWindow.Left         = reply->win_left;
1815             csbi->srWindow.Right        = reply->win_right;
1816             csbi->srWindow.Top          = reply->win_top;
1817             csbi->srWindow.Bottom       = reply->win_bottom;
1818             csbi->dwMaximumWindowSize.X = reply->max_width;
1819             csbi->dwMaximumWindowSize.Y = reply->max_height;
1820         }
1821     }
1822     SERVER_END_REQ;
1823
1824     TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n", 
1825           hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1826           csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1827           csbi->wAttributes,
1828           csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1829           csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1830
1831     return ret;
1832 }
1833
1834
1835 /******************************************************************************
1836  * SetConsoleActiveScreenBuffer [KERNEL32.@]  Sets buffer to current console
1837  *
1838  * RETURNS
1839  *    Success: TRUE
1840  *    Failure: FALSE
1841  */
1842 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1843 {
1844     BOOL ret;
1845
1846     TRACE("(%p)\n", hConsoleOutput);
1847
1848     SERVER_START_REQ( set_console_input_info )
1849     {
1850         req->handle    = 0;
1851         req->mask      = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1852         req->active_sb = hConsoleOutput;
1853         ret = !wine_server_call_err( req );
1854     }
1855     SERVER_END_REQ;
1856     return ret;
1857 }
1858
1859
1860 /***********************************************************************
1861  *            GetConsoleMode   (KERNEL32.@)
1862  */
1863 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1864 {
1865     BOOL ret;
1866
1867     SERVER_START_REQ(get_console_mode)
1868     {
1869         req->handle = console_handle_unmap(hcon);
1870         ret = !wine_server_call_err( req );
1871         if (ret && mode) *mode = reply->mode;
1872     }
1873     SERVER_END_REQ;
1874     return ret;
1875 }
1876
1877
1878 /******************************************************************************
1879  * SetConsoleMode [KERNEL32.@]  Sets input mode of console's input buffer
1880  *
1881  * PARAMS
1882  *    hcon [I] Handle to console input or screen buffer
1883  *    mode [I] Input or output mode to set
1884  *
1885  * RETURNS
1886  *    Success: TRUE
1887  *    Failure: FALSE
1888  *
1889  *    mode:
1890  *      ENABLE_PROCESSED_INPUT  0x01
1891  *      ENABLE_LINE_INPUT       0x02
1892  *      ENABLE_ECHO_INPUT       0x04
1893  *      ENABLE_WINDOW_INPUT     0x08
1894  *      ENABLE_MOUSE_INPUT      0x10
1895  */
1896 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1897 {
1898     BOOL ret;
1899
1900     SERVER_START_REQ(set_console_mode)
1901     {
1902         req->handle = console_handle_unmap(hcon);
1903         req->mode = mode;
1904         ret = !wine_server_call_err( req );
1905     }
1906     SERVER_END_REQ;
1907     /* FIXME: when resetting a console input to editline mode, I think we should
1908      * empty the S_EditString buffer
1909      */
1910
1911     TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
1912
1913     return ret;
1914 }
1915
1916
1917 /******************************************************************
1918  *              CONSOLE_WriteChars
1919  *
1920  * WriteConsoleOutput helper: hides server call semantics
1921  * writes a string at a given pos with standard attribute
1922  */
1923 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1924 {
1925     int written = -1;
1926
1927     if (!nc) return 0;
1928
1929     SERVER_START_REQ( write_console_output )
1930     {
1931         req->handle = console_handle_unmap(hCon);
1932         req->x      = pos->X;
1933         req->y      = pos->Y;
1934         req->mode   = CHAR_INFO_MODE_TEXTSTDATTR;
1935         req->wrap   = FALSE;
1936         wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1937         if (!wine_server_call_err( req )) written = reply->written;
1938     }
1939     SERVER_END_REQ;
1940
1941     if (written > 0) pos->X += written;
1942     return written;
1943 }
1944
1945 /******************************************************************
1946  *              next_line
1947  *
1948  * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1949  *
1950  */
1951 static int      next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1952 {
1953     SMALL_RECT  src;
1954     CHAR_INFO   ci;
1955     COORD       dst;
1956
1957     csbi->dwCursorPosition.X = 0;
1958     csbi->dwCursorPosition.Y++;
1959
1960     if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1961
1962     src.Top    = 1;
1963     src.Bottom = csbi->dwSize.Y - 1;
1964     src.Left   = 0;
1965     src.Right  = csbi->dwSize.X - 1;
1966
1967     dst.X      = 0;
1968     dst.Y      = 0;
1969
1970     ci.Attributes = csbi->wAttributes;
1971     ci.Char.UnicodeChar = ' ';
1972
1973     csbi->dwCursorPosition.Y--;
1974     if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1975         return 0;
1976     return 1;
1977 }
1978
1979 /******************************************************************
1980  *              write_block
1981  *
1982  * WriteConsoleOutput helper: writes a block of non special characters
1983  * Block can spread on several lines, and wrapping, if needed, is
1984  * handled
1985  *
1986  */
1987 static int      write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1988                             DWORD mode, LPCWSTR ptr, int len)
1989 {
1990     int blk;    /* number of chars to write on current line */
1991     int done;   /* number of chars already written */
1992
1993     if (len <= 0) return 1;
1994
1995     if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1996     {
1997         for (done = 0; done < len; done += blk)
1998         {
1999             blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2000
2001             if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2002                 return 0;
2003             if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2004                 return 0;
2005         }
2006     }
2007     else
2008     {
2009         int     pos = csbi->dwCursorPosition.X;
2010         /* FIXME: we could reduce the number of loops
2011          * but, in most cases we wouldn't gain lots of time (it would only
2012          * happen if we're asked to overwrite more than twice the part of the line,
2013          * which is unlikely
2014          */
2015         for (blk = done = 0; done < len; done += blk)
2016         {
2017             blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2018
2019             csbi->dwCursorPosition.X = pos;
2020             if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2021                 return 0;
2022         }
2023     }
2024
2025     return 1;
2026 }
2027
2028 /***********************************************************************
2029  *            WriteConsoleW   (KERNEL32.@)
2030  */
2031 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2032                           LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2033 {
2034     DWORD                       mode;
2035     DWORD                       nw = 0;
2036     const WCHAR*                psz = lpBuffer;
2037     CONSOLE_SCREEN_BUFFER_INFO  csbi;
2038     int                         k, first = 0;
2039
2040     TRACE("%p %s %d %p %p\n",
2041           hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2042           nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2043
2044     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2045
2046     if (!GetConsoleMode(hConsoleOutput, &mode) ||
2047         !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2048         return FALSE;
2049
2050     if (mode & ENABLE_PROCESSED_OUTPUT)
2051     {
2052         unsigned int    i;
2053
2054         for (i = 0; i < nNumberOfCharsToWrite; i++)
2055         {
2056             switch (psz[i])
2057             {
2058             case '\b': case '\t': case '\n': case '\a': case '\r':
2059                 /* don't handle here the i-th char... done below */
2060                 if ((k = i - first) > 0)
2061                 {
2062                     if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2063                         goto the_end;
2064                     nw += k;
2065                 }
2066                 first = i + 1;
2067                 nw++;
2068             }
2069             switch (psz[i])
2070             {
2071             case '\b':
2072                 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2073                 break;
2074             case '\t':
2075                 {
2076                     WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2077
2078                     if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2079                                      ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2080                         goto the_end;
2081                 }
2082                 break;
2083             case '\n':
2084                 next_line(hConsoleOutput, &csbi);
2085                 break;
2086             case '\a':
2087                 Beep(400, 300);
2088                 break;
2089             case '\r':
2090                 csbi.dwCursorPosition.X = 0;
2091                 break;
2092             default:
2093                 break;
2094             }
2095         }
2096     }
2097
2098     /* write the remaining block (if any) if processed output is enabled, or the
2099      * entire buffer otherwise
2100      */
2101     if ((k = nNumberOfCharsToWrite - first) > 0)
2102     {
2103         if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2104             goto the_end;
2105         nw += k;
2106     }
2107
2108  the_end:
2109     SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2110     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2111     return nw != 0;
2112 }
2113
2114
2115 /***********************************************************************
2116  *            WriteConsoleA   (KERNEL32.@)
2117  */
2118 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2119                           LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2120 {
2121     BOOL        ret;
2122     LPWSTR      xstring;
2123     DWORD       n;
2124
2125     n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2126
2127     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2128     xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2129     if (!xstring) return 0;
2130
2131     MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2132
2133     ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2134
2135     HeapFree(GetProcessHeap(), 0, xstring);
2136
2137     return ret;
2138 }
2139
2140 /******************************************************************************
2141  * SetConsoleCursorPosition [KERNEL32.@]
2142  * Sets the cursor position in console
2143  *
2144  * PARAMS
2145  *    hConsoleOutput   [I] Handle of console screen buffer
2146  *    dwCursorPosition [I] New cursor position coordinates
2147  *
2148  * RETURNS
2149  *    Success: TRUE
2150  *    Failure: FALSE
2151  */
2152 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2153 {
2154     BOOL                        ret;
2155     CONSOLE_SCREEN_BUFFER_INFO  csbi;
2156     int                         do_move = 0;
2157     int                         w, h;
2158
2159     TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2160
2161     SERVER_START_REQ(set_console_output_info)
2162     {
2163         req->handle         = console_handle_unmap(hcon);
2164         req->cursor_x       = pos.X;
2165         req->cursor_y       = pos.Y;
2166         req->mask           = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2167         ret = !wine_server_call_err( req );
2168     }
2169     SERVER_END_REQ;
2170
2171     if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2172         return FALSE;
2173
2174     /* if cursor is no longer visible, scroll the visible window... */
2175     w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2176     h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2177     if (pos.X < csbi.srWindow.Left)
2178     {
2179         csbi.srWindow.Left   = min(pos.X, csbi.dwSize.X - w);
2180         do_move++;
2181     }
2182     else if (pos.X > csbi.srWindow.Right)
2183     {
2184         csbi.srWindow.Left   = max(pos.X, w) - w + 1;
2185         do_move++;
2186     }
2187     csbi.srWindow.Right  = csbi.srWindow.Left + w - 1;
2188
2189     if (pos.Y < csbi.srWindow.Top)
2190     {
2191         csbi.srWindow.Top    = min(pos.Y, csbi.dwSize.Y - h);
2192         do_move++;
2193     }
2194     else if (pos.Y > csbi.srWindow.Bottom)
2195     {
2196         csbi.srWindow.Top   = max(pos.Y, h) - h + 1;
2197         do_move++;
2198     }
2199     csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2200
2201     ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2202
2203     return ret;
2204 }
2205
2206 /******************************************************************************
2207  * GetConsoleCursorInfo [KERNEL32.@]  Gets size and visibility of console
2208  *
2209  * PARAMS
2210  *    hcon  [I] Handle to console screen buffer
2211  *    cinfo [O] Address of cursor information
2212  *
2213  * RETURNS
2214  *    Success: TRUE
2215  *    Failure: FALSE
2216  */
2217 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2218 {
2219     BOOL ret;
2220
2221     SERVER_START_REQ(get_console_output_info)
2222     {
2223         req->handle = console_handle_unmap(hCon);
2224         ret = !wine_server_call_err( req );
2225         if (ret && cinfo)
2226         {
2227             cinfo->dwSize = reply->cursor_size;
2228             cinfo->bVisible = reply->cursor_visible;
2229         }
2230     }
2231     SERVER_END_REQ;
2232
2233     TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2234     return ret;
2235 }
2236
2237
2238 /******************************************************************************
2239  * SetConsoleCursorInfo [KERNEL32.@]  Sets size and visibility of cursor
2240  *
2241  * PARAMS
2242  *      hcon    [I] Handle to console screen buffer
2243  *      cinfo   [I] Address of cursor information
2244  * RETURNS
2245  *    Success: TRUE
2246  *    Failure: FALSE
2247  */
2248 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2249 {
2250     BOOL ret;
2251
2252     TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2253     SERVER_START_REQ(set_console_output_info)
2254     {
2255         req->handle         = console_handle_unmap(hCon);
2256         req->cursor_size    = cinfo->dwSize;
2257         req->cursor_visible = cinfo->bVisible;
2258         req->mask           = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2259         ret = !wine_server_call_err( req );
2260     }
2261     SERVER_END_REQ;
2262     return ret;
2263 }
2264
2265
2266 /******************************************************************************
2267  * SetConsoleWindowInfo [KERNEL32.@]  Sets size and position of console
2268  *
2269  * PARAMS
2270  *      hcon            [I] Handle to console screen buffer
2271  *      bAbsolute       [I] Coordinate type flag
2272  *      window          [I] Address of new window rectangle
2273  * RETURNS
2274  *    Success: TRUE
2275  *    Failure: FALSE
2276  */
2277 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2278 {
2279     SMALL_RECT  p = *window;
2280     BOOL        ret;
2281
2282     TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2283
2284     if (!bAbsolute)
2285     {
2286         CONSOLE_SCREEN_BUFFER_INFO      csbi;
2287
2288         if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2289             return FALSE;
2290         p.Left   += csbi.srWindow.Left;
2291         p.Top    += csbi.srWindow.Top;
2292         p.Right  += csbi.srWindow.Right;
2293         p.Bottom += csbi.srWindow.Bottom;
2294     }
2295     SERVER_START_REQ(set_console_output_info)
2296     {
2297         req->handle         = console_handle_unmap(hCon);
2298         req->win_left       = p.Left;
2299         req->win_top        = p.Top;
2300         req->win_right      = p.Right;
2301         req->win_bottom     = p.Bottom;
2302         req->mask           = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2303         ret = !wine_server_call_err( req );
2304     }
2305     SERVER_END_REQ;
2306
2307     return ret;
2308 }
2309
2310
2311 /******************************************************************************
2312  * SetConsoleTextAttribute [KERNEL32.@]  Sets colors for text
2313  *
2314  * Sets the foreground and background color attributes of characters
2315  * written to the screen buffer.
2316  *
2317  * RETURNS
2318  *    Success: TRUE
2319  *    Failure: FALSE
2320  */
2321 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2322 {
2323     BOOL ret;
2324
2325     TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2326     SERVER_START_REQ(set_console_output_info)
2327     {
2328         req->handle = console_handle_unmap(hConsoleOutput);
2329         req->attr   = wAttr;
2330         req->mask   = SET_CONSOLE_OUTPUT_INFO_ATTR;
2331         ret = !wine_server_call_err( req );
2332     }
2333     SERVER_END_REQ;
2334     return ret;
2335 }
2336
2337
2338 /******************************************************************************
2339  * SetConsoleScreenBufferSize [KERNEL32.@]  Changes size of console
2340  *
2341  * PARAMS
2342  *    hConsoleOutput [I] Handle to console screen buffer
2343  *    dwSize         [I] New size in character rows and cols
2344  *
2345  * RETURNS
2346  *    Success: TRUE
2347  *    Failure: FALSE
2348  */
2349 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2350 {
2351     BOOL ret;
2352
2353     TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2354     SERVER_START_REQ(set_console_output_info)
2355     {
2356         req->handle = console_handle_unmap(hConsoleOutput);
2357         req->width  = dwSize.X;
2358         req->height = dwSize.Y;
2359         req->mask   = SET_CONSOLE_OUTPUT_INFO_SIZE;
2360         ret = !wine_server_call_err( req );
2361     }
2362     SERVER_END_REQ;
2363     return ret;
2364 }
2365
2366
2367 /******************************************************************************
2368  * ScrollConsoleScreenBufferA [KERNEL32.@]
2369  *
2370  */
2371 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2372                                        LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2373                                        LPCHAR_INFO lpFill)
2374 {
2375     CHAR_INFO   ciw;
2376
2377     ciw.Attributes = lpFill->Attributes;
2378     MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2379
2380     return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2381                                       dwDestOrigin, &ciw);
2382 }
2383
2384 /******************************************************************
2385  *              CONSOLE_FillLineUniform
2386  *
2387  * Helper function for ScrollConsoleScreenBufferW
2388  * Fills a part of a line with a constant character info
2389  */
2390 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2391 {
2392     SERVER_START_REQ( fill_console_output )
2393     {
2394         req->handle    = console_handle_unmap(hConsoleOutput);
2395         req->mode      = CHAR_INFO_MODE_TEXTATTR;
2396         req->x         = i;
2397         req->y         = j;
2398         req->count     = len;
2399         req->wrap      = FALSE;
2400         req->data.ch   = lpFill->Char.UnicodeChar;
2401         req->data.attr = lpFill->Attributes;
2402         wine_server_call_err( req );
2403     }
2404     SERVER_END_REQ;
2405 }
2406
2407 /******************************************************************************
2408  * ScrollConsoleScreenBufferW [KERNEL32.@]
2409  *
2410  */
2411
2412 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2413                                        LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2414                                        LPCHAR_INFO lpFill)
2415 {
2416     SMALL_RECT                  dst;
2417     DWORD                       ret;
2418     int                         i, j;
2419     int                         start = -1;
2420     SMALL_RECT                  clip;
2421     CONSOLE_SCREEN_BUFFER_INFO  csbi;
2422     BOOL                        inside;
2423     COORD                       src;
2424
2425     if (lpClipRect)
2426         TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2427               lpScrollRect->Left, lpScrollRect->Top,
2428               lpScrollRect->Right, lpScrollRect->Bottom,
2429               lpClipRect->Left, lpClipRect->Top,
2430               lpClipRect->Right, lpClipRect->Bottom,
2431               dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2432     else
2433         TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2434               lpScrollRect->Left, lpScrollRect->Top,
2435               lpScrollRect->Right, lpScrollRect->Bottom,
2436               dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2437
2438     if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2439         return FALSE;
2440
2441     src.X = lpScrollRect->Left;
2442     src.Y = lpScrollRect->Top;
2443
2444     /* step 1: get dst rect */
2445     dst.Left = dwDestOrigin.X;
2446     dst.Top = dwDestOrigin.Y;
2447     dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2448     dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2449
2450     /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2451     if (lpClipRect)
2452     {
2453         clip.Left   = max(0, lpClipRect->Left);
2454         clip.Right  = min(csbi.dwSize.X - 1, lpClipRect->Right);
2455         clip.Top    = max(0, lpClipRect->Top);
2456         clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2457     }
2458     else
2459     {
2460         clip.Left   = 0;
2461         clip.Right  = csbi.dwSize.X - 1;
2462         clip.Top    = 0;
2463         clip.Bottom = csbi.dwSize.Y - 1;
2464     }
2465     if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2466
2467     /* step 2b: clip dst rect */
2468     if (dst.Left   < clip.Left  ) {src.X += clip.Left - dst.Left; dst.Left   = clip.Left;}
2469     if (dst.Top    < clip.Top   ) {src.Y += clip.Top  - dst.Top;  dst.Top    = clip.Top;}
2470     if (dst.Right  > clip.Right ) dst.Right  = clip.Right;
2471     if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2472
2473     /* step 3: transfer the bits */
2474     SERVER_START_REQ(move_console_output)
2475     {
2476         req->handle = console_handle_unmap(hConsoleOutput);
2477         req->x_src = src.X;
2478         req->y_src = src.Y;
2479         req->x_dst = dst.Left;
2480         req->y_dst = dst.Top;
2481         req->w = dst.Right - dst.Left + 1;
2482         req->h = dst.Bottom - dst.Top + 1;
2483         ret = !wine_server_call_err( req );
2484     }
2485     SERVER_END_REQ;
2486
2487     if (!ret) return FALSE;
2488
2489     /* step 4: clean out the exposed part */
2490
2491     /* have to write cell [i,j] if it is not in dst rect (because it has already
2492      * been written to by the scroll) and is in clip (we shall not write
2493      * outside of clip)
2494      */
2495     for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2496     {
2497         inside = dst.Top <= j && j <= dst.Bottom;
2498         start = -1;
2499         for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2500         {
2501             if (inside && dst.Left <= i && i <= dst.Right)
2502             {
2503                 if (start != -1)
2504                 {
2505                     CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2506                     start = -1;
2507                 }
2508             }
2509             else
2510             {
2511                 if (start == -1) start = i;
2512             }
2513         }
2514         if (start != -1)
2515             CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2516     }
2517
2518     return TRUE;
2519 }
2520
2521 /******************************************************************
2522  *              AttachConsole  (KERNEL32.@)
2523  */
2524 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2525 {
2526     FIXME("stub %x\n",dwProcessId);
2527     return TRUE;
2528 }
2529
2530
2531 /* ====================================================================
2532  *
2533  * Console manipulation functions
2534  *
2535  * ====================================================================*/
2536
2537 /* some missing functions...
2538  * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2539  * should get the right API and implement them
2540  *      GetConsoleCommandHistory[AW] (dword dword dword)
2541  *      GetConsoleCommandHistoryLength[AW]
2542  *      SetConsoleCommandHistoryMode
2543  *      SetConsoleNumberOfCommands[AW]
2544  */
2545 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2546 {
2547     int len = 0;
2548
2549     SERVER_START_REQ( get_console_input_history )
2550     {
2551         req->handle = 0;
2552         req->index = idx;
2553         if (buf && buf_len > 1)
2554         {
2555             wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2556         }
2557         if (!wine_server_call_err( req ))
2558         {
2559             if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2560             len = reply->total / sizeof(WCHAR) + 1;
2561         }
2562     }
2563     SERVER_END_REQ;
2564     return len;
2565 }
2566
2567 /******************************************************************
2568  *              CONSOLE_AppendHistory
2569  *
2570  *
2571  */
2572 BOOL    CONSOLE_AppendHistory(const WCHAR* ptr)
2573 {
2574     size_t      len = strlenW(ptr);
2575     BOOL        ret;
2576
2577     while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2578     if (!len) return FALSE;
2579
2580     SERVER_START_REQ( append_console_input_history )
2581     {
2582         req->handle = 0;
2583         wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2584         ret = !wine_server_call_err( req );
2585     }
2586     SERVER_END_REQ;
2587     return ret;
2588 }
2589
2590 /******************************************************************
2591  *              CONSOLE_GetNumHistoryEntries
2592  *
2593  *
2594  */
2595 unsigned CONSOLE_GetNumHistoryEntries(void)
2596 {
2597     unsigned ret = -1;
2598     SERVER_START_REQ(get_console_input_info)
2599     {
2600         req->handle = 0;
2601         if (!wine_server_call_err( req )) ret = reply->history_index;
2602     }
2603     SERVER_END_REQ;
2604     return ret;
2605 }
2606
2607 /******************************************************************
2608  *              CONSOLE_GetEditionMode
2609  *
2610  *
2611  */
2612 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2613 {
2614     unsigned ret = FALSE;
2615     SERVER_START_REQ(get_console_input_info)
2616     {
2617         req->handle = console_handle_unmap(hConIn);
2618         if ((ret = !wine_server_call_err( req )))
2619             *mode = reply->edition_mode;
2620     }
2621     SERVER_END_REQ;
2622     return ret;
2623 }