Compile the kernel dll with -DSTRICT.
[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 "msvcrt/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     return ret;
753 }
754
755
756 /******************************************************************************
757  * GetConsoleTitleW [KERNEL32.@]  Retrieves title string for console
758  *
759  * PARAMS
760  *    title [O] Address of buffer for title
761  *    size  [I] Size of buffer
762  *
763  * RETURNS
764  *    Success: Length of string copied
765  *    Failure: 0
766  */
767 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
768 {
769     DWORD ret = 0;
770
771     SERVER_START_REQ( get_console_input_info )
772     {
773         req->handle = 0;
774         wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
775         if (!wine_server_call_err( req ))
776         {
777             ret = wine_server_reply_size(reply) / sizeof(WCHAR);
778             title[ret] = 0;
779         }
780     }
781     SERVER_END_REQ;
782     return ret;
783 }
784
785
786 /***********************************************************************
787  *            GetLargestConsoleWindowSize   (KERNEL32.@)
788  *
789  * NOTE
790  *      This should return a COORD, but calling convention for returning
791  *      structures is different between Windows and gcc on i386.
792  *
793  * VERSION: [i386]
794  */
795 #ifdef __i386__
796 #undef GetLargestConsoleWindowSize
797 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
798 {
799     COORD c;
800     c.X = 80;
801     c.Y = 24;
802     return *(DWORD *)&c;
803 }
804 #endif /* defined(__i386__) */
805
806
807 /***********************************************************************
808  *            GetLargestConsoleWindowSize   (KERNEL32.@)
809  *
810  * NOTE
811  *      This should return a COORD, but calling convention for returning
812  *      structures is different between Windows and gcc on i386.
813  *
814  * VERSION: [!i386]
815  */
816 #ifndef __i386__
817 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
818 {
819     COORD c;
820     c.X = 80;
821     c.Y = 24;
822     return c;
823 }
824 #endif /* defined(__i386__) */
825
826 static WCHAR*   S_EditString /* = NULL */;
827 static unsigned S_EditStrPos /* = 0 */;
828
829 /***********************************************************************
830  *            FreeConsole (KERNEL32.@)
831  */
832 BOOL WINAPI FreeConsole(VOID)
833 {
834     BOOL ret;
835
836     SERVER_START_REQ(free_console)
837     {
838         ret = !wine_server_call_err( req );
839     }
840     SERVER_END_REQ;
841     return ret;
842 }
843
844 /******************************************************************
845  *              start_console_renderer
846  *
847  * helper for AllocConsole
848  * starts the renderer process
849  */
850 static  BOOL    start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
851                                               HANDLE hEvent)
852 {
853     char                buffer[1024];
854     int                 ret;
855     PROCESS_INFORMATION pi;
856
857     /* FIXME: use dynamic allocation for most of the buffers below */
858     ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%d", appname, (INT)hEvent);
859     if ((ret > -1) && (ret < sizeof(buffer)) &&
860         CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
861                        NULL, NULL, si, &pi))
862     {
863         if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
864
865         TRACE("Started wineconsole pid=%08lx tid=%08lx\n",
866               pi.dwProcessId, pi.dwThreadId);
867
868         return TRUE;
869     }
870     return FALSE;
871 }
872
873 static  BOOL    start_console_renderer(STARTUPINFOA* si)
874 {
875     HANDLE              hEvent = 0;
876     LPSTR               p;
877     OBJECT_ATTRIBUTES   attr;
878     BOOL                ret = FALSE;
879
880     attr.Length                   = sizeof(attr);
881     attr.RootDirectory            = 0;
882     attr.Attributes               = OBJ_INHERIT;
883     attr.ObjectName               = NULL;
884     attr.SecurityDescriptor       = NULL;
885     attr.SecurityQualityOfService = NULL;
886
887     NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
888     if (!hEvent) return FALSE;
889
890     /* first try environment variable */
891     if ((p = getenv("WINECONSOLE")) != NULL)
892     {
893         ret = start_console_renderer_helper(p, si, hEvent);
894         if (!ret)
895             ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
896                 "trying default access\n", p);
897     }
898
899     /* then try the regular PATH */
900     if (!ret)
901         ret = start_console_renderer_helper("wineconsole", si, hEvent);
902
903     CloseHandle(hEvent);
904     return ret;
905 }
906
907 /***********************************************************************
908  *            AllocConsole (KERNEL32.@)
909  *
910  * creates an xterm with a pty to our program
911  */
912 BOOL WINAPI AllocConsole(void)
913 {
914     HANDLE              handle_in = INVALID_HANDLE_VALUE;
915     HANDLE              handle_out = INVALID_HANDLE_VALUE;
916     HANDLE              handle_err = INVALID_HANDLE_VALUE;
917     STARTUPINFOA        siCurrent;
918     STARTUPINFOA        siConsole;
919     char                buffer[1024];
920
921     TRACE("()\n");
922
923     handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
924                              0, NULL, OPEN_EXISTING, 0, 0 );
925
926     if (handle_in != INVALID_HANDLE_VALUE)
927     {
928         /* we already have a console opened on this process, don't create a new one */
929         CloseHandle(handle_in);
930         return FALSE;
931     }
932
933     GetStartupInfoA(&siCurrent);
934
935     memset(&siConsole, 0, sizeof(siConsole));
936     siConsole.cb = sizeof(siConsole);
937     /* setup a view arguments for wineconsole (it'll use them as default values)  */
938     if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
939     {
940         siConsole.dwFlags |= STARTF_USECOUNTCHARS;
941         siConsole.dwXCountChars = siCurrent.dwXCountChars;
942         siConsole.dwYCountChars = siCurrent.dwYCountChars;
943     }
944     if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
945     {
946         siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
947         siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
948     }
949     /* FIXME (should pass the unicode form) */
950     if (siCurrent.lpTitle)
951         siConsole.lpTitle = siCurrent.lpTitle;
952     else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
953         siConsole.lpTitle = buffer;
954
955     if (!start_console_renderer(&siConsole))
956         goto the_end;
957
958     handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
959                              0, NULL, OPEN_EXISTING, 0, 0 );
960     if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
961
962     handle_out = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE,
963                              0, NULL, OPEN_EXISTING, 0, 0 );
964     if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
965
966     if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(), &handle_err,
967                          0, TRUE, DUPLICATE_SAME_ACCESS))
968         goto the_end;
969
970     /* NT resets the STD_*_HANDLEs on console alloc */
971     SetStdHandle(STD_INPUT_HANDLE,  handle_in);
972     SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
973     SetStdHandle(STD_ERROR_HANDLE,  handle_err);
974
975     SetLastError(ERROR_SUCCESS);
976
977     return TRUE;
978
979  the_end:
980     ERR("Can't allocate console\n");
981     if (handle_in != INVALID_HANDLE_VALUE)      CloseHandle(handle_in);
982     if (handle_out != INVALID_HANDLE_VALUE)     CloseHandle(handle_out);
983     if (handle_err != INVALID_HANDLE_VALUE)     CloseHandle(handle_err);
984     FreeConsole();
985     return FALSE;
986 }
987
988
989 /******************************************************************************
990  * read_console_input
991  *
992  * Helper function for ReadConsole, ReadConsoleInput and PeekConsoleInput
993  */
994 static BOOL read_console_input(HANDLE handle, LPINPUT_RECORD buffer, DWORD count,
995                                LPDWORD pRead, BOOL flush)
996 {
997     BOOL        ret;
998     unsigned    read = 0;
999
1000     SERVER_START_REQ( read_console_input )
1001     {
1002         req->handle = handle;
1003         req->flush = flush;
1004         wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1005         if ((ret = !wine_server_call_err( req ))) read = reply->read;
1006     }
1007     SERVER_END_REQ;
1008     if (pRead) *pRead = read;
1009     return ret;
1010 }
1011
1012
1013 /***********************************************************************
1014  *            ReadConsoleA   (KERNEL32.@)
1015  */
1016 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1017                          LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1018 {
1019     LPWSTR      ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1020     DWORD       ncr = 0;
1021     BOOL        ret;
1022
1023     if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1024         ncr = WideCharToMultiByte(CP_ACP, 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1025
1026     if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1027     HeapFree(GetProcessHeap(), 0, ptr);
1028
1029     return ret;
1030 }
1031
1032 /***********************************************************************
1033  *            ReadConsoleW   (KERNEL32.@)
1034  */
1035 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1036                          DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1037 {
1038     DWORD       charsread;
1039     LPWSTR      xbuf = (LPWSTR)lpBuffer;
1040     DWORD       mode;
1041
1042     TRACE("(%p,%p,%ld,%p,%p)\n",
1043           hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1044
1045     if (!GetConsoleMode(hConsoleInput, &mode))
1046         return FALSE;
1047
1048     if (mode & ENABLE_LINE_INPUT)
1049     {
1050         if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1051         {
1052             if (S_EditString) HeapFree(GetProcessHeap(), 0, S_EditString);
1053             if (!(S_EditString = CONSOLE_Readline(hConsoleInput, mode & WINE_ENABLE_LINE_INPUT_EMACS)))
1054                 return FALSE;
1055             S_EditStrPos = 0;
1056         }
1057         charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1058         if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1059         memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1060         S_EditStrPos += charsread;
1061     }
1062     else
1063     {
1064         INPUT_RECORD    ir;
1065         DWORD           count;
1066
1067         /* FIXME: should we read at least 1 char? The SDK does not say */
1068         /* wait for at least one available input record (it doesn't mean we'll have
1069          * chars stored in xbuf...
1070          */
1071         WaitForSingleObject(hConsoleInput, INFINITE);
1072         for (charsread = 0; charsread < nNumberOfCharsToRead;)
1073         {
1074             if (!read_console_input(hConsoleInput, &ir, 1, &count, TRUE)) return FALSE;
1075             if (count && ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1076                 ir.Event.KeyEvent.uChar.UnicodeChar &&
1077                 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
1078             {
1079                 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1080             }
1081         }
1082     }
1083
1084     if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1085
1086     return TRUE;
1087 }
1088
1089
1090 /***********************************************************************
1091  *            ReadConsoleInputW   (KERNEL32.@)
1092  */
1093 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, LPINPUT_RECORD lpBuffer,
1094                               DWORD nLength, LPDWORD lpNumberOfEventsRead)
1095 {
1096     DWORD count;
1097
1098     if (!nLength)
1099     {
1100         if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1101         return TRUE;
1102     }
1103
1104     /* loop until we get at least one event */
1105     for (;;)
1106     {
1107         WaitForSingleObject(hConsoleInput, INFINITE);
1108         if (!read_console_input(hConsoleInput, lpBuffer, nLength, &count, TRUE))
1109             return FALSE;
1110         if (count)
1111         {
1112             if (lpNumberOfEventsRead) *lpNumberOfEventsRead = count;
1113             return TRUE;
1114         }
1115     }
1116 }
1117
1118
1119 /******************************************************************************
1120  * WriteConsoleOutputCharacterW [KERNEL32.@]  Copies character to consecutive
1121  *                                            cells in the console screen buffer
1122  *
1123  * PARAMS
1124  *    hConsoleOutput    [I] Handle to screen buffer
1125  *    str               [I] Pointer to buffer with chars to write
1126  *    length            [I] Number of cells to write to
1127  *    coord             [I] Coords of first cell
1128  *    lpNumCharsWritten [O] Pointer to number of cells written
1129  *
1130  * RETURNS
1131  *    Success: TRUE
1132  *    Failure: FALSE
1133  *
1134  */
1135 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1136                                           COORD coord, LPDWORD lpNumCharsWritten )
1137 {
1138     BOOL ret;
1139
1140     TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
1141           debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1142
1143     SERVER_START_REQ( write_console_output )
1144     {
1145         req->handle = hConsoleOutput;
1146         req->x      = coord.X;
1147         req->y      = coord.Y;
1148         req->mode   = CHAR_INFO_MODE_TEXT;
1149         req->wrap   = TRUE;
1150         wine_server_add_data( req, str, length * sizeof(WCHAR) );
1151         if ((ret = !wine_server_call_err( req )))
1152         {
1153             if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1154         }
1155     }
1156     SERVER_END_REQ;
1157     return ret;
1158 }
1159
1160
1161 /******************************************************************************
1162  * SetConsoleTitleW [KERNEL32.@]  Sets title bar string for console
1163  *
1164  * PARAMS
1165  *    title [I] Address of new title
1166  *
1167  * RETURNS
1168  *    Success: TRUE
1169  *    Failure: FALSE
1170  */
1171 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1172 {
1173     BOOL ret;
1174
1175     SERVER_START_REQ( set_console_input_info )
1176     {
1177         req->handle = 0;
1178         req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1179         wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1180         ret = !wine_server_call_err( req );
1181     }
1182     SERVER_END_REQ;
1183     return ret;
1184 }
1185
1186
1187 /***********************************************************************
1188  *            GetNumberOfConsoleMouseButtons   (KERNEL32.@)
1189  */
1190 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1191 {
1192     FIXME("(%p): stub\n", nrofbuttons);
1193     *nrofbuttons = 2;
1194     return TRUE;
1195 }
1196
1197 /******************************************************************************
1198  *  SetConsoleInputExeNameW      [KERNEL32.@]
1199  *
1200  * BUGS
1201  *   Unimplemented
1202  */
1203 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1204 {
1205     FIXME("(%s): stub!\n", debugstr_w(name));
1206
1207     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1208     return TRUE;
1209 }
1210
1211 /******************************************************************************
1212  *  SetConsoleInputExeNameA      [KERNEL32.@]
1213  *
1214  * BUGS
1215  *   Unimplemented
1216  */
1217 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1218 {
1219     int         len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1220     LPWSTR      xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1221     BOOL        ret;
1222
1223     if (!xptr) return FALSE;
1224
1225     MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
1226     ret = SetConsoleInputExeNameW(xptr);
1227     HeapFree(GetProcessHeap(), 0, xptr);
1228
1229     return ret;
1230 }
1231
1232 /******************************************************************
1233  *              CONSOLE_DefaultHandler
1234  *
1235  * Final control event handler
1236  */
1237 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1238 {
1239     FIXME("Terminating process %lx on event %lx\n", GetCurrentProcessId(), dwCtrlType);
1240     ExitProcess(0);
1241     /* should never go here */
1242     return TRUE;
1243 }
1244
1245 /******************************************************************************
1246  * SetConsoleCtrlHandler [KERNEL32.@]  Adds function to calling process list
1247  *
1248  * PARAMS
1249  *    func [I] Address of handler function
1250  *    add  [I] Handler to add or remove
1251  *
1252  * RETURNS
1253  *    Success: TRUE
1254  *    Failure: FALSE
1255  *
1256  * CHANGED
1257  * James Sutherland (JamesSutherland@gmx.de)
1258  * Added global variables console_ignore_ctrl_c and handlers[]
1259  * Does not yet do any error checking, or set LastError if failed.
1260  * This doesn't yet matter, since these handlers are not yet called...!
1261  */
1262
1263 struct ConsoleHandler {
1264     PHANDLER_ROUTINE            handler;
1265     struct ConsoleHandler*      next;
1266 };
1267
1268 static unsigned int             CONSOLE_IgnoreCtrlC = 0; /* FIXME: this should be inherited somehow */
1269 static struct ConsoleHandler    CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1270 static struct ConsoleHandler*   CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1271 static CRITICAL_SECTION         CONSOLE_CritSect = CRITICAL_SECTION_INIT("console_ctrl_section");
1272
1273 /*****************************************************************************/
1274
1275 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1276 {
1277     BOOL        ret = TRUE;
1278
1279     FIXME("(%p,%i) - no error checking or testing yet\n", func, add);
1280
1281     if (!func)
1282     {
1283         CONSOLE_IgnoreCtrlC = add;
1284     }
1285     else if (add)
1286     {
1287         struct ConsoleHandler*  ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1288
1289         if (!ch) return FALSE;
1290         ch->handler = func;
1291         EnterCriticalSection(&CONSOLE_CritSect);
1292         ch->next = CONSOLE_Handlers;
1293         CONSOLE_Handlers = ch;
1294         LeaveCriticalSection(&CONSOLE_CritSect);
1295     }
1296     else
1297     {
1298         struct ConsoleHandler**  ch;
1299         EnterCriticalSection(&CONSOLE_CritSect);
1300         for (ch = &CONSOLE_Handlers; *ch; *ch = (*ch)->next)
1301         {
1302             if ((*ch)->handler == func) break;
1303         }
1304         if (*ch)
1305         {
1306             struct ConsoleHandler*   rch = *ch;
1307
1308             /* sanity check */
1309             if (rch == &CONSOLE_DefaultConsoleHandler)
1310             {
1311                 ERR("Who's trying to remove default handler???\n");
1312                 ret = FALSE;
1313             }
1314             else
1315             {
1316                 rch = *ch;
1317                 *ch = (*ch)->next;
1318                 HeapFree(GetProcessHeap(), 0, rch);
1319             }
1320         }
1321         else
1322         {
1323             WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1324             ret = FALSE;
1325         }
1326         LeaveCriticalSection(&CONSOLE_CritSect);
1327     }
1328     return ret;
1329 }
1330
1331 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
1332 {
1333     TRACE("(%lx)\n", GetExceptionCode());
1334     return EXCEPTION_EXECUTE_HANDLER;
1335 }
1336
1337 static DWORD WINAPI CONSOLE_HandleCtrlCEntry(void* pmt)
1338 {
1339     struct ConsoleHandler*  ch;
1340
1341     EnterCriticalSection(&CONSOLE_CritSect);
1342     /* the debugger didn't continue... so, pass to ctrl handlers */
1343     for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1344     {
1345         if (ch->handler((DWORD)pmt)) break;
1346     }
1347     LeaveCriticalSection(&CONSOLE_CritSect);
1348     return 0;
1349 }
1350
1351 /******************************************************************
1352  *              CONSOLE_HandleCtrlC
1353  *
1354  * Check whether the shall manipulate CtrlC events
1355  */
1356 int     CONSOLE_HandleCtrlC(unsigned sig)
1357 {
1358     /* FIXME: better test whether a console is attached to this process ??? */
1359     extern    unsigned CONSOLE_GetNumHistoryEntries(void);
1360     if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1361     if (CONSOLE_IgnoreCtrlC) return 1;
1362
1363     /* try to pass the exception to the debugger
1364      * if it continues, there's nothing more to do
1365      * otherwise, we need to send the ctrl-event to the handlers
1366      */
1367     __TRY
1368     {
1369         RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1370     }
1371     __EXCEPT(CONSOLE_CtrlEventHandler)
1372     {
1373         /* Create a separate thread to signal all the events. This would allow to
1374          * synchronize between setting the handlers and actually calling them
1375          */
1376         CreateThread(NULL, 0, CONSOLE_HandleCtrlCEntry, (void*)CTRL_C_EVENT, 0, NULL);
1377     }
1378     __ENDTRY;
1379     return 1;
1380 }
1381
1382 /******************************************************************************
1383  * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1384  *
1385  * PARAMS
1386  *    dwCtrlEvent        [I] Type of event
1387  *    dwProcessGroupID   [I] Process group ID to send event to
1388  *
1389  * RETURNS
1390  *    Success: True
1391  *    Failure: False (and *should* [but doesn't] set LastError)
1392  */
1393 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1394                                      DWORD dwProcessGroupID)
1395 {
1396     BOOL ret;
1397
1398     TRACE("(%ld, %ld)\n", dwCtrlEvent, dwProcessGroupID);
1399
1400     if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1401     {
1402         ERR("Invalid event %ld for PGID %ld\n", dwCtrlEvent, dwProcessGroupID);
1403         return FALSE;
1404     }
1405
1406     SERVER_START_REQ( send_console_signal )
1407     {
1408         req->signal = dwCtrlEvent;
1409         req->group_id = dwProcessGroupID;
1410         ret = !wine_server_call_err( req );
1411     }
1412     SERVER_END_REQ;
1413
1414     return ret;
1415 }
1416
1417
1418 /******************************************************************************
1419  * CreateConsoleScreenBuffer [KERNEL32.@]  Creates a console screen buffer
1420  *
1421  * PARAMS
1422  *    dwDesiredAccess    [I] Access flag
1423  *    dwShareMode        [I] Buffer share mode
1424  *    sa                 [I] Security attributes
1425  *    dwFlags            [I] Type of buffer to create
1426  *    lpScreenBufferData [I] Reserved
1427  *
1428  * NOTES
1429  *    Should call SetLastError
1430  *
1431  * RETURNS
1432  *    Success: Handle to new console screen buffer
1433  *    Failure: INVALID_HANDLE_VALUE
1434  */
1435 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1436                                         LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1437                                         LPVOID lpScreenBufferData)
1438 {
1439     HANDLE      ret = INVALID_HANDLE_VALUE;
1440
1441     TRACE("(%ld,%ld,%p,%ld,%p)\n",
1442           dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1443
1444     if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1445     {
1446         SetLastError(ERROR_INVALID_PARAMETER);
1447         return INVALID_HANDLE_VALUE;
1448     }
1449
1450     SERVER_START_REQ(create_console_output)
1451     {
1452         req->handle_in = 0;
1453         req->access    = dwDesiredAccess;
1454         req->share     = dwShareMode;
1455         req->inherit   = (sa && sa->bInheritHandle);
1456         if (!wine_server_call_err( req )) ret = reply->handle_out;
1457     }
1458     SERVER_END_REQ;
1459
1460     return ret;
1461 }
1462
1463
1464 /***********************************************************************
1465  *           GetConsoleScreenBufferInfo   (KERNEL32.@)
1466  */
1467 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1468 {
1469     BOOL        ret;
1470
1471     SERVER_START_REQ(get_console_output_info)
1472     {
1473         req->handle = hConsoleOutput;
1474         if ((ret = !wine_server_call_err( req )))
1475         {
1476             csbi->dwSize.X              = reply->width;
1477             csbi->dwSize.Y              = reply->height;
1478             csbi->dwCursorPosition.X    = reply->cursor_x;
1479             csbi->dwCursorPosition.Y    = reply->cursor_y;
1480             csbi->wAttributes           = reply->attr;
1481             csbi->srWindow.Left         = reply->win_left;
1482             csbi->srWindow.Right        = reply->win_right;
1483             csbi->srWindow.Top          = reply->win_top;
1484             csbi->srWindow.Bottom       = reply->win_bottom;
1485             csbi->dwMaximumWindowSize.X = reply->max_width;
1486             csbi->dwMaximumWindowSize.Y = reply->max_height;
1487         }
1488     }
1489     SERVER_END_REQ;
1490
1491     return ret;
1492 }
1493
1494
1495 /******************************************************************************
1496  * SetConsoleActiveScreenBuffer [KERNEL32.@]  Sets buffer to current console
1497  *
1498  * RETURNS
1499  *    Success: TRUE
1500  *    Failure: FALSE
1501  */
1502 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1503 {
1504     BOOL ret;
1505
1506     TRACE("(%p)\n", hConsoleOutput);
1507
1508     SERVER_START_REQ( set_console_input_info )
1509     {
1510         req->handle    = 0;
1511         req->mask      = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1512         req->active_sb = hConsoleOutput;
1513         ret = !wine_server_call_err( req );
1514     }
1515     SERVER_END_REQ;
1516     return ret;
1517 }
1518
1519
1520 /***********************************************************************
1521  *            GetConsoleMode   (KERNEL32.@)
1522  */
1523 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1524 {
1525     BOOL ret;
1526
1527     SERVER_START_REQ(get_console_mode)
1528     {
1529         req->handle = hcon;
1530         ret = !wine_server_call_err( req );
1531         if (ret && mode) *mode = reply->mode;
1532     }
1533     SERVER_END_REQ;
1534     return ret;
1535 }
1536
1537
1538 /******************************************************************************
1539  * SetConsoleMode [KERNEL32.@]  Sets input mode of console's input buffer
1540  *
1541  * PARAMS
1542  *    hcon [I] Handle to console input or screen buffer
1543  *    mode [I] Input or output mode to set
1544  *
1545  * RETURNS
1546  *    Success: TRUE
1547  *    Failure: FALSE
1548  *
1549  *    mode:
1550  *      ENABLE_PROCESSED_INPUT  0x01
1551  *      ENABLE_LINE_INPUT       0x02
1552  *      ENABLE_ECHO_INPUT       0x04
1553  *      ENABLE_WINDOW_INPUT     0x08
1554  *      ENABLE_MOUSE_INPUT      0x10
1555  */
1556 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1557 {
1558     BOOL ret;
1559
1560     SERVER_START_REQ(set_console_mode)
1561     {
1562         req->handle = hcon;
1563         req->mode = mode;
1564         ret = !wine_server_call_err( req );
1565     }
1566     SERVER_END_REQ;
1567     /* FIXME: when resetting a console input to editline mode, I think we should
1568      * empty the S_EditString buffer
1569      */
1570
1571     TRACE("(%p,%lx) retval == %d\n", hcon, mode, ret);
1572
1573     return ret;
1574 }
1575
1576
1577 /******************************************************************
1578  *              write_char
1579  *
1580  * WriteConsoleOutput helper: hides server call semantics
1581  */
1582 static int write_char(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1583 {
1584     int written = -1;
1585
1586     if (!nc) return 0;
1587
1588     SERVER_START_REQ( write_console_output )
1589     {
1590         req->handle = hCon;
1591         req->x      = pos->X;
1592         req->y      = pos->Y;
1593         req->mode   = CHAR_INFO_MODE_TEXTSTDATTR;
1594         req->wrap   = FALSE;
1595         wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1596         if (!wine_server_call_err( req )) written = reply->written;
1597     }
1598     SERVER_END_REQ;
1599
1600     if (written > 0) pos->X += written;
1601     return written;
1602 }
1603
1604 /******************************************************************
1605  *              next_line
1606  *
1607  * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1608  *
1609  */
1610 static int      next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1611 {
1612     SMALL_RECT  src;
1613     CHAR_INFO   ci;
1614     COORD       dst;
1615
1616     csbi->dwCursorPosition.X = 0;
1617     csbi->dwCursorPosition.Y++;
1618
1619     if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1620
1621     src.Top    = 1;
1622     src.Bottom = csbi->dwSize.Y - 1;
1623     src.Left   = 0;
1624     src.Right  = csbi->dwSize.X - 1;
1625
1626     dst.X      = 0;
1627     dst.Y      = 0;
1628
1629     ci.Attributes = csbi->wAttributes;
1630     ci.Char.UnicodeChar = ' ';
1631
1632     csbi->dwCursorPosition.Y--;
1633     if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1634         return 0;
1635     return 1;
1636 }
1637
1638 /******************************************************************
1639  *              write_block
1640  *
1641  * WriteConsoleOutput helper: writes a block of non special characters
1642  * Block can spread on several lines, and wrapping, if needed, is
1643  * handled
1644  *
1645  */
1646 static int      write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1647                             DWORD mode, LPWSTR ptr, int len)
1648 {
1649     int blk;    /* number of chars to write on current line */
1650
1651     if (len <= 0) return 1;
1652
1653     if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1654     {
1655         int     done;
1656
1657         for (done = 0; done < len; done += blk)
1658         {
1659             blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1660
1661             if (write_char(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1662                 return 0;
1663             if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
1664                 return 0;
1665         }
1666     }
1667     else
1668     {
1669         blk = min(len, csbi->dwSize.X - csbi->dwCursorPosition.X);
1670
1671         if (write_char(hCon, ptr, blk, &csbi->dwCursorPosition) != blk)
1672             return 0;
1673         if (blk < len)
1674         {
1675             csbi->dwCursorPosition.X = csbi->dwSize.X - 1;
1676             /* all remaining chars should be written on last column,
1677              * so only overwrite the last column with last char in block
1678              */
1679             if (write_char(hCon, ptr + len - 1, 1, &csbi->dwCursorPosition) != 1)
1680                 return 0;
1681             csbi->dwCursorPosition.X = csbi->dwSize.X - 1;
1682         }
1683     }
1684
1685     return 1;
1686 }
1687
1688 /***********************************************************************
1689  *            WriteConsoleW   (KERNEL32.@)
1690  */
1691 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1692                           LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1693 {
1694     DWORD                       mode;
1695     DWORD                       nw = 0;
1696     WCHAR*                      psz = (WCHAR*)lpBuffer;
1697     CONSOLE_SCREEN_BUFFER_INFO  csbi;
1698     int                         k, first = 0;
1699
1700     TRACE("%p %s %ld %p %p\n",
1701           hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
1702           nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
1703
1704     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1705
1706     if (!GetConsoleMode(hConsoleOutput, &mode) ||
1707         !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1708         return FALSE;
1709
1710     if (mode & ENABLE_PROCESSED_OUTPUT)
1711     {
1712         int     i;
1713
1714         for (i = 0; i < nNumberOfCharsToWrite; i++)
1715         {
1716             switch (psz[i])
1717             {
1718             case '\b': case '\t': case '\n': case '\a': case '\r':
1719                 /* don't handle here the i-th char... done below */
1720                 if ((k = i - first) > 0)
1721                 {
1722                     if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1723                         goto the_end;
1724                     nw += k;
1725                 }
1726                 first = i + 1;
1727                 nw++;
1728             }
1729             switch (psz[i])
1730             {
1731             case '\b':
1732                 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
1733                 break;
1734             case '\t':
1735                 {
1736                     WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
1737
1738                     if (!write_block(hConsoleOutput, &csbi, mode, tmp,
1739                                      ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
1740                         goto the_end;
1741                 }
1742                 break;
1743             case '\n':
1744                 next_line(hConsoleOutput, &csbi);
1745                 break;
1746             case '\a':
1747                 Beep(400, 300);
1748                 break;
1749             case '\r':
1750                 csbi.dwCursorPosition.X = 0;
1751                 break;
1752             default:
1753                 break;
1754             }
1755         }
1756     }
1757
1758     /* write the remaining block (if any) if processed output is enabled, or the
1759      * entire buffer otherwise
1760      */
1761     if ((k = nNumberOfCharsToWrite - first) > 0)
1762     {
1763         if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1764             goto the_end;
1765         nw += k;
1766     }
1767
1768  the_end:
1769     SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
1770     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
1771     return nw != 0;
1772 }
1773
1774
1775 /***********************************************************************
1776  *            WriteConsoleA   (KERNEL32.@)
1777  */
1778 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1779                           LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1780 {
1781     BOOL        ret;
1782     LPWSTR      xstring;
1783     DWORD       n;
1784
1785     n = MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
1786
1787     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1788     xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
1789     if (!xstring) return 0;
1790
1791     MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
1792
1793     ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
1794
1795     HeapFree(GetProcessHeap(), 0, xstring);
1796
1797     return ret;
1798 }
1799
1800 /******************************************************************************
1801  * SetConsoleCursorPosition [KERNEL32.@]
1802  * Sets the cursor position in console
1803  *
1804  * PARAMS
1805  *    hConsoleOutput   [I] Handle of console screen buffer
1806  *    dwCursorPosition [I] New cursor position coordinates
1807  *
1808  * RETURNS STD
1809  */
1810 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
1811 {
1812     BOOL                        ret;
1813     CONSOLE_SCREEN_BUFFER_INFO  csbi;
1814     int                         do_move = 0;
1815     int                         w, h;
1816
1817     TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
1818
1819     SERVER_START_REQ(set_console_output_info)
1820     {
1821         req->handle         = hcon;
1822         req->cursor_x       = pos.X;
1823         req->cursor_y       = pos.Y;
1824         req->mask           = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
1825         ret = !wine_server_call_err( req );
1826     }
1827     SERVER_END_REQ;
1828
1829     if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
1830         return FALSE;
1831
1832     /* if cursor is no longer visible, scroll the visible window... */
1833     w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
1834     h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1835     if (pos.X < csbi.srWindow.Left)
1836     {
1837         csbi.srWindow.Left   = min(pos.X, csbi.dwSize.X - w);
1838         do_move++;
1839     }
1840     else if (pos.X > csbi.srWindow.Right)
1841     {
1842         csbi.srWindow.Left   = max(pos.X, w) - w + 1;
1843         do_move++;
1844     }
1845     csbi.srWindow.Right  = csbi.srWindow.Left + w - 1;
1846
1847     if (pos.Y < csbi.srWindow.Top)
1848     {
1849         csbi.srWindow.Top    = min(pos.Y, csbi.dwSize.Y - h);
1850         do_move++;
1851     }
1852     else if (pos.Y > csbi.srWindow.Bottom)
1853     {
1854         csbi.srWindow.Top   = max(pos.Y, h) - h + 1;
1855         do_move++;
1856     }
1857     csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
1858
1859     ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
1860
1861     return ret;
1862 }
1863
1864 /******************************************************************************
1865  * GetConsoleCursorInfo [KERNEL32.@]  Gets size and visibility of console
1866  *
1867  * PARAMS
1868  *    hcon  [I] Handle to console screen buffer
1869  *    cinfo [O] Address of cursor information
1870  *
1871  * RETURNS
1872  *    Success: TRUE
1873  *    Failure: FALSE
1874  */
1875 BOOL WINAPI GetConsoleCursorInfo(HANDLE hcon, LPCONSOLE_CURSOR_INFO cinfo)
1876 {
1877     BOOL ret;
1878
1879     SERVER_START_REQ(get_console_output_info)
1880     {
1881         req->handle = hcon;
1882         ret = !wine_server_call_err( req );
1883         if (ret && cinfo)
1884         {
1885             cinfo->dwSize = reply->cursor_size;
1886             cinfo->bVisible = reply->cursor_visible;
1887         }
1888     }
1889     SERVER_END_REQ;
1890     return ret;
1891 }
1892
1893
1894 /******************************************************************************
1895  * SetConsoleCursorInfo [KERNEL32.@]  Sets size and visibility of cursor
1896  *
1897  * PARAMS
1898  *      hcon    [I] Handle to console screen buffer
1899  *      cinfo   [I] Address of cursor information
1900  * RETURNS
1901  *    Success: TRUE
1902  *    Failure: FALSE
1903  */
1904 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
1905 {
1906     BOOL ret;
1907
1908     SERVER_START_REQ(set_console_output_info)
1909     {
1910         req->handle         = hCon;
1911         req->cursor_size    = cinfo->dwSize;
1912         req->cursor_visible = cinfo->bVisible;
1913         req->mask           = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
1914         ret = !wine_server_call_err( req );
1915     }
1916     SERVER_END_REQ;
1917     return ret;
1918 }
1919
1920
1921 /******************************************************************************
1922  * SetConsoleWindowInfo [KERNEL32.@]  Sets size and position of console
1923  *
1924  * PARAMS
1925  *      hcon            [I] Handle to console screen buffer
1926  *      bAbsolute       [I] Coordinate type flag
1927  *      window          [I] Address of new window rectangle
1928  * RETURNS
1929  *    Success: TRUE
1930  *    Failure: FALSE
1931  */
1932 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
1933 {
1934     SMALL_RECT  p = *window;
1935     BOOL        ret;
1936
1937     if (!bAbsolute)
1938     {
1939         CONSOLE_SCREEN_BUFFER_INFO      csbi;
1940         if (!GetConsoleScreenBufferInfo(hCon, &csbi))
1941             return FALSE;
1942         p.Left   += csbi.srWindow.Left;
1943         p.Top    += csbi.srWindow.Top;
1944         p.Right  += csbi.srWindow.Left;
1945         p.Bottom += csbi.srWindow.Top;
1946     }
1947     SERVER_START_REQ(set_console_output_info)
1948     {
1949         req->handle         = hCon;
1950         req->win_left       = p.Left;
1951         req->win_top        = p.Top;
1952         req->win_right      = p.Right;
1953         req->win_bottom     = p.Bottom;
1954         req->mask           = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
1955         ret = !wine_server_call_err( req );
1956     }
1957     SERVER_END_REQ;
1958
1959     return ret;
1960 }
1961
1962
1963 /******************************************************************************
1964  * SetConsoleTextAttribute [KERNEL32.@]  Sets colors for text
1965  *
1966  * Sets the foreground and background color attributes of characters
1967  * written to the screen buffer.
1968  *
1969  * RETURNS
1970  *    Success: TRUE
1971  *    Failure: FALSE
1972  */
1973 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
1974 {
1975     BOOL ret;
1976
1977     SERVER_START_REQ(set_console_output_info)
1978     {
1979         req->handle = hConsoleOutput;
1980         req->attr   = wAttr;
1981         req->mask   = SET_CONSOLE_OUTPUT_INFO_ATTR;
1982         ret = !wine_server_call_err( req );
1983     }
1984     SERVER_END_REQ;
1985     return ret;
1986 }
1987
1988
1989 /******************************************************************************
1990  * SetConsoleScreenBufferSize [KERNEL32.@]  Changes size of console
1991  *
1992  * PARAMS
1993  *    hConsoleOutput [I] Handle to console screen buffer
1994  *    dwSize         [I] New size in character rows and cols
1995  *
1996  * RETURNS
1997  *    Success: TRUE
1998  *    Failure: FALSE
1999  */
2000 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2001 {
2002     BOOL ret;
2003
2004     SERVER_START_REQ(set_console_output_info)
2005     {
2006         req->handle = hConsoleOutput;
2007         req->width  = dwSize.X;
2008         req->height = dwSize.Y;
2009         req->mask   = SET_CONSOLE_OUTPUT_INFO_SIZE;
2010         ret = !wine_server_call_err( req );
2011     }
2012     SERVER_END_REQ;
2013     return ret;
2014 }
2015
2016
2017 /******************************************************************************
2018  * ScrollConsoleScreenBufferA [KERNEL32.@]
2019  *
2020  */
2021 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2022                                        LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2023                                        LPCHAR_INFO lpFill)
2024 {
2025     CHAR_INFO   ciw;
2026
2027     ciw.Attributes = lpFill->Attributes;
2028     MultiByteToWideChar(CP_ACP, 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2029
2030     return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2031                                       dwDestOrigin, &ciw);
2032 }
2033
2034 /******************************************************************
2035  *              CONSOLE_FillLineUniform
2036  *
2037  * Helper function for ScrollConsoleScreenBufferW
2038  * Fills a part of a line with a constant character info
2039  */
2040 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2041 {
2042     SERVER_START_REQ( fill_console_output )
2043     {
2044         req->handle    = hConsoleOutput;
2045         req->mode      = CHAR_INFO_MODE_TEXTATTR;
2046         req->x         = i;
2047         req->y         = j;
2048         req->count     = len;
2049         req->wrap      = FALSE;
2050         req->data.ch   = lpFill->Char.UnicodeChar;
2051         req->data.attr = lpFill->Attributes;
2052         wine_server_call_err( req );
2053     }
2054     SERVER_END_REQ;
2055 }
2056
2057 /******************************************************************************
2058  * ScrollConsoleScreenBufferW [KERNEL32.@]
2059  *
2060  */
2061
2062 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2063                                        LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2064                                        LPCHAR_INFO lpFill)
2065 {
2066     SMALL_RECT                  dst;
2067     DWORD                       ret;
2068     int                         i, j;
2069     int                         start = -1;
2070     SMALL_RECT                  clip;
2071     CONSOLE_SCREEN_BUFFER_INFO  csbi;
2072     BOOL                        inside;
2073
2074     if (lpClipRect)
2075         TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2076               lpScrollRect->Left, lpScrollRect->Top,
2077               lpScrollRect->Right, lpScrollRect->Bottom,
2078               lpClipRect->Left, lpClipRect->Top,
2079               lpClipRect->Right, lpClipRect->Bottom,
2080               dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2081     else
2082         TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2083               lpScrollRect->Left, lpScrollRect->Top,
2084               lpScrollRect->Right, lpScrollRect->Bottom,
2085               dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2086
2087     if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2088         return FALSE;
2089
2090     /* step 1: get dst rect */
2091     dst.Left = dwDestOrigin.X;
2092     dst.Top = dwDestOrigin.Y;
2093     dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2094     dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2095
2096     /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2097     if (lpClipRect)
2098     {
2099         clip.Left   = max(0, lpClipRect->Left);
2100         clip.Right  = min(csbi.dwSize.X - 1, lpClipRect->Right);
2101         clip.Top    = max(0, lpClipRect->Top);
2102         clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2103     }
2104     else
2105     {
2106         clip.Left   = 0;
2107         clip.Right  = csbi.dwSize.X - 1;
2108         clip.Top    = 0;
2109         clip.Bottom = csbi.dwSize.Y - 1;
2110     }
2111     if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2112
2113     /* step 2b: clip dst rect */
2114     if (dst.Left   < clip.Left  ) dst.Left   = clip.Left;
2115     if (dst.Top    < clip.Top   ) dst.Top    = clip.Top;
2116     if (dst.Right  > clip.Right ) dst.Right  = clip.Right;
2117     if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2118
2119     /* step 3: transfer the bits */
2120     SERVER_START_REQ(move_console_output)
2121     {
2122         req->handle = hConsoleOutput;
2123         req->x_src = lpScrollRect->Left;
2124         req->y_src = lpScrollRect->Top;
2125         req->x_dst = dst.Left;
2126         req->y_dst = dst.Top;
2127         req->w = dst.Right - dst.Left + 1;
2128         req->h = dst.Bottom - dst.Top + 1;
2129         ret = !wine_server_call_err( req );
2130     }
2131     SERVER_END_REQ;
2132
2133     if (!ret) return FALSE;
2134
2135     /* step 4: clean out the exposed part */
2136
2137     /* have to write cell [i,j] if it is not in dst rect (because it has already
2138      * been written to by the scroll) and is in clip (we shall not write
2139      * outside of clip)
2140      */
2141     for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2142     {
2143         inside = dst.Top <= j && j <= dst.Bottom;
2144         start = -1;
2145         for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2146         {
2147             if (inside && dst.Left <= i && i <= dst.Right)
2148             {
2149                 if (start != -1)
2150                 {
2151                     CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2152                     start = -1;
2153                 }
2154             }
2155             else
2156             {
2157                 if (start == -1) start = i;
2158             }
2159         }
2160         if (start != -1)
2161             CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2162     }
2163
2164     return TRUE;
2165 }
2166
2167
2168 /* ====================================================================
2169  *
2170  * Console manipulation functions
2171  *
2172  * ====================================================================*/
2173
2174 /* some missing functions...
2175  * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2176  * should get the right API and implement them
2177  *      GetConsoleCommandHistory[AW] (dword dword dword)
2178  *      GetConsoleCommandHistoryLength[AW]
2179  *      SetConsoleCommandHistoryMode
2180  *      SetConsoleNumberOfCommands[AW]
2181  */
2182 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2183 {
2184     int len = 0;
2185
2186     SERVER_START_REQ( get_console_input_history )
2187     {
2188         req->handle = 0;
2189         req->index = idx;
2190         if (buf && buf_len > 1)
2191         {
2192             wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2193         }
2194         if (!wine_server_call_err( req ))
2195         {
2196             if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2197             len = reply->total / sizeof(WCHAR) + 1;
2198         }
2199     }
2200     SERVER_END_REQ;
2201     return len;
2202 }
2203
2204 /******************************************************************
2205  *              CONSOLE_AppendHistory
2206  *
2207  *
2208  */
2209 BOOL    CONSOLE_AppendHistory(const WCHAR* ptr)
2210 {
2211     size_t      len = strlenW(ptr);
2212     BOOL        ret;
2213
2214     while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2215
2216     SERVER_START_REQ( append_console_input_history )
2217     {
2218         req->handle = 0;
2219         wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2220         ret = !wine_server_call_err( req );
2221     }
2222     SERVER_END_REQ;
2223     return ret;
2224 }
2225
2226 /******************************************************************
2227  *              CONSOLE_GetNumHistoryEntries
2228  *
2229  *
2230  */
2231 unsigned CONSOLE_GetNumHistoryEntries(void)
2232 {
2233     unsigned ret = -1;
2234     SERVER_START_REQ(get_console_input_info)
2235     {
2236         req->handle = 0;
2237         if (!wine_server_call_err( req )) ret = reply->history_index;
2238     }
2239     SERVER_END_REQ;
2240     return ret;
2241 }