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