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