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