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