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