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