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