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