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