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