Add missing backslash in the debugger definition.
[wine] / win32 / console.c
1 /*
2  * Win32 kernel 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  */
9
10 /* FIXME:
11  * - Completely lacks SCREENBUFFER interface.
12  * - No abstraction for something other than xterm.
13  * - Key input translation shouldn't use VkKeyScan and MapVirtualKey, since
14  *   they are window (USER) driver dependend.
15  * - Output sometimes is buffered (We switched off buffering by ~ICANON ?)
16  */
17 /* Reference applications:
18  * -  IDA (interactive disassembler) full version 3.75. Works.
19  * -  LYNX/W32. Works mostly, some keys crash it.
20  */
21
22 #include "config.h"
23
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <unistd.h>
27 #include <termios.h>
28 #include <string.h>
29 #include <sys/ioctl.h>
30 #include <sys/types.h>
31 #include <sys/time.h>
32 #include <fcntl.h>
33 #include <errno.h>
34 #ifdef HAVE_SYS_ERRNO_H
35 #include <sys/errno.h>
36 #endif
37 #include <signal.h>
38 #include <assert.h>
39
40 #include "winbase.h"
41 #include "windef.h"
42 #include "wingdi.h"
43 #include "wine/winuser16.h"
44 #include "wine/keyboard16.h"
45 #include "thread.h"
46 #include "file.h"
47 #include "process.h"
48 #include "winerror.h"
49 #include "wincon.h"
50 #include "heap.h"
51 #include "server.h"
52 #include "debugtools.h"
53 #include "winnls.h"
54
55 DEFAULT_DEBUG_CHANNEL(console)
56
57
58 /* FIXME:  Should be in an internal header file.  OK, so which one?
59    Used by CONSOLE_makecomplex. */
60 int wine_openpty(int *master, int *slave, char *name,
61                  struct termios *term, struct winsize *winsize);
62
63 /****************************************************************************
64  *              CONSOLE_GetPid
65  */
66 static int CONSOLE_GetPid( HANDLE handle )
67 {
68     struct get_console_info_request *req = get_req_buffer();
69     req->handle = handle;
70     if (server_call( REQ_GET_CONSOLE_INFO )) return 0;
71     return req->pid;
72 }
73
74 /****************************************************************************
75  *              XTERM_string_to_IR                      [internal]
76  *
77  * Transfers a string read from XTERM to INPUT_RECORDs and adds them to the
78  * queue. Does translation of vt100 style function keys and xterm-mouse clicks.
79  */
80 static void
81 CONSOLE_string_to_IR( HANDLE hConsoleInput,unsigned char *buf,int len) {
82     int                 j,k;
83     INPUT_RECORD        ir;
84     DWORD               junk;
85
86     for (j=0;j<len;j++) {
87         unsigned char inchar = buf[j];
88
89         if (inchar!=27) { /* no escape -> 'normal' keyboard event */
90             ir.EventType = 1; /* Key_event */
91
92             ir.Event.KeyEvent.bKeyDown          = 1;
93             ir.Event.KeyEvent.wRepeatCount      = 0;
94
95             ir.Event.KeyEvent.dwControlKeyState = 0;
96             if (inchar & 0x80) {
97                 ir.Event.KeyEvent.dwControlKeyState|=LEFT_ALT_PRESSED;
98                 inchar &= ~0x80;
99             }
100             ir.Event.KeyEvent.wVirtualKeyCode = VkKeyScan16(inchar);
101             if (ir.Event.KeyEvent.wVirtualKeyCode & 0x0100)
102                 ir.Event.KeyEvent.dwControlKeyState|=SHIFT_PRESSED;
103             if (ir.Event.KeyEvent.wVirtualKeyCode & 0x0200)
104                 ir.Event.KeyEvent.dwControlKeyState|=LEFT_CTRL_PRESSED;
105             if (ir.Event.KeyEvent.wVirtualKeyCode & 0x0400)
106                 ir.Event.KeyEvent.dwControlKeyState|=LEFT_ALT_PRESSED;
107             ir.Event.KeyEvent.wVirtualScanCode = MapVirtualKey16(
108                 ir.Event.KeyEvent.wVirtualKeyCode & 0x00ff,
109                 0 /* VirtualKeyCodes to ScanCode */
110             );
111             ir.Event.KeyEvent.uChar.AsciiChar = inchar;
112
113             if ((inchar==127)||(inchar=='\b')) { /* backspace */
114                 ir.Event.KeyEvent.uChar.AsciiChar = '\b'; /* FIXME: hmm */
115                 ir.Event.KeyEvent.wVirtualScanCode = 0x0e;
116                 ir.Event.KeyEvent.wVirtualKeyCode = VK_BACK;
117             } else {
118                 if ((inchar=='\n')||(inchar=='\r')) {
119                     ir.Event.KeyEvent.uChar.AsciiChar   = '\r';
120                     ir.Event.KeyEvent.wVirtualKeyCode   = VK_RETURN;
121                     ir.Event.KeyEvent.wVirtualScanCode  = 0x1c;
122                     ir.Event.KeyEvent.dwControlKeyState = 0;
123                 } else {
124                     if (inchar<' ') {
125                         /* FIXME: find good values for ^X */
126                         ir.Event.KeyEvent.wVirtualKeyCode = 0xdead;
127                         ir.Event.KeyEvent.wVirtualScanCode = 0xbeef;
128                     } 
129                 }
130             }
131
132             assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
133             ir.Event.KeyEvent.bKeyDown = 0;
134             assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
135             continue;
136         }
137         /* inchar is ESC */
138         if ((j==len-1) || (buf[j+1]!='[')) {/* add ESCape on its own */
139             ir.EventType = 1; /* Key_event */
140             ir.Event.KeyEvent.bKeyDown          = 1;
141             ir.Event.KeyEvent.wRepeatCount      = 0;
142
143             ir.Event.KeyEvent.wVirtualKeyCode   = VkKeyScan16(27);
144             ir.Event.KeyEvent.wVirtualScanCode  = MapVirtualKey16(
145                 ir.Event.KeyEvent.wVirtualKeyCode,0
146             );
147             ir.Event.KeyEvent.dwControlKeyState = 0;
148             ir.Event.KeyEvent.uChar.AsciiChar   = 27;
149             assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
150             ir.Event.KeyEvent.bKeyDown = 0;
151             assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
152             continue;
153         }
154         for (k=j;k<len;k++) {
155             if (((buf[k]>='A') && (buf[k]<='Z')) ||
156                 ((buf[k]>='a') && (buf[k]<='z')) ||
157                  (buf[k]=='~')
158             )
159                 break;
160         }
161         if (k<len) {
162             int subid,scancode=0;
163
164             ir.EventType                        = 1; /* Key_event */
165             ir.Event.KeyEvent.bKeyDown          = 1;
166             ir.Event.KeyEvent.wRepeatCount      = 0;
167             ir.Event.KeyEvent.dwControlKeyState = 0;
168
169             ir.Event.KeyEvent.wVirtualKeyCode   = 0xad; /* FIXME */
170             ir.Event.KeyEvent.wVirtualScanCode  = 0xad; /* FIXME */
171             ir.Event.KeyEvent.uChar.AsciiChar   = 0;
172
173             switch (buf[k]) {
174             case '~':
175                 sscanf(&buf[j+2],"%d",&subid);
176                 switch (subid) {
177                 case  2:/*INS */scancode = 0xe052;break;
178                 case  3:/*DEL */scancode = 0xe053;break;
179                 case  6:/*PGDW*/scancode = 0xe051;break;
180                 case  5:/*PGUP*/scancode = 0xe049;break;
181                 case 11:/*F1  */scancode = 0x003b;break;
182                 case 12:/*F2  */scancode = 0x003c;break;
183                 case 13:/*F3  */scancode = 0x003d;break;
184                 case 14:/*F4  */scancode = 0x003e;break;
185                 case 15:/*F5  */scancode = 0x003f;break;
186                 case 17:/*F6  */scancode = 0x0040;break;
187                 case 18:/*F7  */scancode = 0x0041;break;
188                 case 19:/*F8  */scancode = 0x0042;break;
189                 case 20:/*F9  */scancode = 0x0043;break;
190                 case 21:/*F10 */scancode = 0x0044;break;
191                 case 23:/*F11 */scancode = 0x00d9;break;
192                 case 24:/*F12 */scancode = 0x00da;break;
193                 /* FIXME: Shift-Fx */
194                 default:
195                         FIXME("parse ESC[%d~\n",subid);
196                         break;
197                 }
198                 break;
199             case 'A': /* Cursor Up    */scancode = 0xe048;break;
200             case 'B': /* Cursor Down  */scancode = 0xe050;break;
201             case 'D': /* Cursor Left  */scancode = 0xe04b;break;
202             case 'C': /* Cursor Right */scancode = 0xe04d;break;
203             case 'F': /* End          */scancode = 0xe04f;break;
204             case 'H': /* Home         */scancode = 0xe047;break;
205             case 'M':
206                 /* Mouse Button Press  (ESCM<button+'!'><x+'!'><y+'!'>) or
207                  *              Release (ESCM#<x+'!'><y+'!'>
208                  */
209                 if (k<len-3) {
210                     ir.EventType                        = MOUSE_EVENT;
211                     ir.Event.MouseEvent.dwMousePosition.x = buf[k+2]-'!';
212                     ir.Event.MouseEvent.dwMousePosition.y = buf[k+3]-'!';
213                     if (buf[k+1]=='#')
214                         ir.Event.MouseEvent.dwButtonState = 0;
215                     else
216                         ir.Event.MouseEvent.dwButtonState = 1<<(buf[k+1]-' ');
217                     ir.Event.MouseEvent.dwEventFlags      = 0; /* FIXME */
218                     assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk));
219                     j=k+3;
220                 }
221                 break;
222             case 'c':
223                 j=k;
224                 break;
225             }
226             if (scancode) {
227                 ir.Event.KeyEvent.wVirtualScanCode = scancode;
228                 ir.Event.KeyEvent.wVirtualKeyCode = MapVirtualKey16(scancode,1);
229                 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
230                 ir.Event.KeyEvent.bKeyDown              = 0;
231                 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
232                 j=k;
233                 continue;
234             }
235         }
236     }
237 }
238
239 /****************************************************************************
240  *              CONSOLE_get_input               (internal)
241  *
242  * Reads (nonblocking) as much input events as possible and stores them
243  * in an internal queue.
244  */
245 static void
246 CONSOLE_get_input( HANDLE handle, BOOL blockwait )
247 {
248     char        *buf = HeapAlloc(GetProcessHeap(),0,1);
249     int         len = 0, escape_seen = 0;
250
251     while (1)
252     {
253         DWORD res;
254         char inchar;
255
256         /* If we have at one time seen escape in this loop, we are 
257          * within an Escape sequence, so wait for a bit more input for the
258          * rest of the loop.
259          */
260         if (WaitForSingleObject( handle, escape_seen*10 )) break;
261         if (!ReadFile( handle, &inchar, 1, &res, NULL )) break;
262         if (!res) /* res 0 but readable means EOF? Hmm. */
263                 break;
264         buf = HeapReAlloc(GetProcessHeap(),0,buf,len+1);
265         buf[len++]=inchar;
266         if (inchar == 27) {
267                 if (len>1) {
268                         /* If we spot an ESC, we flush all up to it
269                          * since we can be sure that we have a complete
270                          * sequence.
271                          */
272                         CONSOLE_string_to_IR(handle,buf,len-1);
273                         buf = HeapReAlloc(GetProcessHeap(),0,buf,1);
274                         buf[0] = 27;
275                         len = 1;
276                 }
277                 escape_seen = 1;
278         }
279     }
280     CONSOLE_string_to_IR(handle,buf,len);
281     HeapFree(GetProcessHeap(),0,buf);
282 }
283
284 /******************************************************************************
285  * SetConsoleCtrlHandler [KERNEL32.459]  Adds function to calling process list
286  *
287  * PARAMS
288  *    func [I] Address of handler function
289  *    add  [I] Handler to add or remove
290  *
291  * RETURNS
292  *    Success: TRUE
293  *    Failure: FALSE
294  *
295  * CHANGED
296  * James Sutherland (JamesSutherland@gmx.de)
297  * Added global variables console_ignore_ctrl_c and handlers[]
298  * Does not yet do any error checking, or set LastError if failed.
299  * This doesn't yet matter, since these handlers are not yet called...!
300  */
301 static unsigned int console_ignore_ctrl_c = 0;
302 static HANDLER_ROUTINE *handlers[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
303 BOOL WINAPI SetConsoleCtrlHandler( HANDLER_ROUTINE *func, BOOL add )
304 {
305   unsigned int alloc_loop = sizeof(handlers)/sizeof(HANDLER_ROUTINE *);
306   unsigned int done = 0;
307   FIXME("(%p,%i) - no error checking or testing yet\n", func, add);
308   if (!func)
309     {
310       console_ignore_ctrl_c = add;
311       return TRUE;
312     }
313   if (add)
314       {
315         for (;alloc_loop--;)
316           if (!handlers[alloc_loop] && !done)
317             {
318               handlers[alloc_loop] = func;
319               done++;
320             }
321         if (!done)
322            FIXME("Out of space on CtrlHandler table\n");
323         return(done);
324       }
325     else
326       {
327         for (;alloc_loop--;)
328           if (handlers[alloc_loop] == func && !done)
329             {
330               handlers[alloc_loop] = 0;
331               done++;
332             }
333         if (!done)
334            WARN("Attempt to remove non-installed CtrlHandler %p\n",
335                 func);
336         return (done);
337       }
338     return (done);
339 }
340
341
342 /******************************************************************************
343  * GenerateConsoleCtrlEvent [KERNEL32.275] Simulate a CTRL-C or CTRL-BREAK
344  *
345  * PARAMS
346  *    dwCtrlEvent        [I] Type of event
347  *    dwProcessGroupID   [I] Process group ID to send event to
348  *
349  * NOTES
350  *    Doesn't yet work...!
351  *
352  * RETURNS
353  *    Success: True
354  *    Failure: False (and *should* [but doesn't] set LastError)
355  */
356 BOOL WINAPI GenerateConsoleCtrlEvent( DWORD dwCtrlEvent,
357                                         DWORD dwProcessGroupID )
358 {
359   if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
360     {
361       ERR("invalid event %d for PGID %ld\n", 
362            (unsigned short)dwCtrlEvent, dwProcessGroupID );
363       return FALSE;
364     }
365   if (dwProcessGroupID == GetCurrentProcessId() )
366     {
367       FIXME("Attempt to send event %d to self - stub\n",
368              (unsigned short)dwCtrlEvent );
369       return FALSE;
370     }
371   FIXME("event %d to external PGID %ld - not implemented yet\n",
372          (unsigned short)dwCtrlEvent, dwProcessGroupID );
373   return FALSE;
374 }
375
376
377 /******************************************************************************
378  * CreateConsoleScreenBuffer [KERNEL32.151]  Creates a console screen buffer
379  *
380  * PARAMS
381  *    dwDesiredAccess    [I] Access flag
382  *    dwShareMode        [I] Buffer share mode
383  *    sa                 [I] Security attributes
384  *    dwFlags            [I] Type of buffer to create
385  *    lpScreenBufferData [I] Reserved
386  *
387  * NOTES
388  *    Should call SetLastError
389  *
390  * RETURNS
391  *    Success: Handle to new console screen buffer
392  *    Failure: INVALID_HANDLE_VALUE
393  */
394 HANDLE WINAPI CreateConsoleScreenBuffer( DWORD dwDesiredAccess,
395                 DWORD dwShareMode, LPSECURITY_ATTRIBUTES sa,
396                 DWORD dwFlags, LPVOID lpScreenBufferData )
397 {
398     FIXME("(%ld,%ld,%p,%ld,%p): stub\n",dwDesiredAccess,
399           dwShareMode, sa, dwFlags, lpScreenBufferData);
400     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
401     return INVALID_HANDLE_VALUE;
402 }
403
404
405 /***********************************************************************
406  *           GetConsoleScreenBufferInfo   (KERNEL32.190)
407  */
408 BOOL WINAPI GetConsoleScreenBufferInfo( HANDLE hConsoleOutput,
409                                           LPCONSOLE_SCREEN_BUFFER_INFO csbi )
410 {
411     csbi->dwSize.x = 80;
412     csbi->dwSize.y = 24;
413     csbi->dwCursorPosition.x = 0;
414     csbi->dwCursorPosition.y = 0;
415     csbi->wAttributes = 0;
416     csbi->srWindow.Left = 0;
417     csbi->srWindow.Right        = 79;
418     csbi->srWindow.Top  = 0;
419     csbi->srWindow.Bottom       = 23;
420     csbi->dwMaximumWindowSize.x = 80;
421     csbi->dwMaximumWindowSize.y = 24;
422     return TRUE;
423 }
424
425
426 /******************************************************************************
427  * SetConsoleActiveScreenBuffer [KERNEL32.623]  Sets buffer to current console
428  *
429  * RETURNS
430  *    Success: TRUE
431  *    Failure: FALSE
432  */
433 BOOL WINAPI SetConsoleActiveScreenBuffer(
434     HANDLE hConsoleOutput) /* [in] Handle to console screen buffer */
435 {
436     FIXME("(%x): stub\n", hConsoleOutput);
437     return FALSE;
438 }
439
440
441 /***********************************************************************
442  *            GetLargestConsoleWindowSize   (KERNEL32.226)
443  */
444 DWORD WINAPI GetLargestConsoleWindowSize( HANDLE hConsoleOutput )
445 {
446     return (DWORD)MAKELONG(80,24);
447 }
448
449 /***********************************************************************
450  *            FreeConsole (KERNEL32.267)
451  */
452 BOOL WINAPI FreeConsole(VOID)
453 {
454     return !server_call( REQ_FREE_CONSOLE );
455 }
456
457
458 /*************************************************************************
459  *              CONSOLE_OpenHandle
460  *
461  * Open a handle to the current process console.
462  */
463 HANDLE CONSOLE_OpenHandle( BOOL output, DWORD access, LPSECURITY_ATTRIBUTES sa )
464 {
465     int ret = -1;
466     struct open_console_request *req = get_req_buffer();
467
468     req->output  = output;
469     req->access  = access;
470     req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
471     SetLastError(0);
472     if (!server_call( REQ_OPEN_CONSOLE )) ret = req->handle;
473     return ret;
474 }
475
476
477 /*************************************************************************
478  *              CONSOLE_make_complex                    [internal]
479  *
480  * Turns a CONSOLE kernel object into a complex one.
481  * (switches from output/input using the terminal where WINE was started to 
482  * its own xterm).
483  * 
484  * This makes simple commandline tools pipeable, while complex commandline 
485  * tools work without getting messed up by debugoutput.
486  * 
487  * All other functions should work indedependend from this call.
488  *
489  * To test for complex console: pid == 0 -> simple, otherwise complex.
490  */
491 static BOOL CONSOLE_make_complex(HANDLE handle)
492 {
493         struct set_console_fd_request *req = get_req_buffer();
494         struct termios term;
495         char buf[256];
496         char c = '\0';
497         int i,xpid,master,slave,pty_handle;
498
499         if (CONSOLE_GetPid( handle )) return TRUE; /* already complex */
500
501         MESSAGE("Console: Making console complex (creating an xterm)...\n");
502
503         if (tcgetattr(0, &term) < 0) {
504                 /* ignore failure, or we can't run from a script */
505         }
506         term.c_lflag = ~(ECHO|ICANON);
507
508         if (wine_openpty(&master, &slave, NULL, &term, NULL) < 0)
509             return FALSE;
510
511         if ((xpid=fork()) == 0) {
512                 tcsetattr(slave, TCSADRAIN, &term);
513                 close( slave );
514                 sprintf(buf, "-Sxx%d", master);
515                 /* "-fn vga" for VGA font. Harmless if vga is not present:
516                  *  xterm: unable to open font "vga", trying "fixed".... 
517                  */
518                 execlp("xterm", "xterm", buf, "-fn","vga",NULL);
519                 ERR("error creating AllocConsole xterm\n");
520                 exit(1);
521         }
522         pty_handle = FILE_DupUnixHandle( slave, GENERIC_READ | GENERIC_WRITE );
523         close( master );
524         close( slave );
525         if (pty_handle == -1) return FALSE;
526
527         /* most xterms like to print their window ID when used with -S;
528          * read it and continue before the user has a chance...
529          */
530         for (i = 0; i < 10000; i++)
531         {
532             BOOL ok = ReadFile( pty_handle, &c, 1, NULL, NULL );
533             if (!ok && !c) usleep(100); /* wait for xterm to be created */
534             else if (c == '\n') break;
535         }
536         if (i == 10000)
537         {
538             ERR("can't read xterm WID\n");
539             CloseHandle( pty_handle );
540             return FALSE;
541         }
542         req->handle = handle;
543         req->file_handle = pty_handle;
544         req->pid = xpid;
545         server_call( REQ_SET_CONSOLE_FD );
546         CloseHandle( pty_handle );
547
548         /* enable mouseclicks */
549         strcpy( buf, "\033[?1001s\033[?1000h" );
550         WriteFile(handle,buf,strlen(buf),NULL,NULL);
551
552         strcpy( buf, "\033]2;" );
553         if (GetConsoleTitleA( buf + 4, sizeof(buf) - 5 ))
554         {
555             strcat( buf, "\a" );
556             WriteFile(handle,buf,strlen(buf),NULL,NULL);
557         }
558         return TRUE;
559
560 }
561
562
563 /***********************************************************************
564  *            AllocConsole (KERNEL32.103)
565  *
566  * creates an xterm with a pty to our program
567  */
568 BOOL WINAPI AllocConsole(VOID)
569 {
570     struct alloc_console_request *req = get_req_buffer();
571     HANDLE hStderr;
572     int handle_in, handle_out;
573
574     TRACE("()\n");
575     req->access  = GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE;
576     req->inherit = FALSE;
577     if (server_call( REQ_ALLOC_CONSOLE )) return FALSE;
578     handle_in = req->handle_in;
579     handle_out = req->handle_out;
580
581     if (!DuplicateHandle( GetCurrentProcess(), req->handle_out, GetCurrentProcess(), &hStderr,
582                           0, TRUE, DUPLICATE_SAME_ACCESS ))
583     {
584         CloseHandle( handle_in );
585         CloseHandle( handle_out );
586         FreeConsole();
587         return FALSE;
588     }
589
590     /* NT resets the STD_*_HANDLEs on console alloc */
591     SetStdHandle( STD_INPUT_HANDLE, handle_in );
592     SetStdHandle( STD_OUTPUT_HANDLE, handle_out );
593     SetStdHandle( STD_ERROR_HANDLE, hStderr );
594
595     SetLastError(ERROR_SUCCESS);
596     SetConsoleTitleA("Wine Console");
597     return TRUE;
598 }
599
600
601 /******************************************************************************
602  * GetConsoleCP [KERNEL32.295]  Returns the OEM code page for the console
603  *
604  * RETURNS
605  *    Code page code
606  */
607 UINT WINAPI GetConsoleCP(VOID)
608 {
609     return GetACP();
610 }
611
612
613 /***********************************************************************
614  *            GetConsoleOutputCP   (KERNEL32.189)
615  */
616 UINT WINAPI GetConsoleOutputCP(VOID)
617 {
618     return GetConsoleCP();
619 }
620
621 /***********************************************************************
622  *            GetConsoleMode   (KERNEL32.188)
623  */
624 BOOL WINAPI GetConsoleMode(HANDLE hcon,LPDWORD mode)
625 {
626     BOOL ret = FALSE;
627     struct get_console_mode_request *req = get_req_buffer();
628     req->handle = hcon;
629     if (!server_call( REQ_GET_CONSOLE_MODE ))
630     {
631         if (mode) *mode = req->mode;
632         ret = TRUE;
633     }
634     return ret;
635 }
636
637
638 /******************************************************************************
639  * SetConsoleMode [KERNEL32.628]  Sets input mode of console's input buffer
640  *
641  * PARAMS
642  *    hcon [I] Handle to console input or screen buffer
643  *    mode [I] Input or output mode to set
644  *
645  * RETURNS
646  *    Success: TRUE
647  *    Failure: FALSE
648  */
649 BOOL WINAPI SetConsoleMode( HANDLE hcon, DWORD mode )
650 {
651     struct set_console_mode_request *req = get_req_buffer();
652     req->handle = hcon;
653     req->mode = mode;
654     return !server_call( REQ_SET_CONSOLE_MODE );
655 }
656
657
658 /***********************************************************************
659  *            GetConsoleTitleA   (KERNEL32.191)
660  */
661 DWORD WINAPI GetConsoleTitleA(LPSTR title,DWORD size)
662 {
663     struct get_console_info_request *req = get_req_buffer();
664     DWORD ret = 0;
665     HANDLE hcon;
666
667     if ((hcon = CreateFileA( "CONOUT$", GENERIC_READ, 0, NULL,
668                                OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
669         return 0;
670     req->handle = hcon;
671     if (!server_call( REQ_GET_CONSOLE_INFO ))
672     {
673         lstrcpynA( title, req->title, size );
674         ret = strlen(req->title);
675     }
676     CloseHandle( hcon );
677     return ret;
678 }
679
680
681 /******************************************************************************
682  * GetConsoleTitleW [KERNEL32.192]  Retrieves title string for console
683  *
684  * PARAMS
685  *    title [O] Address of buffer for title
686  *    size  [I] Size of buffer
687  *
688  * RETURNS
689  *    Success: Length of string copied
690  *    Failure: 0
691  */
692 DWORD WINAPI GetConsoleTitleW( LPWSTR title, DWORD size )
693 {
694     char *tmp;
695     DWORD ret;
696
697     if (!(tmp = HeapAlloc( GetProcessHeap(), 0, size ))) return 0;
698     ret = GetConsoleTitleA( tmp, size );
699     lstrcpyAtoW( title, tmp );
700     HeapFree( GetProcessHeap(), 0, tmp );
701     return ret;
702 }
703
704
705 /***********************************************************************
706  *            WriteConsoleA   (KERNEL32.729)
707  */
708 BOOL WINAPI WriteConsoleA( HANDLE hConsoleOutput,
709                                LPCVOID lpBuffer,
710                                DWORD nNumberOfCharsToWrite,
711                                LPDWORD lpNumberOfCharsWritten,
712                                LPVOID lpReserved )
713 {
714         /* FIXME: should I check if this is a console handle? */
715         return WriteFile(hConsoleOutput, lpBuffer, nNumberOfCharsToWrite,
716                          lpNumberOfCharsWritten, NULL);
717 }
718
719
720 #define CADD(c)                                                         \
721         if (bufused==curbufsize-1)                                      \
722             buffer = HeapReAlloc(GetProcessHeap(),0,buffer,(curbufsize+=100));\
723         buffer[bufused++]=c;
724 #define SADD(s) { char *x=s;while (*x) {CADD(*x);x++;}}
725
726 /***********************************************************************
727  *            WriteConsoleOutputA   (KERNEL32.732)
728  */
729 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput,
730                                      LPCHAR_INFO lpBuffer,
731                                      COORD dwBufferSize,
732                                      COORD dwBufferCoord,
733                                      LPSMALL_RECT lpWriteRegion)
734 {
735     int i,j,off=0,lastattr=-1;
736     int offbase;
737     char        sbuf[20],*buffer=NULL;
738     int         bufused=0,curbufsize = 100;
739     DWORD       res;
740     CONSOLE_SCREEN_BUFFER_INFO csbi;
741     const int colormap[8] = {
742         0,4,2,6,
743         1,5,3,7,
744     };
745     CONSOLE_make_complex(hConsoleOutput);
746     buffer = HeapAlloc(GetProcessHeap(),0,curbufsize);
747     offbase = (dwBufferCoord.y - 1) * dwBufferSize.x +
748               (dwBufferCoord.x - lpWriteRegion->Left);
749
750     TRACE("orig rect top = %d, bottom=%d, left=%d, right=%d\n",
751         lpWriteRegion->Top,
752         lpWriteRegion->Bottom,
753         lpWriteRegion->Left,
754         lpWriteRegion->Right
755     );
756
757     GetConsoleScreenBufferInfo(hConsoleOutput, &csbi);
758     sprintf(sbuf,"%c7",27);SADD(sbuf);
759
760     /* Step 1. Make (Bottom,Right) offset of intersection with
761        Screen Buffer                                              */
762     lpWriteRegion->Bottom = min(lpWriteRegion->Bottom, csbi.dwSize.y-1) - 
763                                 lpWriteRegion->Top;
764     lpWriteRegion->Right = min(lpWriteRegion->Right, csbi.dwSize.x-1) -
765                                 lpWriteRegion->Left;
766
767     /* Step 2. If either offset is negative, then no action 
768        should be performed. (Implies that requested rectangle is
769        outside the current screen buffer rectangle.)              */
770     if ((lpWriteRegion->Bottom < 0) ||
771         (lpWriteRegion->Right < 0)) {
772         /* readjust (Bottom Right) for rectangle */
773         lpWriteRegion->Bottom += lpWriteRegion->Top;
774         lpWriteRegion->Right += lpWriteRegion->Left;
775
776         TRACE("invisible rect top = %d, bottom=%d, left=%d, right=%d\n",
777             lpWriteRegion->Top,
778             lpWriteRegion->Bottom,
779             lpWriteRegion->Left,
780             lpWriteRegion->Right
781         );
782
783         HeapFree(GetProcessHeap(),0,buffer);
784         return TRUE;
785     }
786
787     /* Step 3. Intersect with source rectangle                    */
788     lpWriteRegion->Bottom = lpWriteRegion->Top - dwBufferCoord.y +
789              min(lpWriteRegion->Bottom + dwBufferCoord.y, dwBufferSize.y-1);
790     lpWriteRegion->Right = lpWriteRegion->Left - dwBufferCoord.x +
791              min(lpWriteRegion->Right + dwBufferCoord.x, dwBufferSize.x-1);
792
793     TRACE("clipped rect top = %d, bottom=%d, left=%d,right=%d\n",
794         lpWriteRegion->Top,
795         lpWriteRegion->Bottom,
796         lpWriteRegion->Left,
797         lpWriteRegion->Right
798     );
799
800     /* Validate above computations made sense, if not then issue
801        error and fudge to single character rectangle                  */
802     if ((lpWriteRegion->Bottom < lpWriteRegion->Top) ||
803         (lpWriteRegion->Right < lpWriteRegion->Left)) {
804        ERR("Invalid clipped rectangle top = %d, bottom=%d, left=%d,right=%d\n",
805               lpWriteRegion->Top,
806               lpWriteRegion->Bottom,
807               lpWriteRegion->Left,
808               lpWriteRegion->Right
809           );
810        lpWriteRegion->Bottom = lpWriteRegion->Top;
811        lpWriteRegion->Right = lpWriteRegion->Left;
812     }
813
814     /* Now do the real processing and move the characters    */
815     for (i=lpWriteRegion->Top;i<=lpWriteRegion->Bottom;i++) {
816         offbase += dwBufferSize.x;
817         sprintf(sbuf,"%c[%d;%dH",27,i+1,lpWriteRegion->Left+1);
818         SADD(sbuf);
819         for (j=lpWriteRegion->Left;j<=lpWriteRegion->Right;j++) {
820             off = j + offbase;
821             if (lastattr!=lpBuffer[off].Attributes) {
822                 lastattr = lpBuffer[off].Attributes;
823                 sprintf(sbuf,"%c[0;%s3%d;4%dm",
824                         27,
825                         (lastattr & FOREGROUND_INTENSITY)?"1;":"",
826                         colormap[lastattr&7],
827                         colormap[(lastattr&0x70)>>4]
828                 );
829                 /* FIXME: BACKGROUND_INTENSITY */
830                 SADD(sbuf);
831             }
832             CADD(lpBuffer[off].Char.AsciiChar);
833         }
834     }
835     sprintf(sbuf,"%c[0m%c8",27,27);SADD(sbuf);
836     WriteFile(hConsoleOutput,buffer,bufused,&res,NULL);
837     HeapFree(GetProcessHeap(),0,buffer);
838     return TRUE;
839 }
840
841 /***********************************************************************
842  *            WriteConsoleW   (KERNEL32.577)
843  */
844 BOOL WINAPI WriteConsoleW( HANDLE hConsoleOutput,
845                                LPCVOID lpBuffer,
846                                DWORD nNumberOfCharsToWrite,
847                                LPDWORD lpNumberOfCharsWritten,
848                                LPVOID lpReserved )
849 {
850         BOOL ret;
851         LPSTR xstring;
852         DWORD n;
853
854         n = WideCharToMultiByte(CP_ACP,0,lpBuffer,nNumberOfCharsToWrite,NULL,0,NULL,NULL);
855         xstring=HeapAlloc( GetProcessHeap(), 0, n );
856
857         n = WideCharToMultiByte(CP_ACP,0,lpBuffer,nNumberOfCharsToWrite,xstring,n,NULL,NULL);
858
859         /* FIXME: should I check if this is a console handle? */
860         ret= WriteFile(hConsoleOutput, xstring, n,
861                          lpNumberOfCharsWritten, NULL);
862         /* FIXME: lpNumberOfCharsWritten should be converted to numofchars in UNICODE */ 
863         HeapFree( GetProcessHeap(), 0, xstring );
864         return ret;
865 }
866
867
868 /***********************************************************************
869  *            ReadConsoleA   (KERNEL32.419)
870  */
871 BOOL WINAPI ReadConsoleA( HANDLE hConsoleInput,
872                               LPVOID lpBuffer,
873                               DWORD nNumberOfCharsToRead,
874                               LPDWORD lpNumberOfCharsRead,
875                               LPVOID lpReserved )
876 {
877     int         charsread = 0;
878     LPSTR       xbuf = (LPSTR)lpBuffer;
879     LPINPUT_RECORD      ir;
880
881     TRACE("(%d,%p,%ld,%p,%p)\n",
882             hConsoleInput,lpBuffer,nNumberOfCharsToRead,
883             lpNumberOfCharsRead,lpReserved
884     );
885
886     CONSOLE_get_input(hConsoleInput,FALSE);
887
888     /* FIXME: should we read at least 1 char? The SDK does not say */
889     while (charsread<nNumberOfCharsToRead)
890     {
891         struct read_console_input_request *req = get_req_buffer();
892         req->handle = hConsoleInput;
893         req->count = 1;
894         req->flush = 1;
895         if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
896         if (!req->read) break;
897         ir = (LPINPUT_RECORD)(req+1);
898         if (!ir->Event.KeyEvent.bKeyDown)
899                 continue;
900         if (ir->EventType != KEY_EVENT)
901                 continue;
902         *xbuf++ = ir->Event.KeyEvent.uChar.AsciiChar; 
903         charsread++;
904     }
905     if (lpNumberOfCharsRead)
906         *lpNumberOfCharsRead = charsread;
907     return TRUE;
908 }
909
910 /***********************************************************************
911  *            ReadConsoleW   (KERNEL32.427)
912  */
913 BOOL WINAPI ReadConsoleW( HANDLE hConsoleInput,
914                               LPVOID lpBuffer,
915                               DWORD nNumberOfCharsToRead,
916                               LPDWORD lpNumberOfCharsRead,
917                               LPVOID lpReserved )
918 {
919     BOOL ret;
920     LPSTR buf = (LPSTR)HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead);
921
922     ret = ReadConsoleA(
923         hConsoleInput,
924         buf,
925         nNumberOfCharsToRead,
926         lpNumberOfCharsRead,
927         lpReserved
928     );
929     if (ret)
930         lstrcpynAtoW(lpBuffer,buf,nNumberOfCharsToRead);
931     HeapFree( GetProcessHeap(), 0, buf );
932     return ret;
933 }
934
935
936 /******************************************************************************
937  * ReadConsoleInputA [KERNEL32.569]  Reads data from a console
938  *
939  * PARAMS
940  *    hConsoleInput        [I] Handle to console input buffer
941  *    lpBuffer             [O] Address of buffer for read data
942  *    nLength              [I] Number of records to read
943  *    lpNumberOfEventsRead [O] Address of number of records read
944  *
945  * RETURNS
946  *    Success: TRUE
947  *    Failure: FALSE
948  */
949 BOOL WINAPI ReadConsoleInputA(HANDLE hConsoleInput, LPINPUT_RECORD lpBuffer,
950                               DWORD nLength, LPDWORD lpNumberOfEventsRead)
951 {
952     struct read_console_input_request *req = get_req_buffer();
953
954     /* loop until we get at least one event */
955     for (;;)
956     {
957         req->handle = hConsoleInput;
958         req->count = nLength;
959         req->flush = 1;
960         if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
961         if (req->read)
962         {
963             memcpy( lpBuffer, req + 1, req->read * sizeof(*lpBuffer) );
964             if (lpNumberOfEventsRead) *lpNumberOfEventsRead = req->read;
965             return TRUE;
966         }
967         CONSOLE_get_input(hConsoleInput,TRUE);
968         /*WaitForSingleObject( hConsoleInput, INFINITE32 );*/
969     }
970 }
971
972
973 /***********************************************************************
974  *            ReadConsoleInputW   (KERNEL32.570)
975  */
976 BOOL WINAPI ReadConsoleInputW( HANDLE handle, LPINPUT_RECORD buffer,
977                                    DWORD count, LPDWORD read )
978 {
979     /* FIXME: Fix this if we get UNICODE input. */
980     return ReadConsoleInputA( handle, buffer, count, read );
981 }
982
983
984 /***********************************************************************
985  *            FlushConsoleInputBuffer   (KERNEL32.132)
986  */
987 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
988 {
989     struct read_console_input_request *req = get_req_buffer();
990     req->handle = handle;
991     req->count = -1;  /* get all records */
992     req->flush = 1;
993     return !server_call( REQ_READ_CONSOLE_INPUT );
994 }
995
996
997 /***********************************************************************
998  *            PeekConsoleInputA   (KERNEL32.550)
999  *
1000  * Gets 'count' first events (or less) from input queue.
1001  *
1002  * Does not need a complex console.
1003  */
1004 BOOL WINAPI PeekConsoleInputA( HANDLE handle, LPINPUT_RECORD buffer,
1005                                    DWORD count, LPDWORD read )
1006 {
1007     struct read_console_input_request *req = get_req_buffer();
1008
1009     CONSOLE_get_input(handle,FALSE);
1010
1011     req->handle = handle;
1012     req->count = count;
1013     req->flush = 0;
1014     if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
1015     if (req->read) memcpy( buffer, req + 1, req->read * sizeof(*buffer) );
1016     if (read) *read = req->read;
1017     return TRUE;
1018 }
1019
1020
1021 /***********************************************************************
1022  *            PeekConsoleInputW   (KERNEL32.551)
1023  */
1024 BOOL WINAPI PeekConsoleInputW(HANDLE hConsoleInput,
1025                                   LPINPUT_RECORD pirBuffer,
1026                                   DWORD cInRecords,
1027                                   LPDWORD lpcRead)
1028 {
1029     /* FIXME: Hmm. Fix this if we get UNICODE input. */
1030     return PeekConsoleInputA(hConsoleInput,pirBuffer,cInRecords,lpcRead);
1031 }
1032
1033
1034 /******************************************************************************
1035  * WriteConsoleInputA [KERNEL32.730]  Write data to a console input buffer
1036  *
1037  */
1038 BOOL WINAPI WriteConsoleInputA( HANDLE handle, INPUT_RECORD *buffer,
1039                                 DWORD count, LPDWORD written )
1040 {
1041     struct write_console_input_request *req = get_req_buffer();
1042     const DWORD max = server_remaining( req + 1 ) / sizeof(INPUT_RECORD);
1043
1044     if (written) *written = 0;
1045     while (count)
1046     {
1047         DWORD len = count < max ? count : max;
1048         req->count = len;
1049         req->handle = handle;
1050         memcpy( req + 1, buffer, len * sizeof(*buffer) );
1051         if (server_call( REQ_WRITE_CONSOLE_INPUT )) return FALSE;
1052         if (written) *written += req->written;
1053         count -= len;
1054         buffer += len;
1055     }
1056     return TRUE;
1057 }
1058
1059
1060 /***********************************************************************
1061  *            SetConsoleTitleA   (KERNEL32.476)
1062  *
1063  * Sets the console title.
1064  *
1065  * We do not necessarily need to create a complex console for that,
1066  * but should remember the title and set it on creation of the latter.
1067  * (not fixed at this time).
1068  */
1069 BOOL WINAPI SetConsoleTitleA(LPCSTR title)
1070 {
1071     struct set_console_info_request *req = get_req_buffer();
1072     HANDLE hcon;
1073     DWORD written;
1074
1075     if ((hcon = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, NULL,
1076                                OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
1077         return FALSE;
1078     req->handle = hcon;
1079     req->mask = SET_CONSOLE_INFO_TITLE;
1080     lstrcpynA( req->title, title, server_remaining(req->title) );
1081     if (server_call( REQ_SET_CONSOLE_INFO )) goto error;
1082     if (CONSOLE_GetPid( hcon ))
1083     {
1084         /* only set title for complex console (own xterm) */
1085         WriteFile( hcon, "\033]2;", 4, &written, NULL );
1086         WriteFile( hcon, title, strlen(title), &written, NULL );
1087         WriteFile( hcon, "\a", 1, &written, NULL );
1088     }
1089     CloseHandle( hcon );
1090     return TRUE;
1091  error:
1092     CloseHandle( hcon );
1093     return FALSE;
1094 }
1095
1096
1097 /******************************************************************************
1098  * SetConsoleTitleW [KERNEL32.477]  Sets title bar string for console
1099  *
1100  * PARAMS
1101  *    title [I] Address of new title
1102  *
1103  * NOTES
1104  *    This should not be calling the A version
1105  *
1106  * RETURNS
1107  *    Success: TRUE
1108  *    Failure: FALSE
1109  */
1110 BOOL WINAPI SetConsoleTitleW( LPCWSTR title )
1111 {
1112     BOOL ret;
1113
1114     LPSTR titleA = HEAP_strdupWtoA( GetProcessHeap(), 0, title );
1115     ret = SetConsoleTitleA(titleA);
1116     HeapFree( GetProcessHeap(), 0, titleA );
1117     return ret;
1118 }
1119
1120 /******************************************************************************
1121  * SetConsoleCursorPosition [KERNEL32.627]
1122  * Sets the cursor position in console
1123  *
1124  * PARAMS
1125  *    hConsoleOutput   [I] Handle of console screen buffer
1126  *    dwCursorPosition [I] New cursor position coordinates
1127  *
1128  * RETURNS STD
1129  */
1130 BOOL WINAPI SetConsoleCursorPosition( HANDLE hcon, COORD pos )
1131 {
1132     char        xbuf[20];
1133     DWORD       xlen;
1134
1135     /* make console complex only if we change lines, not just in the line */
1136     if (pos.y)
1137         CONSOLE_make_complex(hcon);
1138
1139     TRACE("%d (%dx%d)\n", hcon, pos.x , pos.y );
1140     /* x are columns, y rows */
1141     if (pos.y) 
1142         /* full screen cursor absolute positioning */
1143         sprintf(xbuf,"%c[%d;%dH", 0x1B, pos.y+1, pos.x+1);
1144     else
1145         /* relative cursor positioning in line (\r to go to 0) */
1146         sprintf(xbuf,"\r%c[%dC", 0x1B, pos.x);
1147     /* FIXME: store internal if we start using own console buffers */
1148     WriteFile(hcon,xbuf,strlen(xbuf),&xlen,NULL);
1149     return TRUE;
1150 }
1151
1152 /***********************************************************************
1153  *            GetNumberOfConsoleInputEvents   (KERNEL32.246)
1154  */
1155 BOOL WINAPI GetNumberOfConsoleInputEvents(HANDLE hcon,LPDWORD nrofevents)
1156 {
1157     struct read_console_input_request *req = get_req_buffer();
1158
1159     CONSOLE_get_input(hcon,FALSE);
1160
1161     req->handle = hcon;
1162     req->count = -1;
1163     req->flush = 0;
1164     if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
1165     if (nrofevents) *nrofevents = req->read;
1166     return TRUE;
1167 }
1168
1169 /***********************************************************************
1170  *            GetNumberOfConsoleMouseButtons   (KERNEL32.358)
1171  */
1172 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1173 {
1174     FIXME("(%p): stub\n", nrofbuttons);
1175     *nrofbuttons = 2;
1176     return TRUE;
1177 }
1178
1179 /******************************************************************************
1180  * GetConsoleCursorInfo [KERNEL32.296]  Gets size and visibility of console
1181  *
1182  * PARAMS
1183  *    hcon  [I] Handle to console screen buffer
1184  *    cinfo [O] Address of cursor information
1185  *
1186  * RETURNS
1187  *    Success: TRUE
1188  *    Failure: FALSE
1189  */
1190 BOOL WINAPI GetConsoleCursorInfo( HANDLE hcon, LPCONSOLE_CURSOR_INFO cinfo )
1191 {
1192     struct get_console_info_request *req = get_req_buffer();
1193     req->handle = hcon;
1194     if (server_call( REQ_GET_CONSOLE_INFO )) return FALSE;
1195     if (cinfo)
1196     {
1197         cinfo->dwSize = req->cursor_size;
1198         cinfo->bVisible = req->cursor_visible;
1199     }
1200     return TRUE;
1201 }
1202
1203
1204 /******************************************************************************
1205  * SetConsoleCursorInfo [KERNEL32.626]  Sets size and visibility of cursor
1206  *
1207  * RETURNS
1208  *    Success: TRUE
1209  *    Failure: FALSE
1210  */
1211 BOOL WINAPI SetConsoleCursorInfo( 
1212     HANDLE hcon,                /* [in] Handle to console screen buffer */
1213     LPCONSOLE_CURSOR_INFO cinfo)  /* [in] Address of cursor information */
1214 {
1215     struct set_console_info_request *req = get_req_buffer();
1216     char        buf[8];
1217     DWORD       xlen;
1218
1219     CONSOLE_make_complex(hcon);
1220     sprintf(buf,"\033[?25%c",cinfo->bVisible?'h':'l');
1221     WriteFile(hcon,buf,strlen(buf),&xlen,NULL);
1222
1223     req->handle         = hcon;
1224     req->cursor_size    = cinfo->dwSize;
1225     req->cursor_visible = cinfo->bVisible;
1226     req->mask           = SET_CONSOLE_INFO_CURSOR;
1227     return !server_call( REQ_SET_CONSOLE_INFO );
1228 }
1229
1230
1231 /******************************************************************************
1232  * SetConsoleWindowInfo [KERNEL32.634]  Sets size and position of console
1233  *
1234  * RETURNS
1235  *    Success: TRUE
1236  *    Failure: FALSE
1237  */
1238 BOOL WINAPI SetConsoleWindowInfo(
1239     HANDLE hcon,       /* [in] Handle to console screen buffer */
1240     BOOL bAbsolute,    /* [in] Coordinate type flag */
1241     LPSMALL_RECT window) /* [in] Address of new window rectangle */
1242 {
1243     FIXME("(%x,%d,%p): stub\n", hcon, bAbsolute, window);
1244     return TRUE;
1245 }
1246
1247
1248 /******************************************************************************
1249  * SetConsoleTextAttribute [KERNEL32.631]  Sets colors for text
1250  *
1251  * Sets the foreground and background color attributes of characters
1252  * written to the screen buffer.
1253  *
1254  * RETURNS
1255  *    Success: TRUE
1256  *    Failure: FALSE
1257  */
1258 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput,WORD wAttr)
1259 {
1260     const int colormap[8] = {
1261         0,4,2,6,
1262         1,5,3,7,
1263     };
1264     DWORD xlen;
1265     char buffer[20];
1266
1267     TRACE("(%d,%d)\n",hConsoleOutput,wAttr);
1268     sprintf(buffer,"%c[0;%s3%d;4%dm",
1269         27,
1270         (wAttr & FOREGROUND_INTENSITY)?"1;":"",
1271         colormap[wAttr&7],
1272         colormap[(wAttr&0x70)>>4]
1273     );
1274     WriteFile(hConsoleOutput,buffer,strlen(buffer),&xlen,NULL);
1275     return TRUE;
1276 }
1277
1278
1279 /******************************************************************************
1280  * SetConsoleScreenBufferSize [KERNEL32.630]  Changes size of console 
1281  *
1282  * PARAMS
1283  *    hConsoleOutput [I] Handle to console screen buffer
1284  *    dwSize         [I] New size in character rows and cols
1285  *
1286  * RETURNS
1287  *    Success: TRUE
1288  *    Failure: FALSE
1289  */
1290 BOOL WINAPI SetConsoleScreenBufferSize( HANDLE hConsoleOutput, 
1291                                           COORD dwSize )
1292 {
1293     FIXME("(%d,%dx%d): stub\n",hConsoleOutput,dwSize.x,dwSize.y);
1294     return TRUE;
1295 }
1296
1297
1298 /******************************************************************************
1299  * FillConsoleOutputCharacterA [KERNEL32.242]
1300  *
1301  * PARAMS
1302  *    hConsoleOutput    [I] Handle to screen buffer
1303  *    cCharacter        [I] Character to write
1304  *    nLength           [I] Number of cells to write to
1305  *    dwCoord           [I] Coords of first cell
1306  *    lpNumCharsWritten [O] Pointer to number of cells written
1307  *
1308  * RETURNS
1309  *    Success: TRUE
1310  *    Failure: FALSE
1311  */
1312 BOOL WINAPI FillConsoleOutputCharacterA(
1313     HANDLE hConsoleOutput,
1314     BYTE cCharacter,
1315     DWORD nLength,
1316     COORD dwCoord,
1317     LPDWORD lpNumCharsWritten)
1318 {
1319     long        count;
1320     DWORD       xlen;
1321
1322     SetConsoleCursorPosition(hConsoleOutput,dwCoord);
1323     for(count=0;count<nLength;count++)
1324         WriteFile(hConsoleOutput,&cCharacter,1,&xlen,NULL);
1325     *lpNumCharsWritten = nLength;
1326     return TRUE;
1327 }
1328
1329
1330 /******************************************************************************
1331  * FillConsoleOutputCharacterW [KERNEL32.243]  Writes characters to console
1332  *
1333  * PARAMS
1334  *    hConsoleOutput    [I] Handle to screen buffer
1335  *    cCharacter        [I] Character to write
1336  *    nLength           [I] Number of cells to write to
1337  *    dwCoord           [I] Coords of first cell
1338  *    lpNumCharsWritten [O] Pointer to number of cells written
1339  *
1340  * RETURNS
1341  *    Success: TRUE
1342  *    Failure: FALSE
1343  */
1344 BOOL WINAPI FillConsoleOutputCharacterW(HANDLE hConsoleOutput,
1345                                             WCHAR cCharacter,
1346                                             DWORD nLength,
1347                                            COORD dwCoord, 
1348                                             LPDWORD lpNumCharsWritten)
1349 {
1350     long        count;
1351     DWORD       xlen;
1352
1353     SetConsoleCursorPosition(hConsoleOutput,dwCoord);
1354     /* FIXME: not quite correct ... but the lower part of UNICODE char comes
1355      * first 
1356      */
1357     for(count=0;count<nLength;count++)
1358         WriteFile(hConsoleOutput,&cCharacter,1,&xlen,NULL);
1359     *lpNumCharsWritten = nLength;
1360     return TRUE;
1361 }
1362
1363
1364 /******************************************************************************
1365  * FillConsoleOutputAttribute [KERNEL32.241]  Sets attributes for console
1366  *
1367  * PARAMS
1368  *    hConsoleOutput    [I] Handle to screen buffer
1369  *    wAttribute        [I] Color attribute to write
1370  *    nLength           [I] Number of cells to write to
1371  *    dwCoord           [I] Coords of first cell
1372  *    lpNumAttrsWritten [O] Pointer to number of cells written
1373  *
1374  * RETURNS
1375  *    Success: TRUE
1376  *    Failure: FALSE
1377  */
1378 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, 
1379               WORD wAttribute, DWORD nLength, COORD dwCoord, 
1380               LPDWORD lpNumAttrsWritten)
1381 {
1382     FIXME("(%d,%d,%ld,%dx%d,%p): stub\n", hConsoleOutput,
1383           wAttribute,nLength,dwCoord.x,dwCoord.y,lpNumAttrsWritten);
1384     *lpNumAttrsWritten = nLength;
1385     return TRUE;
1386 }
1387
1388 /******************************************************************************
1389  * ReadConsoleOutputCharacterA [KERNEL32.573]
1390  * 
1391  * BUGS
1392  *   Unimplemented
1393  */
1394 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, 
1395               LPSTR lpstr, DWORD dword, COORD coord, LPDWORD lpdword)
1396 {
1397     FIXME("(%d,%p,%ld,%dx%d,%p): stub\n", hConsoleOutput,lpstr,
1398           dword,coord.x,coord.y,lpdword);
1399     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1400     return FALSE;
1401 }
1402
1403
1404 /******************************************************************************
1405  * ScrollConsoleScreenBufferA [KERNEL32.612]
1406  * 
1407  * BUGS
1408  *   Unimplemented
1409  */
1410 BOOL WINAPI ScrollConsoleScreenBufferA( HANDLE hConsoleOutput, 
1411               LPSMALL_RECT lpScrollRect, LPSMALL_RECT lpClipRect,
1412               COORD dwDestOrigin, LPCHAR_INFO lpFill)
1413 {
1414     FIXME("(%d,%p,%p,%dx%d,%p): stub\n", hConsoleOutput,lpScrollRect,
1415           lpClipRect,dwDestOrigin.x,dwDestOrigin.y,lpFill);
1416     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1417     return FALSE;
1418 }