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