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