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