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