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