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