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