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