oleaut32: Remove unnecessary check for NULL.
[wine] / dlls / kernel / console.c
1 /*
2  * Win32 console functions
3  *
4  * Copyright 1995 Martin von Loewis and Cameron Heide
5  * Copyright 1997 Karl Garrison
6  * Copyright 1998 John Richardson
7  * Copyright 1998 Marcus Meissner
8  * Copyright 2001,2002,2004,2005 Eric Pouech
9  * Copyright 2001 Alexandre Julliard
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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
42 #include "windef.h"
43 #include "winbase.h"
44 #include "winnls.h"
45 #include "winerror.h"
46 #include "wincon.h"
47 #include "wine/winbase16.h"
48 #include "wine/server.h"
49 #include "wine/exception.h"
50 #include "wine/unicode.h"
51 #include "wine/debug.h"
52 #include "excpt.h"
53 #include "console_private.h"
54 #include "kernel_private.h"
55
56 WINE_DEFAULT_DEBUG_CHANNEL(console);
57
58 static UINT console_input_codepage;
59 static UINT console_output_codepage;
60
61 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
62 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
63
64 /* map input records to ASCII */
65 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
66 {
67     int i;
68     char ch;
69
70     for (i = 0; i < count; i++)
71     {
72         if (buffer[i].EventType != KEY_EVENT) continue;
73         WideCharToMultiByte( GetConsoleCP(), 0,
74                              &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
75         buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
76     }
77 }
78
79 /* map input records to Unicode */
80 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
81 {
82     int i;
83     WCHAR ch;
84
85     for (i = 0; i < count; i++)
86     {
87         if (buffer[i].EventType != KEY_EVENT) continue;
88         MultiByteToWideChar( GetConsoleCP(), 0,
89                              &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
90         buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
91     }
92 }
93
94 /* map char infos to ASCII */
95 static void char_info_WtoA( CHAR_INFO *buffer, int count )
96 {
97     char ch;
98
99     while (count-- > 0)
100     {
101         WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
102                              &ch, 1, NULL, NULL );
103         buffer->Char.AsciiChar = ch;
104         buffer++;
105     }
106 }
107
108 /* map char infos to Unicode */
109 static void char_info_AtoW( CHAR_INFO *buffer, int count )
110 {
111     WCHAR ch;
112
113     while (count-- > 0)
114     {
115         MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
116         buffer->Char.UnicodeChar = ch;
117         buffer++;
118     }
119 }
120
121
122 /******************************************************************************
123  * GetConsoleWindow [KERNEL32.@]
124  */
125 HWND WINAPI GetConsoleWindow(VOID)
126 {
127     FIXME("stub\n");
128     return NULL;
129 }
130
131
132 /******************************************************************************
133  * GetConsoleCP [KERNEL32.@]  Returns the OEM code page for the console
134  *
135  * RETURNS
136  *    Code page code
137  */
138 UINT WINAPI GetConsoleCP(VOID)
139 {
140     if (!console_input_codepage) 
141     {
142         console_input_codepage = GetOEMCP();
143         TRACE("%u\n", console_input_codepage);
144     }
145     return console_input_codepage;
146 }
147
148
149 /******************************************************************************
150  *  SetConsoleCP         [KERNEL32.@]
151  */
152 BOOL WINAPI SetConsoleCP(UINT cp)
153 {
154     if (!IsValidCodePage( cp )) return FALSE;
155     console_input_codepage = cp;
156     return TRUE;
157 }
158
159
160 /***********************************************************************
161  *            GetConsoleOutputCP   (KERNEL32.@)
162  */
163 UINT WINAPI GetConsoleOutputCP(VOID)
164 {
165     if (!console_output_codepage)
166     {
167         console_output_codepage = GetOEMCP();
168         TRACE("%u\n", console_output_codepage);
169     }
170     return console_output_codepage;
171 }
172
173
174 /******************************************************************************
175  * SetConsoleOutputCP [KERNEL32.@]  Set the output codepage used by the console
176  *
177  * PARAMS
178  *    cp [I] code page to set
179  *
180  * RETURNS
181  *    Success: TRUE
182  *    Failure: FALSE
183  */
184 BOOL WINAPI SetConsoleOutputCP(UINT cp)
185 {
186     if (!IsValidCodePage( cp )) return FALSE;
187     console_output_codepage = cp;
188     return TRUE;
189 }
190
191
192 /***********************************************************************
193  *           Beep   (KERNEL32.@)
194  */
195 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
196 {
197     static const char beep = '\a';
198     /* dwFreq and dwDur are ignored by Win95 */
199     if (isatty(2)) write( 2, &beep, 1 );
200     return TRUE;
201 }
202
203
204 /******************************************************************
205  *              OpenConsoleW            (KERNEL32.@)
206  *
207  * Undocumented
208  *      Open a handle to the current process console.
209  *      Returns INVALID_HANDLE_VALUE on failure.
210  */
211 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
212 {
213     BOOL        output;
214     HANDLE      ret;
215
216     if (strcmpiW(coninW, name) == 0) 
217         output = FALSE;
218     else if (strcmpiW(conoutW, name) == 0) 
219         output = TRUE;
220     else
221     {
222         SetLastError(ERROR_INVALID_NAME);
223         return INVALID_HANDLE_VALUE;
224     }
225     if (creation != OPEN_EXISTING)
226     {
227         SetLastError(ERROR_INVALID_PARAMETER);
228         return INVALID_HANDLE_VALUE;
229     }
230
231     SERVER_START_REQ( open_console )
232     {
233         req->from       = output;
234         req->access     = access;
235         req->attributes = inherit ? OBJ_INHERIT : 0;
236         req->share      = FILE_SHARE_READ | FILE_SHARE_WRITE;
237         SetLastError(0);
238         wine_server_call_err( req );
239         ret = reply->handle;
240     }
241     SERVER_END_REQ;
242     if (ret)
243         ret = console_handle_map(ret);
244     else
245     {
246         /* likely, we're not attached to wineconsole
247          * let's try to return a handle to the unix-console
248          */
249         int fd = open("/dev/tty", output ? O_WRONLY : O_RDONLY);
250         ret = INVALID_HANDLE_VALUE;
251         if (fd != -1)
252         {
253             DWORD access = (output ? GENERIC_WRITE : GENERIC_READ) | SYNCHRONIZE;
254             wine_server_fd_to_handle(fd, access, inherit ? OBJ_INHERIT : 0, &ret);
255             close(fd);
256         }
257     }
258     return ret;
259 }
260
261 /******************************************************************
262  *              VerifyConsoleIoHandle            (KERNEL32.@)
263  *
264  * Undocumented
265  */
266 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
267 {
268     BOOL ret;
269
270     if (!is_console_handle(handle)) return FALSE;
271     SERVER_START_REQ(get_console_mode)
272     {
273         req->handle = console_handle_unmap(handle);
274         ret = !wine_server_call_err( req );
275     }
276     SERVER_END_REQ;
277     return ret;
278 }
279
280 /******************************************************************
281  *              DuplicateConsoleHandle            (KERNEL32.@)
282  *
283  * Undocumented
284  */
285 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
286                                      DWORD options)
287 {
288     HANDLE      ret;
289
290     if (!is_console_handle(handle) ||
291         !DuplicateHandle(GetCurrentProcess(), console_handle_unmap(handle), 
292                          GetCurrentProcess(), &ret, access, inherit, options))
293         return INVALID_HANDLE_VALUE;
294     return console_handle_map(ret);
295 }
296
297 /******************************************************************
298  *              CloseConsoleHandle            (KERNEL32.@)
299  *
300  * Undocumented
301  */
302 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
303 {
304     if (!is_console_handle(handle)) 
305     {
306         SetLastError(ERROR_INVALID_PARAMETER);
307         return FALSE;
308     }
309     return CloseHandle(console_handle_unmap(handle));
310 }
311
312 /******************************************************************
313  *              GetConsoleInputWaitHandle            (KERNEL32.@)
314  *
315  * Undocumented
316  */
317 HANDLE WINAPI GetConsoleInputWaitHandle(void)
318 {
319     static HANDLE console_wait_event;
320  
321     /* FIXME: this is not thread safe */
322     if (!console_wait_event)
323     {
324         SERVER_START_REQ(get_console_wait_event)
325         {
326             if (!wine_server_call_err( req )) console_wait_event = reply->handle;
327         }
328         SERVER_END_REQ;
329     }
330     return console_wait_event;
331 }
332
333
334 /******************************************************************************
335  * WriteConsoleInputA [KERNEL32.@]
336  */
337 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
338                                 DWORD count, LPDWORD written )
339 {
340     INPUT_RECORD *recW;
341     BOOL ret;
342
343     if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
344     memcpy( recW, buffer, count*sizeof(*recW) );
345     input_records_AtoW( recW, count );
346     ret = WriteConsoleInputW( handle, recW, count, written );
347     HeapFree( GetProcessHeap(), 0, recW );
348     return ret;
349 }
350
351
352 /******************************************************************************
353  * WriteConsoleInputW [KERNEL32.@]
354  */
355 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
356                                 DWORD count, LPDWORD written )
357 {
358     BOOL ret;
359
360     TRACE("(%p,%p,%ld,%p)\n", handle, buffer, count, written);
361
362     if (written) *written = 0;
363     SERVER_START_REQ( write_console_input )
364     {
365         req->handle = console_handle_unmap(handle);
366         wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
367         if ((ret = !wine_server_call_err( req )) && written)
368             *written = reply->written;
369     }
370     SERVER_END_REQ;
371
372     return ret;
373 }
374
375
376 /***********************************************************************
377  *            WriteConsoleOutputA   (KERNEL32.@)
378  */
379 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
380                                  COORD size, COORD coord, LPSMALL_RECT region )
381 {
382     int y;
383     BOOL ret;
384     COORD new_size, new_coord;
385     CHAR_INFO *ciw;
386
387     new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
388     new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
389
390     if (new_size.X <= 0 || new_size.Y <= 0)
391     {
392         region->Bottom = region->Top + new_size.Y - 1;
393         region->Right = region->Left + new_size.X - 1;
394         return TRUE;
395     }
396
397     /* only copy the useful rectangle */
398     if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
399         return FALSE;
400     for (y = 0; y < new_size.Y; y++)
401     {
402         memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
403                 new_size.X * sizeof(CHAR_INFO) );
404         char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
405     }
406     new_coord.X = new_coord.Y = 0;
407     ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
408     HeapFree( GetProcessHeap(), 0, ciw );
409     return ret;
410 }
411
412
413 /***********************************************************************
414  *            WriteConsoleOutputW   (KERNEL32.@)
415  */
416 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
417                                  COORD size, COORD coord, LPSMALL_RECT region )
418 {
419     int width, height, y;
420     BOOL ret = TRUE;
421
422     TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
423           hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
424           region->Left, region->Top, region->Right, region->Bottom);
425
426     width = min( region->Right - region->Left + 1, size.X - coord.X );
427     height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
428
429     if (width > 0 && height > 0)
430     {
431         for (y = 0; y < height; y++)
432         {
433             SERVER_START_REQ( write_console_output )
434             {
435                 req->handle = console_handle_unmap(hConsoleOutput);
436                 req->x      = region->Left;
437                 req->y      = region->Top + y;
438                 req->mode   = CHAR_INFO_MODE_TEXTATTR;
439                 req->wrap   = FALSE;
440                 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
441                                       width * sizeof(CHAR_INFO));
442                 if ((ret = !wine_server_call_err( req )))
443                 {
444                     width  = min( width, reply->width - region->Left );
445                     height = min( height, reply->height - region->Top );
446                 }
447             }
448             SERVER_END_REQ;
449             if (!ret) break;
450         }
451     }
452     region->Bottom = region->Top + height - 1;
453     region->Right = region->Left + width - 1;
454     return ret;
455 }
456
457
458 /******************************************************************************
459  * WriteConsoleOutputCharacterA [KERNEL32.@]
460  *
461  * See WriteConsoleOutputCharacterW.
462  */
463 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
464                                           COORD coord, LPDWORD lpNumCharsWritten )
465 {
466     BOOL ret;
467     LPWSTR strW;
468     DWORD lenW;
469
470     TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
471           debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
472
473     lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
474
475     if (lpNumCharsWritten) *lpNumCharsWritten = 0;
476
477     if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
478     MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
479
480     ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
481     HeapFree( GetProcessHeap(), 0, strW );
482     return ret;
483 }
484
485
486 /******************************************************************************
487  * WriteConsoleOutputAttribute [KERNEL32.@]  Sets attributes for some cells in
488  *                                           the console screen buffer
489  *
490  * PARAMS
491  *    hConsoleOutput    [I] Handle to screen buffer
492  *    attr              [I] Pointer to buffer with write attributes
493  *    length            [I] Number of cells to write to
494  *    coord             [I] Coords of first cell
495  *    lpNumAttrsWritten [O] Pointer to number of cells written
496  *
497  * RETURNS
498  *    Success: TRUE
499  *    Failure: FALSE
500  *
501  */
502 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
503                                          COORD coord, LPDWORD lpNumAttrsWritten )
504 {
505     BOOL ret;
506
507     TRACE("(%p,%p,%ld,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
508
509     SERVER_START_REQ( write_console_output )
510     {
511         req->handle = console_handle_unmap(hConsoleOutput);
512         req->x      = coord.X;
513         req->y      = coord.Y;
514         req->mode   = CHAR_INFO_MODE_ATTR;
515         req->wrap   = TRUE;
516         wine_server_add_data( req, attr, length * sizeof(WORD) );
517         if ((ret = !wine_server_call_err( req )))
518         {
519             if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
520         }
521     }
522     SERVER_END_REQ;
523     return ret;
524 }
525
526
527 /******************************************************************************
528  * FillConsoleOutputCharacterA [KERNEL32.@]
529  *
530  * See FillConsoleOutputCharacterW.
531  */
532 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
533                                          COORD coord, LPDWORD lpNumCharsWritten )
534 {
535     WCHAR wch;
536
537     MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
538     return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
539 }
540
541
542 /******************************************************************************
543  * FillConsoleOutputCharacterW [KERNEL32.@]  Writes characters to console
544  *
545  * PARAMS
546  *    hConsoleOutput    [I] Handle to screen buffer
547  *    ch                [I] Character to write
548  *    length            [I] Number of cells to write to
549  *    coord             [I] Coords of first cell
550  *    lpNumCharsWritten [O] Pointer to number of cells written
551  *
552  * RETURNS
553  *    Success: TRUE
554  *    Failure: FALSE
555  */
556 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
557                                          COORD coord, LPDWORD lpNumCharsWritten)
558 {
559     BOOL ret;
560
561     TRACE("(%p,%s,%ld,(%dx%d),%p)\n",
562           hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
563
564     SERVER_START_REQ( fill_console_output )
565     {
566         req->handle  = console_handle_unmap(hConsoleOutput);
567         req->x       = coord.X;
568         req->y       = coord.Y;
569         req->mode    = CHAR_INFO_MODE_TEXT;
570         req->wrap    = TRUE;
571         req->data.ch = ch;
572         req->count   = length;
573         if ((ret = !wine_server_call_err( req )))
574         {
575             if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
576         }
577     }
578     SERVER_END_REQ;
579     return ret;
580 }
581
582
583 /******************************************************************************
584  * FillConsoleOutputAttribute [KERNEL32.@]  Sets attributes for console
585  *
586  * PARAMS
587  *    hConsoleOutput    [I] Handle to screen buffer
588  *    attr              [I] Color attribute to write
589  *    length            [I] Number of cells to write to
590  *    coord             [I] Coords of first cell
591  *    lpNumAttrsWritten [O] Pointer to number of cells written
592  *
593  * RETURNS
594  *    Success: TRUE
595  *    Failure: FALSE
596  */
597 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
598                                         COORD coord, LPDWORD lpNumAttrsWritten )
599 {
600     BOOL ret;
601
602     TRACE("(%p,%d,%ld,(%dx%d),%p)\n",
603           hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
604
605     SERVER_START_REQ( fill_console_output )
606     {
607         req->handle    = console_handle_unmap(hConsoleOutput);
608         req->x         = coord.X;
609         req->y         = coord.Y;
610         req->mode      = CHAR_INFO_MODE_ATTR;
611         req->wrap      = TRUE;
612         req->data.attr = attr;
613         req->count     = length;
614         if ((ret = !wine_server_call_err( req )))
615         {
616             if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
617         }
618     }
619     SERVER_END_REQ;
620     return ret;
621 }
622
623
624 /******************************************************************************
625  * ReadConsoleOutputCharacterA [KERNEL32.@]
626  *
627  */
628 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
629                                         COORD coord, LPDWORD read_count)
630 {
631     DWORD read;
632     BOOL ret;
633     LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
634
635     if (read_count) *read_count = 0;
636     if (!wptr) return FALSE;
637
638     if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
639     {
640         read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
641         if (read_count) *read_count = read;
642     }
643     HeapFree( GetProcessHeap(), 0, wptr );
644     return ret;
645 }
646
647
648 /******************************************************************************
649  * ReadConsoleOutputCharacterW [KERNEL32.@]
650  *
651  */
652 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
653                                          COORD coord, LPDWORD read_count )
654 {
655     BOOL ret;
656
657     TRACE( "(%p,%p,%ld,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
658
659     SERVER_START_REQ( read_console_output )
660     {
661         req->handle = console_handle_unmap(hConsoleOutput);
662         req->x      = coord.X;
663         req->y      = coord.Y;
664         req->mode   = CHAR_INFO_MODE_TEXT;
665         req->wrap   = TRUE;
666         wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
667         if ((ret = !wine_server_call_err( req )))
668         {
669             if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
670         }
671     }
672     SERVER_END_REQ;
673     return ret;
674 }
675
676
677 /******************************************************************************
678  *  ReadConsoleOutputAttribute [KERNEL32.@]
679  */
680 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
681                                        COORD coord, LPDWORD read_count)
682 {
683     BOOL ret;
684
685     TRACE("(%p,%p,%ld,%dx%d,%p)\n",
686           hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
687
688     SERVER_START_REQ( read_console_output )
689     {
690         req->handle = console_handle_unmap(hConsoleOutput);
691         req->x      = coord.X;
692         req->y      = coord.Y;
693         req->mode   = CHAR_INFO_MODE_ATTR;
694         req->wrap   = TRUE;
695         wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
696         if ((ret = !wine_server_call_err( req )))
697         {
698             if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
699         }
700     }
701     SERVER_END_REQ;
702     return ret;
703 }
704
705
706 /******************************************************************************
707  *  ReadConsoleOutputA [KERNEL32.@]
708  *
709  */
710 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
711                                 COORD coord, LPSMALL_RECT region )
712 {
713     BOOL ret;
714     int y;
715
716     ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
717     if (ret && region->Right >= region->Left)
718     {
719         for (y = 0; y <= region->Bottom - region->Top; y++)
720         {
721             char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
722                             region->Right - region->Left + 1 );
723         }
724     }
725     return ret;
726 }
727
728
729 /******************************************************************************
730  *  ReadConsoleOutputW [KERNEL32.@]
731  *
732  * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
733  * think we need to be *that* compatible.  -- AJ
734  */
735 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
736                                 COORD coord, LPSMALL_RECT region )
737 {
738     int width, height, y;
739     BOOL ret = TRUE;
740
741     width = min( region->Right - region->Left + 1, size.X - coord.X );
742     height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
743
744     if (width > 0 && height > 0)
745     {
746         for (y = 0; y < height; y++)
747         {
748             SERVER_START_REQ( read_console_output )
749             {
750                 req->handle = console_handle_unmap(hConsoleOutput);
751                 req->x      = region->Left;
752                 req->y      = region->Top + y;
753                 req->mode   = CHAR_INFO_MODE_TEXTATTR;
754                 req->wrap   = FALSE;
755                 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
756                                        width * sizeof(CHAR_INFO) );
757                 if ((ret = !wine_server_call_err( req )))
758                 {
759                     width  = min( width, reply->width - region->Left );
760                     height = min( height, reply->height - region->Top );
761                 }
762             }
763             SERVER_END_REQ;
764             if (!ret) break;
765         }
766     }
767     region->Bottom = region->Top + height - 1;
768     region->Right = region->Left + width - 1;
769     return ret;
770 }
771
772
773 /******************************************************************************
774  * ReadConsoleInputA [KERNEL32.@]  Reads data from a console
775  *
776  * PARAMS
777  *    handle   [I] Handle to console input buffer
778  *    buffer   [O] Address of buffer for read data
779  *    count    [I] Number of records to read
780  *    pRead    [O] Address of number of records read
781  *
782  * RETURNS
783  *    Success: TRUE
784  *    Failure: FALSE
785  */
786 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
787 {
788     DWORD read;
789
790     if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
791     input_records_WtoA( buffer, read );
792     if (pRead) *pRead = read;
793     return TRUE;
794 }
795
796
797 /***********************************************************************
798  *            PeekConsoleInputA   (KERNEL32.@)
799  *
800  * Gets 'count' first events (or less) from input queue.
801  */
802 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
803 {
804     DWORD read;
805
806     if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
807     input_records_WtoA( buffer, read );
808     if (pRead) *pRead = read;
809     return TRUE;
810 }
811
812
813 /***********************************************************************
814  *            PeekConsoleInputW   (KERNEL32.@)
815  */
816 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
817 {
818     BOOL ret;
819     SERVER_START_REQ( read_console_input )
820     {
821         req->handle = console_handle_unmap(handle);
822         req->flush  = FALSE;
823         wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
824         if ((ret = !wine_server_call_err( req )))
825         {
826             if (read) *read = count ? reply->read : 0;
827         }
828     }
829     SERVER_END_REQ;
830     return ret;
831 }
832
833
834 /***********************************************************************
835  *            GetNumberOfConsoleInputEvents   (KERNEL32.@)
836  */
837 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
838 {
839     BOOL ret;
840     SERVER_START_REQ( read_console_input )
841     {
842         req->handle = console_handle_unmap(handle);
843         req->flush  = FALSE;
844         if ((ret = !wine_server_call_err( req )))
845         {
846             if (nrofevents) *nrofevents = reply->read;
847         }
848     }
849     SERVER_END_REQ;
850     return ret;
851 }
852
853
854 /******************************************************************************
855  * read_console_input
856  *
857  * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
858  *
859  * Returns 
860  *      0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
861  */
862 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
863 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
864 {
865     enum read_console_input_return      ret;
866
867     if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
868         return rci_timeout;
869     SERVER_START_REQ( read_console_input )
870     {
871         req->handle = console_handle_unmap(handle);
872         req->flush = TRUE;
873         wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
874         if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
875         else ret = rci_gotone;
876     }
877     SERVER_END_REQ;
878
879     return ret;
880 }
881
882
883 /***********************************************************************
884  *            FlushConsoleInputBuffer   (KERNEL32.@)
885  */
886 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
887 {
888     enum read_console_input_return      last;
889     INPUT_RECORD                        ir;
890
891     while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
892
893     return last == rci_timeout;
894 }
895
896
897 /***********************************************************************
898  *            SetConsoleTitleA   (KERNEL32.@)
899  */
900 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
901 {
902     LPWSTR titleW;
903     BOOL ret;
904
905     DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
906     if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
907     MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
908     ret = SetConsoleTitleW(titleW);
909     HeapFree(GetProcessHeap(), 0, titleW);
910     return ret;
911 }
912
913
914 /***********************************************************************
915  *            GetConsoleTitleA   (KERNEL32.@)
916  *
917  * See GetConsoleTitleW.
918  */
919 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
920 {
921     WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
922     DWORD ret;
923
924     if (!ptr) return 0;
925     ret = GetConsoleTitleW( ptr, size );
926     if (ret)
927     {
928         WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
929         ret = strlen(title);
930     }
931     HeapFree(GetProcessHeap(), 0, ptr);
932     return ret;
933 }
934
935
936 /******************************************************************************
937  * GetConsoleTitleW [KERNEL32.@]  Retrieves title string for console
938  *
939  * PARAMS
940  *    title [O] Address of buffer for title
941  *    size  [I] Size of buffer
942  *
943  * RETURNS
944  *    Success: Length of string copied
945  *    Failure: 0
946  */
947 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
948 {
949     DWORD ret = 0;
950
951     SERVER_START_REQ( get_console_input_info )
952     {
953         req->handle = 0;
954         wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
955         if (!wine_server_call_err( req ))
956         {
957             ret = wine_server_reply_size(reply) / sizeof(WCHAR);
958             title[ret] = 0;
959         }
960     }
961     SERVER_END_REQ;
962     return ret;
963 }
964
965
966 /***********************************************************************
967  *            GetLargestConsoleWindowSize   (KERNEL32.@)
968  *
969  * NOTE
970  *      This should return a COORD, but calling convention for returning
971  *      structures is different between Windows and gcc on i386.
972  *
973  * VERSION: [i386]
974  */
975 #ifdef __i386__
976 #undef GetLargestConsoleWindowSize
977 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
978 {
979     union {
980         COORD c;
981         DWORD w;
982     } x;
983     x.c.X = 80;
984     x.c.Y = 24;
985     TRACE("(%p), returning %dx%d (%lx)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
986     return x.w;
987 }
988 #endif /* defined(__i386__) */
989
990
991 /***********************************************************************
992  *            GetLargestConsoleWindowSize   (KERNEL32.@)
993  *
994  * NOTE
995  *      This should return a COORD, but calling convention for returning
996  *      structures is different between Windows and gcc on i386.
997  *
998  * VERSION: [!i386]
999  */
1000 #ifndef __i386__
1001 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1002 {
1003     COORD c;
1004     c.X = 80;
1005     c.Y = 24;
1006     TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1007     return c;
1008 }
1009 #endif /* defined(__i386__) */
1010
1011 static WCHAR*   S_EditString /* = NULL */;
1012 static unsigned S_EditStrPos /* = 0 */;
1013
1014 /***********************************************************************
1015  *            FreeConsole (KERNEL32.@)
1016  */
1017 BOOL WINAPI FreeConsole(VOID)
1018 {
1019     BOOL ret;
1020
1021     SERVER_START_REQ(free_console)
1022     {
1023         ret = !wine_server_call_err( req );
1024     }
1025     SERVER_END_REQ;
1026     return ret;
1027 }
1028
1029 /******************************************************************
1030  *              start_console_renderer
1031  *
1032  * helper for AllocConsole
1033  * starts the renderer process
1034  */
1035 static  BOOL    start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1036                                               HANDLE hEvent)
1037 {
1038     char                buffer[1024];
1039     int                 ret;
1040     PROCESS_INFORMATION pi;
1041
1042     /* FIXME: use dynamic allocation for most of the buffers below */
1043     ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%d", appname, (INT)hEvent);
1044     if ((ret > -1) && (ret < sizeof(buffer)) &&
1045         CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1046                        NULL, NULL, si, &pi))
1047     {
1048         if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
1049
1050         TRACE("Started wineconsole pid=%08lx tid=%08lx\n",
1051               pi.dwProcessId, pi.dwThreadId);
1052
1053         return TRUE;
1054     }
1055     return FALSE;
1056 }
1057
1058 static  BOOL    start_console_renderer(STARTUPINFOA* si)
1059 {
1060     HANDLE              hEvent = 0;
1061     LPSTR               p;
1062     OBJECT_ATTRIBUTES   attr;
1063     BOOL                ret = FALSE;
1064
1065     attr.Length                   = sizeof(attr);
1066     attr.RootDirectory            = 0;
1067     attr.Attributes               = OBJ_INHERIT;
1068     attr.ObjectName               = NULL;
1069     attr.SecurityDescriptor       = NULL;
1070     attr.SecurityQualityOfService = NULL;
1071
1072     NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
1073     if (!hEvent) return FALSE;
1074
1075     /* first try environment variable */
1076     if ((p = getenv("WINECONSOLE")) != NULL)
1077     {
1078         ret = start_console_renderer_helper(p, si, hEvent);
1079         if (!ret)
1080             ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1081                 "trying default access\n", p);
1082     }
1083
1084     /* then try the regular PATH */
1085     if (!ret)
1086         ret = start_console_renderer_helper("wineconsole", si, hEvent);
1087
1088     CloseHandle(hEvent);
1089     return ret;
1090 }
1091
1092 /***********************************************************************
1093  *            AllocConsole (KERNEL32.@)
1094  *
1095  * creates an xterm with a pty to our program
1096  */
1097 BOOL WINAPI AllocConsole(void)
1098 {
1099     HANDLE              handle_in = INVALID_HANDLE_VALUE;
1100     HANDLE              handle_out = INVALID_HANDLE_VALUE;
1101     HANDLE              handle_err = INVALID_HANDLE_VALUE;
1102     STARTUPINFOA        siCurrent;
1103     STARTUPINFOA        siConsole;
1104     char                buffer[1024];
1105
1106     TRACE("()\n");
1107
1108     handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1109                               FALSE, OPEN_EXISTING );
1110
1111     if (VerifyConsoleIoHandle(handle_in))
1112     {
1113         /* we already have a console opened on this process, don't create a new one */
1114         CloseHandle(handle_in);
1115         return FALSE;
1116     }
1117     /* happens when we're running on a Unix console */
1118     if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1119
1120     GetStartupInfoA(&siCurrent);
1121
1122     memset(&siConsole, 0, sizeof(siConsole));
1123     siConsole.cb = sizeof(siConsole);
1124     /* setup a view arguments for wineconsole (it'll use them as default values)  */
1125     if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1126     {
1127         siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1128         siConsole.dwXCountChars = siCurrent.dwXCountChars;
1129         siConsole.dwYCountChars = siCurrent.dwYCountChars;
1130     }
1131     if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1132     {
1133         siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1134         siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1135     }
1136     if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1137     {
1138         siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1139         siConsole.wShowWindow = siCurrent.wShowWindow;
1140     }
1141     /* FIXME (should pass the unicode form) */
1142     if (siCurrent.lpTitle)
1143         siConsole.lpTitle = siCurrent.lpTitle;
1144     else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1145     {
1146         buffer[sizeof(buffer) - 1] = '\0';
1147         siConsole.lpTitle = buffer;
1148     }
1149
1150     if (!start_console_renderer(&siConsole))
1151         goto the_end;
1152
1153     if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1154         /* all std I/O handles are inheritable by default */
1155         handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1156                                   TRUE, OPEN_EXISTING );
1157         if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1158   
1159         handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1160                                    TRUE, OPEN_EXISTING );
1161         if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1162   
1163         if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1164                     &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1165             goto the_end;
1166     } else {
1167         /*  STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1168         handle_in  =  siCurrent.hStdInput;
1169         handle_out =  siCurrent.hStdOutput;
1170         handle_err =  siCurrent.hStdError;
1171     }
1172
1173     /* NT resets the STD_*_HANDLEs on console alloc */
1174     SetStdHandle(STD_INPUT_HANDLE,  handle_in);
1175     SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1176     SetStdHandle(STD_ERROR_HANDLE,  handle_err);
1177
1178     SetLastError(ERROR_SUCCESS);
1179
1180     return TRUE;
1181
1182  the_end:
1183     ERR("Can't allocate console\n");
1184     if (handle_in != INVALID_HANDLE_VALUE)      CloseHandle(handle_in);
1185     if (handle_out != INVALID_HANDLE_VALUE)     CloseHandle(handle_out);
1186     if (handle_err != INVALID_HANDLE_VALUE)     CloseHandle(handle_err);
1187     FreeConsole();
1188     return FALSE;
1189 }
1190
1191
1192 /***********************************************************************
1193  *            ReadConsoleA   (KERNEL32.@)
1194  */
1195 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1196                          LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1197 {
1198     LPWSTR      ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1199     DWORD       ncr = 0;
1200     BOOL        ret;
1201
1202     if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1203         ncr = WideCharToMultiByte(CP_ACP, 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1204
1205     if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1206     HeapFree(GetProcessHeap(), 0, ptr);
1207
1208     return ret;
1209 }
1210
1211 /***********************************************************************
1212  *            ReadConsoleW   (KERNEL32.@)
1213  */
1214 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1215                          DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1216 {
1217     DWORD       charsread;
1218     LPWSTR      xbuf = (LPWSTR)lpBuffer;
1219     DWORD       mode;
1220
1221     TRACE("(%p,%p,%ld,%p,%p)\n",
1222           hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1223
1224     if (!GetConsoleMode(hConsoleInput, &mode))
1225         return FALSE;
1226
1227     if (mode & ENABLE_LINE_INPUT)
1228     {
1229         if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1230         {
1231             HeapFree(GetProcessHeap(), 0, S_EditString);
1232             if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1233                 return FALSE;
1234             S_EditStrPos = 0;
1235         }
1236         charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1237         if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1238         memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1239         S_EditStrPos += charsread;
1240     }
1241     else
1242     {
1243         INPUT_RECORD    ir;
1244         DWORD           timeout = INFINITE;
1245
1246         /* FIXME: should we read at least 1 char? The SDK does not say */
1247         /* wait for at least one available input record (it doesn't mean we'll have
1248          * chars stored in xbuf...)
1249          */
1250         charsread = 0;
1251         do 
1252         {
1253             if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1254             timeout = 0;
1255             if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1256                 ir.Event.KeyEvent.uChar.UnicodeChar &&
1257                 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
1258             {
1259                 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1260             }
1261         } while (charsread < nNumberOfCharsToRead);
1262         /* nothing has been read */
1263         if (timeout == INFINITE) return FALSE;
1264     }
1265
1266     if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1267
1268     return TRUE;
1269 }
1270
1271
1272 /***********************************************************************
1273  *            ReadConsoleInputW   (KERNEL32.@)
1274  */
1275 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1276                               DWORD nLength, LPDWORD lpNumberOfEventsRead)
1277 {
1278     DWORD idx = 0;
1279     DWORD timeout = INFINITE;
1280
1281     if (!nLength)
1282     {
1283         if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1284         return TRUE;
1285     }
1286
1287     /* loop until we get at least one event */
1288     while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1289            ++idx < nLength)
1290         timeout = 0;
1291
1292     if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1293     return idx != 0;
1294 }
1295
1296
1297 /******************************************************************************
1298  * WriteConsoleOutputCharacterW [KERNEL32.@]
1299  * 
1300  * Copy character to consecutive cells in the console screen buffer.
1301  *
1302  * PARAMS
1303  *    hConsoleOutput    [I] Handle to screen buffer
1304  *    str               [I] Pointer to buffer with chars to write
1305  *    length            [I] Number of cells to write to
1306  *    coord             [I] Coords of first cell
1307  *    lpNumCharsWritten [O] Pointer to number of cells written
1308  *
1309  * RETURNS
1310  *    Success: TRUE
1311  *    Failure: FALSE
1312  *
1313  */
1314 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1315                                           COORD coord, LPDWORD lpNumCharsWritten )
1316 {
1317     BOOL ret;
1318
1319     TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
1320           debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1321
1322     SERVER_START_REQ( write_console_output )
1323     {
1324         req->handle = console_handle_unmap(hConsoleOutput);
1325         req->x      = coord.X;
1326         req->y      = coord.Y;
1327         req->mode   = CHAR_INFO_MODE_TEXT;
1328         req->wrap   = TRUE;
1329         wine_server_add_data( req, str, length * sizeof(WCHAR) );
1330         if ((ret = !wine_server_call_err( req )))
1331         {
1332             if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1333         }
1334     }
1335     SERVER_END_REQ;
1336     return ret;
1337 }
1338
1339
1340 /******************************************************************************
1341  * SetConsoleTitleW [KERNEL32.@]  Sets title bar string for console
1342  *
1343  * PARAMS
1344  *    title [I] Address of new title
1345  *
1346  * RETURNS
1347  *    Success: TRUE
1348  *    Failure: FALSE
1349  */
1350 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1351 {
1352     BOOL ret;
1353
1354     TRACE("(%s)\n", debugstr_w(title));
1355     SERVER_START_REQ( set_console_input_info )
1356     {
1357         req->handle = 0;
1358         req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1359         wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1360         ret = !wine_server_call_err( req );
1361     }
1362     SERVER_END_REQ;
1363     return ret;
1364 }
1365
1366
1367 /***********************************************************************
1368  *            GetNumberOfConsoleMouseButtons   (KERNEL32.@)
1369  */
1370 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1371 {
1372     FIXME("(%p): stub\n", nrofbuttons);
1373     *nrofbuttons = 2;
1374     return TRUE;
1375 }
1376
1377 /******************************************************************************
1378  *  SetConsoleInputExeNameW      [KERNEL32.@]
1379  *
1380  * BUGS
1381  *   Unimplemented
1382  */
1383 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1384 {
1385     FIXME("(%s): stub!\n", debugstr_w(name));
1386
1387     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1388     return TRUE;
1389 }
1390
1391 /******************************************************************************
1392  *  SetConsoleInputExeNameA      [KERNEL32.@]
1393  *
1394  * BUGS
1395  *   Unimplemented
1396  */
1397 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1398 {
1399     int         len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1400     LPWSTR      xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1401     BOOL        ret;
1402
1403     if (!xptr) return FALSE;
1404
1405     MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
1406     ret = SetConsoleInputExeNameW(xptr);
1407     HeapFree(GetProcessHeap(), 0, xptr);
1408
1409     return ret;
1410 }
1411
1412 /******************************************************************
1413  *              CONSOLE_DefaultHandler
1414  *
1415  * Final control event handler
1416  */
1417 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1418 {
1419     FIXME("Terminating process %lx on event %lx\n", GetCurrentProcessId(), dwCtrlType);
1420     ExitProcess(0);
1421     /* should never go here */
1422     return TRUE;
1423 }
1424
1425 /******************************************************************************
1426  * SetConsoleCtrlHandler [KERNEL32.@]  Adds function to calling process list
1427  *
1428  * PARAMS
1429  *    func [I] Address of handler function
1430  *    add  [I] Handler to add or remove
1431  *
1432  * RETURNS
1433  *    Success: TRUE
1434  *    Failure: FALSE
1435  */
1436
1437 struct ConsoleHandler
1438 {
1439     PHANDLER_ROUTINE            handler;
1440     struct ConsoleHandler*      next;
1441 };
1442
1443 static struct ConsoleHandler    CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1444 static struct ConsoleHandler*   CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1445
1446 static CRITICAL_SECTION CONSOLE_CritSect;
1447 static CRITICAL_SECTION_DEBUG critsect_debug =
1448 {
1449     0, 0, &CONSOLE_CritSect,
1450     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
1451       0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
1452 };
1453 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
1454
1455 /*****************************************************************************/
1456
1457 /******************************************************************
1458  *              SetConsoleCtrlHandler (KERNEL32.@)
1459  */
1460 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1461 {
1462     BOOL        ret = TRUE;
1463
1464     TRACE("(%p,%i)\n", func, add);
1465
1466     if (!func)
1467     {
1468         RtlEnterCriticalSection(&CONSOLE_CritSect);
1469         if (add)
1470             NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1471         else
1472             NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1473         RtlLeaveCriticalSection(&CONSOLE_CritSect);
1474     }
1475     else if (add)
1476     {
1477         struct ConsoleHandler*  ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1478
1479         if (!ch) return FALSE;
1480         ch->handler = func;
1481         RtlEnterCriticalSection(&CONSOLE_CritSect);
1482         ch->next = CONSOLE_Handlers;
1483         CONSOLE_Handlers = ch;
1484         RtlLeaveCriticalSection(&CONSOLE_CritSect);
1485     }
1486     else
1487     {
1488         struct ConsoleHandler**  ch;
1489         RtlEnterCriticalSection(&CONSOLE_CritSect);
1490         for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1491         {
1492             if ((*ch)->handler == func) break;
1493         }
1494         if (*ch)
1495         {
1496             struct ConsoleHandler*   rch = *ch;
1497
1498             /* sanity check */
1499             if (rch == &CONSOLE_DefaultConsoleHandler)
1500             {
1501                 ERR("Who's trying to remove default handler???\n");
1502                 SetLastError(ERROR_INVALID_PARAMETER);
1503                 ret = FALSE;
1504             }
1505             else
1506             {
1507                 *ch = rch->next;
1508                 HeapFree(GetProcessHeap(), 0, rch);
1509             }
1510         }
1511         else
1512         {
1513             WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1514             SetLastError(ERROR_INVALID_PARAMETER);
1515             ret = FALSE;
1516         }
1517         RtlLeaveCriticalSection(&CONSOLE_CritSect);
1518     }
1519     return ret;
1520 }
1521
1522 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
1523 {
1524     TRACE("(%lx)\n", GetExceptionCode());
1525     return EXCEPTION_EXECUTE_HANDLER;
1526 }
1527
1528 /******************************************************************
1529  *              CONSOLE_SendEventThread
1530  *
1531  * Internal helper to pass an event to the list on installed handlers
1532  */
1533 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1534 {
1535     DWORD                       event = (DWORD)pmt;
1536     struct ConsoleHandler*      ch;
1537
1538     if (event == CTRL_C_EVENT)
1539     {
1540         BOOL    caught_by_dbg = TRUE;
1541         /* First, try to pass the ctrl-C event to the debugger (if any)
1542          * If it continues, there's nothing more to do
1543          * Otherwise, we need to send the ctrl-C event to the handlers
1544          */
1545         __TRY
1546         {
1547             RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1548         }
1549         __EXCEPT(CONSOLE_CtrlEventHandler)
1550         {
1551             caught_by_dbg = FALSE;
1552         }
1553         __ENDTRY;
1554         if (caught_by_dbg) return 0;
1555         /* the debugger didn't continue... so, pass to ctrl handlers */
1556     }
1557     RtlEnterCriticalSection(&CONSOLE_CritSect);
1558     for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1559     {
1560         if (ch->handler(event)) break;
1561     }
1562     RtlLeaveCriticalSection(&CONSOLE_CritSect);
1563     return 1;
1564 }
1565
1566 /******************************************************************
1567  *              CONSOLE_HandleCtrlC
1568  *
1569  * Check whether the shall manipulate CtrlC events
1570  */
1571 int     CONSOLE_HandleCtrlC(unsigned sig)
1572 {
1573     /* FIXME: better test whether a console is attached to this process ??? */
1574     extern    unsigned CONSOLE_GetNumHistoryEntries(void);
1575     if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1576
1577     /* check if we have to ignore ctrl-C events */
1578     if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1579     {
1580         /* Create a separate thread to signal all the events. 
1581          * This is needed because:
1582          *  - this function can be called in an Unix signal handler (hence on an
1583          *    different stack than the thread that's running). This breaks the 
1584          *    Win32 exception mechanisms (where the thread's stack is checked).
1585          *  - since the current thread, while processing the signal, can hold the
1586          *    console critical section, we need another execution environment where
1587          *    we can wait on this critical section 
1588          */
1589         CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1590     }
1591     return 1;
1592 }
1593
1594 /******************************************************************************
1595  * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1596  *
1597  * PARAMS
1598  *    dwCtrlEvent        [I] Type of event
1599  *    dwProcessGroupID   [I] Process group ID to send event to
1600  *
1601  * RETURNS
1602  *    Success: True
1603  *    Failure: False (and *should* [but doesn't] set LastError)
1604  */
1605 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1606                                      DWORD dwProcessGroupID)
1607 {
1608     BOOL ret;
1609
1610     TRACE("(%ld, %ld)\n", dwCtrlEvent, dwProcessGroupID);
1611
1612     if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1613     {
1614         ERR("Invalid event %ld for PGID %ld\n", dwCtrlEvent, dwProcessGroupID);
1615         return FALSE;
1616     }
1617
1618     SERVER_START_REQ( send_console_signal )
1619     {
1620         req->signal = dwCtrlEvent;
1621         req->group_id = dwProcessGroupID;
1622         ret = !wine_server_call_err( req );
1623     }
1624     SERVER_END_REQ;
1625
1626     /* FIXME: shall this function be synchronous, ie only return when all events
1627      * have been handled by all processes in the given group ?
1628      * As of today, we don't wait...
1629      */
1630     return ret;
1631 }
1632
1633
1634 /******************************************************************************
1635  * CreateConsoleScreenBuffer [KERNEL32.@]  Creates a console screen buffer
1636  *
1637  * PARAMS
1638  *    dwDesiredAccess    [I] Access flag
1639  *    dwShareMode        [I] Buffer share mode
1640  *    sa                 [I] Security attributes
1641  *    dwFlags            [I] Type of buffer to create
1642  *    lpScreenBufferData [I] Reserved
1643  *
1644  * NOTES
1645  *    Should call SetLastError
1646  *
1647  * RETURNS
1648  *    Success: Handle to new console screen buffer
1649  *    Failure: INVALID_HANDLE_VALUE
1650  */
1651 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1652                                         LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1653                                         LPVOID lpScreenBufferData)
1654 {
1655     HANDLE      ret = INVALID_HANDLE_VALUE;
1656
1657     TRACE("(%ld,%ld,%p,%ld,%p)\n",
1658           dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1659
1660     if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1661     {
1662         SetLastError(ERROR_INVALID_PARAMETER);
1663         return INVALID_HANDLE_VALUE;
1664     }
1665
1666     SERVER_START_REQ(create_console_output)
1667     {
1668         req->handle_in  = 0;
1669         req->access     = dwDesiredAccess;
1670         req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
1671         req->share      = dwShareMode;
1672         if (!wine_server_call_err( req )) ret = reply->handle_out;
1673     }
1674     SERVER_END_REQ;
1675
1676     return ret;
1677 }
1678
1679
1680 /***********************************************************************
1681  *           GetConsoleScreenBufferInfo   (KERNEL32.@)
1682  */
1683 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1684 {
1685     BOOL        ret;
1686
1687     SERVER_START_REQ(get_console_output_info)
1688     {
1689         req->handle = console_handle_unmap(hConsoleOutput);
1690         if ((ret = !wine_server_call_err( req )))
1691         {
1692             csbi->dwSize.X              = reply->width;
1693             csbi->dwSize.Y              = reply->height;
1694             csbi->dwCursorPosition.X    = reply->cursor_x;
1695             csbi->dwCursorPosition.Y    = reply->cursor_y;
1696             csbi->wAttributes           = reply->attr;
1697             csbi->srWindow.Left         = reply->win_left;
1698             csbi->srWindow.Right        = reply->win_right;
1699             csbi->srWindow.Top          = reply->win_top;
1700             csbi->srWindow.Bottom       = reply->win_bottom;
1701             csbi->dwMaximumWindowSize.X = reply->max_width;
1702             csbi->dwMaximumWindowSize.Y = reply->max_height;
1703         }
1704     }
1705     SERVER_END_REQ;
1706
1707     TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n", 
1708           hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1709           csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1710           csbi->wAttributes,
1711           csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1712           csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1713
1714     return ret;
1715 }
1716
1717
1718 /******************************************************************************
1719  * SetConsoleActiveScreenBuffer [KERNEL32.@]  Sets buffer to current console
1720  *
1721  * RETURNS
1722  *    Success: TRUE
1723  *    Failure: FALSE
1724  */
1725 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1726 {
1727     BOOL ret;
1728
1729     TRACE("(%p)\n", hConsoleOutput);
1730
1731     SERVER_START_REQ( set_console_input_info )
1732     {
1733         req->handle    = 0;
1734         req->mask      = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1735         req->active_sb = hConsoleOutput;
1736         ret = !wine_server_call_err( req );
1737     }
1738     SERVER_END_REQ;
1739     return ret;
1740 }
1741
1742
1743 /***********************************************************************
1744  *            GetConsoleMode   (KERNEL32.@)
1745  */
1746 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1747 {
1748     BOOL ret;
1749
1750     SERVER_START_REQ(get_console_mode)
1751     {
1752         req->handle = console_handle_unmap(hcon);
1753         ret = !wine_server_call_err( req );
1754         if (ret && mode) *mode = reply->mode;
1755     }
1756     SERVER_END_REQ;
1757     return ret;
1758 }
1759
1760
1761 /******************************************************************************
1762  * SetConsoleMode [KERNEL32.@]  Sets input mode of console's input buffer
1763  *
1764  * PARAMS
1765  *    hcon [I] Handle to console input or screen buffer
1766  *    mode [I] Input or output mode to set
1767  *
1768  * RETURNS
1769  *    Success: TRUE
1770  *    Failure: FALSE
1771  *
1772  *    mode:
1773  *      ENABLE_PROCESSED_INPUT  0x01
1774  *      ENABLE_LINE_INPUT       0x02
1775  *      ENABLE_ECHO_INPUT       0x04
1776  *      ENABLE_WINDOW_INPUT     0x08
1777  *      ENABLE_MOUSE_INPUT      0x10
1778  */
1779 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1780 {
1781     BOOL ret;
1782
1783     SERVER_START_REQ(set_console_mode)
1784     {
1785         req->handle = console_handle_unmap(hcon);
1786         req->mode = mode;
1787         ret = !wine_server_call_err( req );
1788     }
1789     SERVER_END_REQ;
1790     /* FIXME: when resetting a console input to editline mode, I think we should
1791      * empty the S_EditString buffer
1792      */
1793
1794     TRACE("(%p,%lx) retval == %d\n", hcon, mode, ret);
1795
1796     return ret;
1797 }
1798
1799
1800 /******************************************************************
1801  *              CONSOLE_WriteChars
1802  *
1803  * WriteConsoleOutput helper: hides server call semantics
1804  * writes a string at a given pos with standard attribute
1805  */
1806 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1807 {
1808     int written = -1;
1809
1810     if (!nc) return 0;
1811
1812     SERVER_START_REQ( write_console_output )
1813     {
1814         req->handle = console_handle_unmap(hCon);
1815         req->x      = pos->X;
1816         req->y      = pos->Y;
1817         req->mode   = CHAR_INFO_MODE_TEXTSTDATTR;
1818         req->wrap   = FALSE;
1819         wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1820         if (!wine_server_call_err( req )) written = reply->written;
1821     }
1822     SERVER_END_REQ;
1823
1824     if (written > 0) pos->X += written;
1825     return written;
1826 }
1827
1828 /******************************************************************
1829  *              next_line
1830  *
1831  * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1832  *
1833  */
1834 static int      next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1835 {
1836     SMALL_RECT  src;
1837     CHAR_INFO   ci;
1838     COORD       dst;
1839
1840     csbi->dwCursorPosition.X = 0;
1841     csbi->dwCursorPosition.Y++;
1842
1843     if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1844
1845     src.Top    = 1;
1846     src.Bottom = csbi->dwSize.Y - 1;
1847     src.Left   = 0;
1848     src.Right  = csbi->dwSize.X - 1;
1849
1850     dst.X      = 0;
1851     dst.Y      = 0;
1852
1853     ci.Attributes = csbi->wAttributes;
1854     ci.Char.UnicodeChar = ' ';
1855
1856     csbi->dwCursorPosition.Y--;
1857     if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1858         return 0;
1859     return 1;
1860 }
1861
1862 /******************************************************************
1863  *              write_block
1864  *
1865  * WriteConsoleOutput helper: writes a block of non special characters
1866  * Block can spread on several lines, and wrapping, if needed, is
1867  * handled
1868  *
1869  */
1870 static int      write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1871                             DWORD mode, LPCWSTR ptr, int len)
1872 {
1873     int blk;    /* number of chars to write on current line */
1874     int done;   /* number of chars already written */
1875
1876     if (len <= 0) return 1;
1877
1878     if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1879     {
1880         for (done = 0; done < len; done += blk)
1881         {
1882             blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1883
1884             if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1885                 return 0;
1886             if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
1887                 return 0;
1888         }
1889     }
1890     else
1891     {
1892         int     pos = csbi->dwCursorPosition.X;
1893         /* FIXME: we could reduce the number of loops
1894          * but, in most cases we wouldn't gain lots of time (it would only
1895          * happen if we're asked to overwrite more than twice the part of the line,
1896          * which is unlikely
1897          */
1898         for (blk = done = 0; done < len; done += blk)
1899         {
1900             blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1901
1902             csbi->dwCursorPosition.X = pos;
1903             if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1904                 return 0;
1905         }
1906     }
1907
1908     return 1;
1909 }
1910
1911 /***********************************************************************
1912  *            WriteConsoleW   (KERNEL32.@)
1913  */
1914 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1915                           LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1916 {
1917     DWORD                       mode;
1918     DWORD                       nw = 0;
1919     const WCHAR*                psz = lpBuffer;
1920     CONSOLE_SCREEN_BUFFER_INFO  csbi;
1921     int                         k, first = 0;
1922
1923     TRACE("%p %s %ld %p %p\n",
1924           hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
1925           nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
1926
1927     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1928
1929     if (!GetConsoleMode(hConsoleOutput, &mode) ||
1930         !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1931         return FALSE;
1932
1933     if (mode & ENABLE_PROCESSED_OUTPUT)
1934     {
1935         unsigned int    i;
1936
1937         for (i = 0; i < nNumberOfCharsToWrite; i++)
1938         {
1939             switch (psz[i])
1940             {
1941             case '\b': case '\t': case '\n': case '\a': case '\r':
1942                 /* don't handle here the i-th char... done below */
1943                 if ((k = i - first) > 0)
1944                 {
1945                     if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1946                         goto the_end;
1947                     nw += k;
1948                 }
1949                 first = i + 1;
1950                 nw++;
1951             }
1952             switch (psz[i])
1953             {
1954             case '\b':
1955                 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
1956                 break;
1957             case '\t':
1958                 {
1959                     WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
1960
1961                     if (!write_block(hConsoleOutput, &csbi, mode, tmp,
1962                                      ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
1963                         goto the_end;
1964                 }
1965                 break;
1966             case '\n':
1967                 next_line(hConsoleOutput, &csbi);
1968                 break;
1969             case '\a':
1970                 Beep(400, 300);
1971                 break;
1972             case '\r':
1973                 csbi.dwCursorPosition.X = 0;
1974                 break;
1975             default:
1976                 break;
1977             }
1978         }
1979     }
1980
1981     /* write the remaining block (if any) if processed output is enabled, or the
1982      * entire buffer otherwise
1983      */
1984     if ((k = nNumberOfCharsToWrite - first) > 0)
1985     {
1986         if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1987             goto the_end;
1988         nw += k;
1989     }
1990
1991  the_end:
1992     SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
1993     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
1994     return nw != 0;
1995 }
1996
1997
1998 /***********************************************************************
1999  *            WriteConsoleA   (KERNEL32.@)
2000  */
2001 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2002                           LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2003 {
2004     BOOL        ret;
2005     LPWSTR      xstring;
2006     DWORD       n;
2007
2008     n = MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2009
2010     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2011     xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2012     if (!xstring) return 0;
2013
2014     MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2015
2016     ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2017
2018     HeapFree(GetProcessHeap(), 0, xstring);
2019
2020     return ret;
2021 }
2022
2023 /******************************************************************************
2024  * SetConsoleCursorPosition [KERNEL32.@]
2025  * Sets the cursor position in console
2026  *
2027  * PARAMS
2028  *    hConsoleOutput   [I] Handle of console screen buffer
2029  *    dwCursorPosition [I] New cursor position coordinates
2030  *
2031  * RETURNS
2032  *    Success: TRUE
2033  *    Failure: FALSE
2034  */
2035 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2036 {
2037     BOOL                        ret;
2038     CONSOLE_SCREEN_BUFFER_INFO  csbi;
2039     int                         do_move = 0;
2040     int                         w, h;
2041
2042     TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2043
2044     SERVER_START_REQ(set_console_output_info)
2045     {
2046         req->handle         = console_handle_unmap(hcon);
2047         req->cursor_x       = pos.X;
2048         req->cursor_y       = pos.Y;
2049         req->mask           = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2050         ret = !wine_server_call_err( req );
2051     }
2052     SERVER_END_REQ;
2053
2054     if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2055         return FALSE;
2056
2057     /* if cursor is no longer visible, scroll the visible window... */
2058     w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2059     h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2060     if (pos.X < csbi.srWindow.Left)
2061     {
2062         csbi.srWindow.Left   = min(pos.X, csbi.dwSize.X - w);
2063         do_move++;
2064     }
2065     else if (pos.X > csbi.srWindow.Right)
2066     {
2067         csbi.srWindow.Left   = max(pos.X, w) - w + 1;
2068         do_move++;
2069     }
2070     csbi.srWindow.Right  = csbi.srWindow.Left + w - 1;
2071
2072     if (pos.Y < csbi.srWindow.Top)
2073     {
2074         csbi.srWindow.Top    = min(pos.Y, csbi.dwSize.Y - h);
2075         do_move++;
2076     }
2077     else if (pos.Y > csbi.srWindow.Bottom)
2078     {
2079         csbi.srWindow.Top   = max(pos.Y, h) - h + 1;
2080         do_move++;
2081     }
2082     csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2083
2084     ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2085
2086     return ret;
2087 }
2088
2089 /******************************************************************************
2090  * GetConsoleCursorInfo [KERNEL32.@]  Gets size and visibility of console
2091  *
2092  * PARAMS
2093  *    hcon  [I] Handle to console screen buffer
2094  *    cinfo [O] Address of cursor information
2095  *
2096  * RETURNS
2097  *    Success: TRUE
2098  *    Failure: FALSE
2099  */
2100 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2101 {
2102     BOOL ret;
2103
2104     SERVER_START_REQ(get_console_output_info)
2105     {
2106         req->handle = console_handle_unmap(hCon);
2107         ret = !wine_server_call_err( req );
2108         if (ret && cinfo)
2109         {
2110             cinfo->dwSize = reply->cursor_size;
2111             cinfo->bVisible = reply->cursor_visible;
2112         }
2113     }
2114     SERVER_END_REQ;
2115
2116     TRACE("(%p) returning (%ld,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2117     return ret;
2118 }
2119
2120
2121 /******************************************************************************
2122  * SetConsoleCursorInfo [KERNEL32.@]  Sets size and visibility of cursor
2123  *
2124  * PARAMS
2125  *      hcon    [I] Handle to console screen buffer
2126  *      cinfo   [I] Address of cursor information
2127  * RETURNS
2128  *    Success: TRUE
2129  *    Failure: FALSE
2130  */
2131 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2132 {
2133     BOOL ret;
2134
2135     TRACE("(%p,%ld,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2136     SERVER_START_REQ(set_console_output_info)
2137     {
2138         req->handle         = console_handle_unmap(hCon);
2139         req->cursor_size    = cinfo->dwSize;
2140         req->cursor_visible = cinfo->bVisible;
2141         req->mask           = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2142         ret = !wine_server_call_err( req );
2143     }
2144     SERVER_END_REQ;
2145     return ret;
2146 }
2147
2148
2149 /******************************************************************************
2150  * SetConsoleWindowInfo [KERNEL32.@]  Sets size and position of console
2151  *
2152  * PARAMS
2153  *      hcon            [I] Handle to console screen buffer
2154  *      bAbsolute       [I] Coordinate type flag
2155  *      window          [I] Address of new window rectangle
2156  * RETURNS
2157  *    Success: TRUE
2158  *    Failure: FALSE
2159  */
2160 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2161 {
2162     SMALL_RECT  p = *window;
2163     BOOL        ret;
2164
2165     TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2166
2167     if (!bAbsolute)
2168     {
2169         CONSOLE_SCREEN_BUFFER_INFO      csbi;
2170
2171         if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2172             return FALSE;
2173         p.Left   += csbi.srWindow.Left;
2174         p.Top    += csbi.srWindow.Top;
2175         p.Right  += csbi.srWindow.Right;
2176         p.Bottom += csbi.srWindow.Bottom;
2177     }
2178     SERVER_START_REQ(set_console_output_info)
2179     {
2180         req->handle         = console_handle_unmap(hCon);
2181         req->win_left       = p.Left;
2182         req->win_top        = p.Top;
2183         req->win_right      = p.Right;
2184         req->win_bottom     = p.Bottom;
2185         req->mask           = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2186         ret = !wine_server_call_err( req );
2187     }
2188     SERVER_END_REQ;
2189
2190     return ret;
2191 }
2192
2193
2194 /******************************************************************************
2195  * SetConsoleTextAttribute [KERNEL32.@]  Sets colors for text
2196  *
2197  * Sets the foreground and background color attributes of characters
2198  * written to the screen buffer.
2199  *
2200  * RETURNS
2201  *    Success: TRUE
2202  *    Failure: FALSE
2203  */
2204 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2205 {
2206     BOOL ret;
2207
2208     TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2209     SERVER_START_REQ(set_console_output_info)
2210     {
2211         req->handle = console_handle_unmap(hConsoleOutput);
2212         req->attr   = wAttr;
2213         req->mask   = SET_CONSOLE_OUTPUT_INFO_ATTR;
2214         ret = !wine_server_call_err( req );
2215     }
2216     SERVER_END_REQ;
2217     return ret;
2218 }
2219
2220
2221 /******************************************************************************
2222  * SetConsoleScreenBufferSize [KERNEL32.@]  Changes size of console
2223  *
2224  * PARAMS
2225  *    hConsoleOutput [I] Handle to console screen buffer
2226  *    dwSize         [I] New size in character rows and cols
2227  *
2228  * RETURNS
2229  *    Success: TRUE
2230  *    Failure: FALSE
2231  */
2232 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2233 {
2234     BOOL ret;
2235
2236     TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2237     SERVER_START_REQ(set_console_output_info)
2238     {
2239         req->handle = console_handle_unmap(hConsoleOutput);
2240         req->width  = dwSize.X;
2241         req->height = dwSize.Y;
2242         req->mask   = SET_CONSOLE_OUTPUT_INFO_SIZE;
2243         ret = !wine_server_call_err( req );
2244     }
2245     SERVER_END_REQ;
2246     return ret;
2247 }
2248
2249
2250 /******************************************************************************
2251  * ScrollConsoleScreenBufferA [KERNEL32.@]
2252  *
2253  */
2254 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2255                                        LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2256                                        LPCHAR_INFO lpFill)
2257 {
2258     CHAR_INFO   ciw;
2259
2260     ciw.Attributes = lpFill->Attributes;
2261     MultiByteToWideChar(CP_ACP, 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2262
2263     return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2264                                       dwDestOrigin, &ciw);
2265 }
2266
2267 /******************************************************************
2268  *              CONSOLE_FillLineUniform
2269  *
2270  * Helper function for ScrollConsoleScreenBufferW
2271  * Fills a part of a line with a constant character info
2272  */
2273 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2274 {
2275     SERVER_START_REQ( fill_console_output )
2276     {
2277         req->handle    = console_handle_unmap(hConsoleOutput);
2278         req->mode      = CHAR_INFO_MODE_TEXTATTR;
2279         req->x         = i;
2280         req->y         = j;
2281         req->count     = len;
2282         req->wrap      = FALSE;
2283         req->data.ch   = lpFill->Char.UnicodeChar;
2284         req->data.attr = lpFill->Attributes;
2285         wine_server_call_err( req );
2286     }
2287     SERVER_END_REQ;
2288 }
2289
2290 /******************************************************************************
2291  * ScrollConsoleScreenBufferW [KERNEL32.@]
2292  *
2293  */
2294
2295 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2296                                        LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2297                                        LPCHAR_INFO lpFill)
2298 {
2299     SMALL_RECT                  dst;
2300     DWORD                       ret;
2301     int                         i, j;
2302     int                         start = -1;
2303     SMALL_RECT                  clip;
2304     CONSOLE_SCREEN_BUFFER_INFO  csbi;
2305     BOOL                        inside;
2306     COORD                       src;
2307
2308     if (lpClipRect)
2309         TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2310               lpScrollRect->Left, lpScrollRect->Top,
2311               lpScrollRect->Right, lpScrollRect->Bottom,
2312               lpClipRect->Left, lpClipRect->Top,
2313               lpClipRect->Right, lpClipRect->Bottom,
2314               dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2315     else
2316         TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2317               lpScrollRect->Left, lpScrollRect->Top,
2318               lpScrollRect->Right, lpScrollRect->Bottom,
2319               dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2320
2321     if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2322         return FALSE;
2323
2324     src.X = lpScrollRect->Left;
2325     src.Y = lpScrollRect->Top;
2326
2327     /* step 1: get dst rect */
2328     dst.Left = dwDestOrigin.X;
2329     dst.Top = dwDestOrigin.Y;
2330     dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2331     dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2332
2333     /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2334     if (lpClipRect)
2335     {
2336         clip.Left   = max(0, lpClipRect->Left);
2337         clip.Right  = min(csbi.dwSize.X - 1, lpClipRect->Right);
2338         clip.Top    = max(0, lpClipRect->Top);
2339         clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2340     }
2341     else
2342     {
2343         clip.Left   = 0;
2344         clip.Right  = csbi.dwSize.X - 1;
2345         clip.Top    = 0;
2346         clip.Bottom = csbi.dwSize.Y - 1;
2347     }
2348     if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2349
2350     /* step 2b: clip dst rect */
2351     if (dst.Left   < clip.Left  ) {src.X += clip.Left - dst.Left; dst.Left   = clip.Left;}
2352     if (dst.Top    < clip.Top   ) {src.Y += clip.Top  - dst.Top;  dst.Top    = clip.Top;}
2353     if (dst.Right  > clip.Right ) dst.Right  = clip.Right;
2354     if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2355
2356     /* step 3: transfer the bits */
2357     SERVER_START_REQ(move_console_output)
2358     {
2359         req->handle = console_handle_unmap(hConsoleOutput);
2360         req->x_src = src.X;
2361         req->y_src = src.Y;
2362         req->x_dst = dst.Left;
2363         req->y_dst = dst.Top;
2364         req->w = dst.Right - dst.Left + 1;
2365         req->h = dst.Bottom - dst.Top + 1;
2366         ret = !wine_server_call_err( req );
2367     }
2368     SERVER_END_REQ;
2369
2370     if (!ret) return FALSE;
2371
2372     /* step 4: clean out the exposed part */
2373
2374     /* have to write cell [i,j] if it is not in dst rect (because it has already
2375      * been written to by the scroll) and is in clip (we shall not write
2376      * outside of clip)
2377      */
2378     for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2379     {
2380         inside = dst.Top <= j && j <= dst.Bottom;
2381         start = -1;
2382         for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2383         {
2384             if (inside && dst.Left <= i && i <= dst.Right)
2385             {
2386                 if (start != -1)
2387                 {
2388                     CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2389                     start = -1;
2390                 }
2391             }
2392             else
2393             {
2394                 if (start == -1) start = i;
2395             }
2396         }
2397         if (start != -1)
2398             CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2399     }
2400
2401     return TRUE;
2402 }
2403
2404
2405 /* ====================================================================
2406  *
2407  * Console manipulation functions
2408  *
2409  * ====================================================================*/
2410
2411 /* some missing functions...
2412  * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2413  * should get the right API and implement them
2414  *      GetConsoleCommandHistory[AW] (dword dword dword)
2415  *      GetConsoleCommandHistoryLength[AW]
2416  *      SetConsoleCommandHistoryMode
2417  *      SetConsoleNumberOfCommands[AW]
2418  */
2419 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2420 {
2421     int len = 0;
2422
2423     SERVER_START_REQ( get_console_input_history )
2424     {
2425         req->handle = 0;
2426         req->index = idx;
2427         if (buf && buf_len > 1)
2428         {
2429             wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2430         }
2431         if (!wine_server_call_err( req ))
2432         {
2433             if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2434             len = reply->total / sizeof(WCHAR) + 1;
2435         }
2436     }
2437     SERVER_END_REQ;
2438     return len;
2439 }
2440
2441 /******************************************************************
2442  *              CONSOLE_AppendHistory
2443  *
2444  *
2445  */
2446 BOOL    CONSOLE_AppendHistory(const WCHAR* ptr)
2447 {
2448     size_t      len = strlenW(ptr);
2449     BOOL        ret;
2450
2451     while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2452
2453     SERVER_START_REQ( append_console_input_history )
2454     {
2455         req->handle = 0;
2456         wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2457         ret = !wine_server_call_err( req );
2458     }
2459     SERVER_END_REQ;
2460     return ret;
2461 }
2462
2463 /******************************************************************
2464  *              CONSOLE_GetNumHistoryEntries
2465  *
2466  *
2467  */
2468 unsigned CONSOLE_GetNumHistoryEntries(void)
2469 {
2470     unsigned ret = -1;
2471     SERVER_START_REQ(get_console_input_info)
2472     {
2473         req->handle = 0;
2474         if (!wine_server_call_err( req )) ret = reply->history_index;
2475     }
2476     SERVER_END_REQ;
2477     return ret;
2478 }
2479
2480 /******************************************************************
2481  *              CONSOLE_GetEditionMode
2482  *
2483  *
2484  */
2485 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2486 {
2487     unsigned ret = FALSE;
2488     SERVER_START_REQ(get_console_input_info)
2489     {
2490         req->handle = console_handle_unmap(hConIn);
2491         if ((ret = !wine_server_call_err( req )))
2492             *mode = reply->edition_mode;
2493     }
2494     SERVER_END_REQ;
2495     return ret;
2496 }