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