Merged msacm and msacm32 dlls.
[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 COORD WINAPI GetLargestConsoleWindowSize( HANDLE hConsoleOutput )
445 {
446     COORD c;
447     c.X = 80;
448     c.Y = 24;
449     return c;
450 }
451
452 /* gcc doesn't return structures the same way as dwords */
453 DWORD WINAPI WIN32_GetLargestConsoleWindowSize( HANDLE hConsoleOutput )
454 {
455     COORD c = GetLargestConsoleWindowSize( hConsoleOutput );
456     return *(DWORD *)&c;
457 }
458
459 /***********************************************************************
460  *            FreeConsole (KERNEL32.267)
461  */
462 BOOL WINAPI FreeConsole(VOID)
463 {
464     return !server_call( REQ_FREE_CONSOLE );
465 }
466
467
468 /*************************************************************************
469  *              CONSOLE_OpenHandle
470  *
471  * Open a handle to the current process console.
472  */
473 HANDLE CONSOLE_OpenHandle( BOOL output, DWORD access, LPSECURITY_ATTRIBUTES sa )
474 {
475     int ret = -1;
476     struct open_console_request *req = get_req_buffer();
477
478     req->output  = output;
479     req->access  = access;
480     req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
481     SetLastError(0);
482     if (!server_call( REQ_OPEN_CONSOLE )) ret = req->handle;
483     return ret;
484 }
485
486
487 /*************************************************************************
488  *              CONSOLE_make_complex                    [internal]
489  *
490  * Turns a CONSOLE kernel object into a complex one.
491  * (switches from output/input using the terminal where WINE was started to 
492  * its own xterm).
493  * 
494  * This makes simple commandline tools pipeable, while complex commandline 
495  * tools work without getting messed up by debugoutput.
496  * 
497  * All other functions should work indedependend from this call.
498  *
499  * To test for complex console: pid == 0 -> simple, otherwise complex.
500  */
501 static BOOL CONSOLE_make_complex(HANDLE handle)
502 {
503         struct set_console_fd_request *req = get_req_buffer();
504         struct termios term;
505         char buf[256];
506         char c = '\0';
507         int i,xpid,master,slave,pty_handle;
508
509         if (CONSOLE_GetPid( handle )) return TRUE; /* already complex */
510
511         MESSAGE("Console: Making console complex (creating an xterm)...\n");
512
513         if (tcgetattr(0, &term) < 0) {
514                 /* ignore failure, or we can't run from a script */
515         }
516         term.c_lflag = ~(ECHO|ICANON);
517
518         if (wine_openpty(&master, &slave, NULL, &term, NULL) < 0)
519             return FALSE;
520
521         if ((xpid=fork()) == 0) {
522                 tcsetattr(slave, TCSADRAIN, &term);
523                 close( slave );
524                 sprintf(buf, "-Sxx%d", master);
525                 /* "-fn vga" for VGA font. Harmless if vga is not present:
526                  *  xterm: unable to open font "vga", trying "fixed".... 
527                  */
528                 execlp("xterm", "xterm", buf, "-fn","vga",NULL);
529                 ERR("error creating AllocConsole xterm\n");
530                 exit(1);
531         }
532         pty_handle = FILE_DupUnixHandle( slave, GENERIC_READ | GENERIC_WRITE );
533         close( master );
534         close( slave );
535         if (pty_handle == -1) return FALSE;
536
537         /* most xterms like to print their window ID when used with -S;
538          * read it and continue before the user has a chance...
539          */
540         for (i = 0; i < 10000; i++)
541         {
542             BOOL ok = ReadFile( pty_handle, &c, 1, NULL, NULL );
543             if (!ok && !c) usleep(100); /* wait for xterm to be created */
544             else if (c == '\n') break;
545         }
546         if (i == 10000)
547         {
548             ERR("can't read xterm WID\n");
549             CloseHandle( pty_handle );
550             return FALSE;
551         }
552         req->handle = handle;
553         req->file_handle = pty_handle;
554         req->pid = xpid;
555         server_call( REQ_SET_CONSOLE_FD );
556         CloseHandle( pty_handle );
557
558         /* enable mouseclicks */
559         strcpy( buf, "\033[?1001s\033[?1000h" );
560         WriteFile(handle,buf,strlen(buf),NULL,NULL);
561
562         strcpy( buf, "\033]2;" );
563         if (GetConsoleTitleA( buf + 4, sizeof(buf) - 5 ))
564         {
565             strcat( buf, "\a" );
566             WriteFile(handle,buf,strlen(buf),NULL,NULL);
567         }
568         return TRUE;
569
570 }
571
572
573 /***********************************************************************
574  *            AllocConsole (KERNEL32.103)
575  *
576  * creates an xterm with a pty to our program
577  */
578 BOOL WINAPI AllocConsole(VOID)
579 {
580     struct alloc_console_request *req = get_req_buffer();
581     HANDLE hStderr;
582     int handle_in, handle_out;
583
584     TRACE("()\n");
585     req->access  = GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE;
586     req->inherit = FALSE;
587     if (server_call( REQ_ALLOC_CONSOLE )) return FALSE;
588     handle_in = req->handle_in;
589     handle_out = req->handle_out;
590
591     if (!DuplicateHandle( GetCurrentProcess(), req->handle_out, GetCurrentProcess(), &hStderr,
592                           0, TRUE, DUPLICATE_SAME_ACCESS ))
593     {
594         CloseHandle( handle_in );
595         CloseHandle( handle_out );
596         FreeConsole();
597         return FALSE;
598     }
599
600     /* NT resets the STD_*_HANDLEs on console alloc */
601     SetStdHandle( STD_INPUT_HANDLE, handle_in );
602     SetStdHandle( STD_OUTPUT_HANDLE, handle_out );
603     SetStdHandle( STD_ERROR_HANDLE, hStderr );
604
605     SetLastError(ERROR_SUCCESS);
606     SetConsoleTitleA("Wine Console");
607     return TRUE;
608 }
609
610
611 /******************************************************************************
612  * GetConsoleCP [KERNEL32.295]  Returns the OEM code page for the console
613  *
614  * RETURNS
615  *    Code page code
616  */
617 UINT WINAPI GetConsoleCP(VOID)
618 {
619     return GetACP();
620 }
621
622
623 /***********************************************************************
624  *            GetConsoleOutputCP   (KERNEL32.189)
625  */
626 UINT WINAPI GetConsoleOutputCP(VOID)
627 {
628     return GetConsoleCP();
629 }
630
631 /***********************************************************************
632  *            GetConsoleMode   (KERNEL32.188)
633  */
634 BOOL WINAPI GetConsoleMode(HANDLE hcon,LPDWORD mode)
635 {
636     BOOL ret = FALSE;
637     struct get_console_mode_request *req = get_req_buffer();
638     req->handle = hcon;
639     if (!server_call( REQ_GET_CONSOLE_MODE ))
640     {
641         if (mode) *mode = req->mode;
642         ret = TRUE;
643     }
644     return ret;
645 }
646
647
648 /******************************************************************************
649  * SetConsoleMode [KERNEL32.628]  Sets input mode of console's input buffer
650  *
651  * PARAMS
652  *    hcon [I] Handle to console input or screen buffer
653  *    mode [I] Input or output mode to set
654  *
655  * RETURNS
656  *    Success: TRUE
657  *    Failure: FALSE
658  */
659 BOOL WINAPI SetConsoleMode( HANDLE hcon, DWORD mode )
660 {
661     struct set_console_mode_request *req = get_req_buffer();
662     req->handle = hcon;
663     req->mode = mode;
664     return !server_call( REQ_SET_CONSOLE_MODE );
665 }
666
667
668 /******************************************************************************
669  * SetConsoleOutputCP [KERNEL32.629]  Set the output codepage used by the console
670  *
671  * PARAMS
672  *    cp [I] code page to set
673  *
674  * RETURNS
675  *    Success: TRUE
676  *    Failure: FALSE
677  */
678 BOOL WINAPI SetConsoleOutputCP( UINT cp )
679 {
680     FIXME("stub\n");
681     return TRUE;
682 }
683
684
685 /***********************************************************************
686  *            GetConsoleTitleA   (KERNEL32.191)
687  */
688 DWORD WINAPI GetConsoleTitleA(LPSTR title,DWORD size)
689 {
690     struct get_console_info_request *req = get_req_buffer();
691     DWORD ret = 0;
692     HANDLE hcon;
693
694     if ((hcon = CreateFileA( "CONOUT$", GENERIC_READ, 0, NULL,
695                                OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
696         return 0;
697     req->handle = hcon;
698     if (!server_call( REQ_GET_CONSOLE_INFO ))
699     {
700         lstrcpynA( title, req->title, size );
701         ret = strlen(req->title);
702     }
703     CloseHandle( hcon );
704     return ret;
705 }
706
707
708 /******************************************************************************
709  * GetConsoleTitleW [KERNEL32.192]  Retrieves title string for console
710  *
711  * PARAMS
712  *    title [O] Address of buffer for title
713  *    size  [I] Size of buffer
714  *
715  * RETURNS
716  *    Success: Length of string copied
717  *    Failure: 0
718  */
719 DWORD WINAPI GetConsoleTitleW( LPWSTR title, DWORD size )
720 {
721     char *tmp;
722     DWORD ret;
723
724     if (!(tmp = HeapAlloc( GetProcessHeap(), 0, size ))) return 0;
725     ret = GetConsoleTitleA( tmp, size );
726     lstrcpyAtoW( title, tmp );
727     HeapFree( GetProcessHeap(), 0, tmp );
728     return ret;
729 }
730
731
732 /***********************************************************************
733  *            WriteConsoleA   (KERNEL32.729)
734  */
735 BOOL WINAPI WriteConsoleA( HANDLE hConsoleOutput,
736                                LPCVOID lpBuffer,
737                                DWORD nNumberOfCharsToWrite,
738                                LPDWORD lpNumberOfCharsWritten,
739                                LPVOID lpReserved )
740 {
741         /* FIXME: should I check if this is a console handle? */
742         return WriteFile(hConsoleOutput, lpBuffer, nNumberOfCharsToWrite,
743                          lpNumberOfCharsWritten, NULL);
744 }
745
746
747 #define CADD(c)                                                         \
748         if (bufused==curbufsize-1)                                      \
749             buffer = HeapReAlloc(GetProcessHeap(),0,buffer,(curbufsize+=100));\
750         buffer[bufused++]=c;
751 #define SADD(s) { char *x=s;while (*x) {CADD(*x);x++;}}
752
753 /***********************************************************************
754  *            WriteConsoleOutputA   (KERNEL32.732)
755  */
756 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput,
757                                      LPCHAR_INFO lpBuffer,
758                                      COORD dwBufferSize,
759                                      COORD dwBufferCoord,
760                                      LPSMALL_RECT lpWriteRegion)
761 {
762     int i,j,off=0,lastattr=-1;
763     int offbase;
764     char        sbuf[20],*buffer=NULL;
765     int         bufused=0,curbufsize = 100;
766     DWORD       res;
767     CONSOLE_SCREEN_BUFFER_INFO csbi;
768     const int colormap[8] = {
769         0,4,2,6,
770         1,5,3,7,
771     };
772     CONSOLE_make_complex(hConsoleOutput);
773     buffer = HeapAlloc(GetProcessHeap(),0,curbufsize);
774     offbase = (dwBufferCoord.Y - 1) * dwBufferSize.X +
775               (dwBufferCoord.X - lpWriteRegion->Left);
776
777     TRACE("orig rect top = %d, bottom=%d, left=%d, right=%d\n",
778         lpWriteRegion->Top,
779         lpWriteRegion->Bottom,
780         lpWriteRegion->Left,
781         lpWriteRegion->Right
782     );
783
784     GetConsoleScreenBufferInfo(hConsoleOutput, &csbi);
785     sprintf(sbuf,"%c7",27);SADD(sbuf);
786
787     /* Step 1. Make (Bottom,Right) offset of intersection with
788        Screen Buffer                                              */
789     lpWriteRegion->Bottom = min(lpWriteRegion->Bottom, csbi.dwSize.Y-1) - 
790                                 lpWriteRegion->Top;
791     lpWriteRegion->Right = min(lpWriteRegion->Right, csbi.dwSize.X-1) -
792                                 lpWriteRegion->Left;
793
794     /* Step 2. If either offset is negative, then no action 
795        should be performed. (Implies that requested rectangle is
796        outside the current screen buffer rectangle.)              */
797     if ((lpWriteRegion->Bottom < 0) ||
798         (lpWriteRegion->Right < 0)) {
799         /* readjust (Bottom Right) for rectangle */
800         lpWriteRegion->Bottom += lpWriteRegion->Top;
801         lpWriteRegion->Right += lpWriteRegion->Left;
802
803         TRACE("invisible rect top = %d, bottom=%d, left=%d, right=%d\n",
804             lpWriteRegion->Top,
805             lpWriteRegion->Bottom,
806             lpWriteRegion->Left,
807             lpWriteRegion->Right
808         );
809
810         HeapFree(GetProcessHeap(),0,buffer);
811         return TRUE;
812     }
813
814     /* Step 3. Intersect with source rectangle                    */
815     lpWriteRegion->Bottom = lpWriteRegion->Top - dwBufferCoord.Y +
816              min(lpWriteRegion->Bottom + dwBufferCoord.Y, dwBufferSize.Y-1);
817     lpWriteRegion->Right = lpWriteRegion->Left - dwBufferCoord.X +
818              min(lpWriteRegion->Right + dwBufferCoord.X, dwBufferSize.X-1);
819
820     TRACE("clipped rect top = %d, bottom=%d, left=%d,right=%d\n",
821         lpWriteRegion->Top,
822         lpWriteRegion->Bottom,
823         lpWriteRegion->Left,
824         lpWriteRegion->Right
825     );
826
827     /* Validate above computations made sense, if not then issue
828        error and fudge to single character rectangle                  */
829     if ((lpWriteRegion->Bottom < lpWriteRegion->Top) ||
830         (lpWriteRegion->Right < lpWriteRegion->Left)) {
831        ERR("Invalid clipped rectangle top = %d, bottom=%d, left=%d,right=%d\n",
832               lpWriteRegion->Top,
833               lpWriteRegion->Bottom,
834               lpWriteRegion->Left,
835               lpWriteRegion->Right
836           );
837        lpWriteRegion->Bottom = lpWriteRegion->Top;
838        lpWriteRegion->Right = lpWriteRegion->Left;
839     }
840
841     /* Now do the real processing and move the characters    */
842     for (i=lpWriteRegion->Top;i<=lpWriteRegion->Bottom;i++) {
843         offbase += dwBufferSize.X;
844         sprintf(sbuf,"%c[%d;%dH",27,i+1,lpWriteRegion->Left+1);
845         SADD(sbuf);
846         for (j=lpWriteRegion->Left;j<=lpWriteRegion->Right;j++) {
847             off = j + offbase;
848             if (lastattr!=lpBuffer[off].Attributes) {
849                 lastattr = lpBuffer[off].Attributes;
850                 sprintf(sbuf,"%c[0;%s3%d;4%dm",
851                         27,
852                         (lastattr & FOREGROUND_INTENSITY)?"1;":"",
853                         colormap[lastattr&7],
854                         colormap[(lastattr&0x70)>>4]
855                 );
856                 /* FIXME: BACKGROUND_INTENSITY */
857                 SADD(sbuf);
858             }
859             CADD(lpBuffer[off].Char.AsciiChar);
860         }
861     }
862     sprintf(sbuf,"%c[0m%c8",27,27);SADD(sbuf);
863     WriteFile(hConsoleOutput,buffer,bufused,&res,NULL);
864     HeapFree(GetProcessHeap(),0,buffer);
865     return TRUE;
866 }
867
868 /***********************************************************************
869  *            WriteConsoleOutputW   (KERNEL32.734)
870  */
871 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput,
872                                      LPCHAR_INFO lpBuffer,
873                                      COORD dwBufferSize,
874                                      COORD dwBufferCoord,
875                                      LPSMALL_RECT lpWriteRegion)
876 {
877     FIXME("(%d,%p,%dx%d,%dx%d,%p): stub\n", hConsoleOutput, lpBuffer,
878           dwBufferSize.X,dwBufferSize.Y,dwBufferCoord.X,dwBufferCoord.Y,lpWriteRegion);
879     
880     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
881     return FALSE;   
882 }
883
884 /***********************************************************************
885  *            WriteConsoleW   (KERNEL32.577)
886  */
887 BOOL WINAPI WriteConsoleW( HANDLE hConsoleOutput,
888                                LPCVOID lpBuffer,
889                                DWORD nNumberOfCharsToWrite,
890                                LPDWORD lpNumberOfCharsWritten,
891                                LPVOID lpReserved )
892 {
893         BOOL ret;
894         LPSTR xstring;
895         DWORD n;
896
897         n = WideCharToMultiByte(CP_ACP,0,lpBuffer,nNumberOfCharsToWrite,NULL,0,NULL,NULL);
898         xstring=HeapAlloc( GetProcessHeap(), 0, n );
899
900         n = WideCharToMultiByte(CP_ACP,0,lpBuffer,nNumberOfCharsToWrite,xstring,n,NULL,NULL);
901
902         /* FIXME: should I check if this is a console handle? */
903         ret= WriteFile(hConsoleOutput, xstring, n,
904                          lpNumberOfCharsWritten, NULL);
905         /* FIXME: lpNumberOfCharsWritten should be converted to numofchars in UNICODE */ 
906         HeapFree( GetProcessHeap(), 0, xstring );
907         return ret;
908 }
909
910
911 /***********************************************************************
912  *            ReadConsoleA   (KERNEL32.419)
913  */
914 BOOL WINAPI ReadConsoleA( HANDLE hConsoleInput,
915                               LPVOID lpBuffer,
916                               DWORD nNumberOfCharsToRead,
917                               LPDWORD lpNumberOfCharsRead,
918                               LPVOID lpReserved )
919 {
920     int         charsread = 0;
921     LPSTR       xbuf = (LPSTR)lpBuffer;
922     LPINPUT_RECORD      ir;
923
924     TRACE("(%d,%p,%ld,%p,%p)\n",
925             hConsoleInput,lpBuffer,nNumberOfCharsToRead,
926             lpNumberOfCharsRead,lpReserved
927     );
928
929     CONSOLE_get_input(hConsoleInput,FALSE);
930
931     /* FIXME: should we read at least 1 char? The SDK does not say */
932     while (charsread<nNumberOfCharsToRead)
933     {
934         struct read_console_input_request *req = get_req_buffer();
935         req->handle = hConsoleInput;
936         req->count = 1;
937         req->flush = 1;
938         if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
939         if (!req->read) break;
940         ir = (LPINPUT_RECORD)(req+1);
941         if (!ir->Event.KeyEvent.bKeyDown)
942                 continue;
943         if (ir->EventType != KEY_EVENT)
944                 continue;
945         *xbuf++ = ir->Event.KeyEvent.uChar.AsciiChar; 
946         charsread++;
947     }
948     if (lpNumberOfCharsRead)
949         *lpNumberOfCharsRead = charsread;
950     return TRUE;
951 }
952
953 /***********************************************************************
954  *            ReadConsoleW   (KERNEL32.427)
955  */
956 BOOL WINAPI ReadConsoleW( HANDLE hConsoleInput,
957                               LPVOID lpBuffer,
958                               DWORD nNumberOfCharsToRead,
959                               LPDWORD lpNumberOfCharsRead,
960                               LPVOID lpReserved )
961 {
962     BOOL ret;
963     LPSTR buf = (LPSTR)HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead);
964
965     ret = ReadConsoleA(
966         hConsoleInput,
967         buf,
968         nNumberOfCharsToRead,
969         lpNumberOfCharsRead,
970         lpReserved
971     );
972     if (ret)
973         lstrcpynAtoW(lpBuffer,buf,nNumberOfCharsToRead);
974     HeapFree( GetProcessHeap(), 0, buf );
975     return ret;
976 }
977
978
979 /******************************************************************************
980  * ReadConsoleInputA [KERNEL32.569]  Reads data from a console
981  *
982  * PARAMS
983  *    hConsoleInput        [I] Handle to console input buffer
984  *    lpBuffer             [O] Address of buffer for read data
985  *    nLength              [I] Number of records to read
986  *    lpNumberOfEventsRead [O] Address of number of records read
987  *
988  * RETURNS
989  *    Success: TRUE
990  *    Failure: FALSE
991  */
992 BOOL WINAPI ReadConsoleInputA(HANDLE hConsoleInput, LPINPUT_RECORD lpBuffer,
993                               DWORD nLength, LPDWORD lpNumberOfEventsRead)
994 {
995     struct read_console_input_request *req = get_req_buffer();
996
997     /* loop until we get at least one event */
998     for (;;)
999     {
1000         req->handle = hConsoleInput;
1001         req->count = nLength;
1002         req->flush = 1;
1003         if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
1004         if (req->read)
1005         {
1006             memcpy( lpBuffer, req + 1, req->read * sizeof(*lpBuffer) );
1007             if (lpNumberOfEventsRead) *lpNumberOfEventsRead = req->read;
1008             return TRUE;
1009         }
1010         CONSOLE_get_input(hConsoleInput,TRUE);
1011         /*WaitForSingleObject( hConsoleInput, INFINITE32 );*/
1012     }
1013 }
1014
1015
1016 /***********************************************************************
1017  *            ReadConsoleInputW   (KERNEL32.570)
1018  */
1019 BOOL WINAPI ReadConsoleInputW( HANDLE handle, LPINPUT_RECORD buffer,
1020                                    DWORD count, LPDWORD read )
1021 {
1022     /* FIXME: Fix this if we get UNICODE input. */
1023     return ReadConsoleInputA( handle, buffer, count, read );
1024 }
1025
1026
1027 /***********************************************************************
1028  *            FlushConsoleInputBuffer   (KERNEL32.132)
1029  */
1030 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1031 {
1032     struct read_console_input_request *req = get_req_buffer();
1033     req->handle = handle;
1034     req->count = -1;  /* get all records */
1035     req->flush = 1;
1036     return !server_call( REQ_READ_CONSOLE_INPUT );
1037 }
1038
1039
1040 /***********************************************************************
1041  *            PeekConsoleInputA   (KERNEL32.550)
1042  *
1043  * Gets 'count' first events (or less) from input queue.
1044  *
1045  * Does not need a complex console.
1046  */
1047 BOOL WINAPI PeekConsoleInputA( HANDLE handle, LPINPUT_RECORD buffer,
1048                                    DWORD count, LPDWORD read )
1049 {
1050     struct read_console_input_request *req = get_req_buffer();
1051
1052     CONSOLE_get_input(handle,FALSE);
1053
1054     req->handle = handle;
1055     req->count = count;
1056     req->flush = 0;
1057     if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
1058     if (req->read) memcpy( buffer, req + 1, req->read * sizeof(*buffer) );
1059     if (read) *read = req->read;
1060     return TRUE;
1061 }
1062
1063
1064 /***********************************************************************
1065  *            PeekConsoleInputW   (KERNEL32.551)
1066  */
1067 BOOL WINAPI PeekConsoleInputW(HANDLE hConsoleInput,
1068                                   LPINPUT_RECORD pirBuffer,
1069                                   DWORD cInRecords,
1070                                   LPDWORD lpcRead)
1071 {
1072     /* FIXME: Hmm. Fix this if we get UNICODE input. */
1073     return PeekConsoleInputA(hConsoleInput,pirBuffer,cInRecords,lpcRead);
1074 }
1075
1076
1077 /******************************************************************************
1078  * WriteConsoleInputA [KERNEL32.730]  Write data to a console input buffer
1079  *
1080  */
1081 BOOL WINAPI WriteConsoleInputA( HANDLE handle, INPUT_RECORD *buffer,
1082                                 DWORD count, LPDWORD written )
1083 {
1084     struct write_console_input_request *req = get_req_buffer();
1085     const DWORD max = server_remaining( req + 1 ) / sizeof(INPUT_RECORD);
1086
1087     if (written) *written = 0;
1088     while (count)
1089     {
1090         DWORD len = count < max ? count : max;
1091         req->count = len;
1092         req->handle = handle;
1093         memcpy( req + 1, buffer, len * sizeof(*buffer) );
1094         if (server_call( REQ_WRITE_CONSOLE_INPUT )) return FALSE;
1095         if (written) *written += req->written;
1096         count -= len;
1097         buffer += len;
1098     }
1099     return TRUE;
1100 }
1101
1102 /******************************************************************************
1103  * WriteConsoleInputW [KERNEL32.731]  Write data to a console input buffer
1104  *
1105  */
1106 BOOL WINAPI WriteConsoleInputW( HANDLE handle, INPUT_RECORD *buffer,
1107                                 DWORD count, LPDWORD written )
1108 {
1109     FIXME("(%d,%p,%ld,%p): stub!\n", handle, buffer, count, written);
1110
1111     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1112     return FALSE;    
1113 }
1114
1115
1116 /***********************************************************************
1117  *            SetConsoleTitleA   (KERNEL32.476)
1118  *
1119  * Sets the console title.
1120  *
1121  * We do not necessarily need to create a complex console for that,
1122  * but should remember the title and set it on creation of the latter.
1123  * (not fixed at this time).
1124  */
1125 BOOL WINAPI SetConsoleTitleA(LPCSTR title)
1126 {
1127     struct set_console_info_request *req = get_req_buffer();
1128     HANDLE hcon;
1129     DWORD written;
1130
1131     if ((hcon = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, NULL,
1132                                OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
1133         return FALSE;
1134     req->handle = hcon;
1135     req->mask = SET_CONSOLE_INFO_TITLE;
1136     lstrcpynA( req->title, title, server_remaining(req->title) );
1137     if (server_call( REQ_SET_CONSOLE_INFO )) goto error;
1138     if (CONSOLE_GetPid( hcon ))
1139     {
1140         /* only set title for complex console (own xterm) */
1141         WriteFile( hcon, "\033]2;", 4, &written, NULL );
1142         WriteFile( hcon, title, strlen(title), &written, NULL );
1143         WriteFile( hcon, "\a", 1, &written, NULL );
1144     }
1145     CloseHandle( hcon );
1146     return TRUE;
1147  error:
1148     CloseHandle( hcon );
1149     return FALSE;
1150 }
1151
1152
1153 /******************************************************************************
1154  * SetConsoleTitleW [KERNEL32.477]  Sets title bar string for console
1155  *
1156  * PARAMS
1157  *    title [I] Address of new title
1158  *
1159  * NOTES
1160  *    This should not be calling the A version
1161  *
1162  * RETURNS
1163  *    Success: TRUE
1164  *    Failure: FALSE
1165  */
1166 BOOL WINAPI SetConsoleTitleW( LPCWSTR title )
1167 {
1168     BOOL ret;
1169
1170     LPSTR titleA = HEAP_strdupWtoA( GetProcessHeap(), 0, title );
1171     ret = SetConsoleTitleA(titleA);
1172     HeapFree( GetProcessHeap(), 0, titleA );
1173     return ret;
1174 }
1175
1176 /******************************************************************************
1177  * SetConsoleCursorPosition [KERNEL32.627]
1178  * Sets the cursor position in console
1179  *
1180  * PARAMS
1181  *    hConsoleOutput   [I] Handle of console screen buffer
1182  *    dwCursorPosition [I] New cursor position coordinates
1183  *
1184  * RETURNS STD
1185  */
1186 BOOL WINAPI SetConsoleCursorPosition( HANDLE hcon, COORD pos )
1187 {
1188     char        xbuf[20];
1189     DWORD       xlen;
1190
1191     /* make console complex only if we change lines, not just in the line */
1192     if (pos.Y)
1193         CONSOLE_make_complex(hcon);
1194
1195     TRACE("%d (%dx%d)\n", hcon, pos.X , pos.Y );
1196     /* x are columns, y rows */
1197     if (pos.Y) 
1198         /* full screen cursor absolute positioning */
1199         sprintf(xbuf,"%c[%d;%dH", 0x1B, pos.Y+1, pos.X+1);
1200     else
1201         /* relative cursor positioning in line (\r to go to 0) */
1202         sprintf(xbuf,"\r%c[%dC", 0x1B, pos.X);
1203     /* FIXME: store internal if we start using own console buffers */
1204     WriteFile(hcon,xbuf,strlen(xbuf),&xlen,NULL);
1205     return TRUE;
1206 }
1207
1208 /***********************************************************************
1209  *            GetNumberOfConsoleInputEvents   (KERNEL32.246)
1210  */
1211 BOOL WINAPI GetNumberOfConsoleInputEvents(HANDLE hcon,LPDWORD nrofevents)
1212 {
1213     struct read_console_input_request *req = get_req_buffer();
1214
1215     CONSOLE_get_input(hcon,FALSE);
1216
1217     req->handle = hcon;
1218     req->count = -1;
1219     req->flush = 0;
1220     if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
1221     if (nrofevents) *nrofevents = req->read;
1222     return TRUE;
1223 }
1224
1225 /***********************************************************************
1226  *            GetNumberOfConsoleMouseButtons   (KERNEL32.358)
1227  */
1228 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1229 {
1230     FIXME("(%p): stub\n", nrofbuttons);
1231     *nrofbuttons = 2;
1232     return TRUE;
1233 }
1234
1235 /******************************************************************************
1236  * GetConsoleCursorInfo [KERNEL32.296]  Gets size and visibility of console
1237  *
1238  * PARAMS
1239  *    hcon  [I] Handle to console screen buffer
1240  *    cinfo [O] Address of cursor information
1241  *
1242  * RETURNS
1243  *    Success: TRUE
1244  *    Failure: FALSE
1245  */
1246 BOOL WINAPI GetConsoleCursorInfo( HANDLE hcon, LPCONSOLE_CURSOR_INFO cinfo )
1247 {
1248     struct get_console_info_request *req = get_req_buffer();
1249     req->handle = hcon;
1250     if (server_call( REQ_GET_CONSOLE_INFO )) return FALSE;
1251     if (cinfo)
1252     {
1253         cinfo->dwSize = req->cursor_size;
1254         cinfo->bVisible = req->cursor_visible;
1255     }
1256     return TRUE;
1257 }
1258
1259
1260 /******************************************************************************
1261  * SetConsoleCursorInfo [KERNEL32.626]  Sets size and visibility of cursor
1262  *
1263  * RETURNS
1264  *    Success: TRUE
1265  *    Failure: FALSE
1266  */
1267 BOOL WINAPI SetConsoleCursorInfo( 
1268     HANDLE hcon,                /* [in] Handle to console screen buffer */
1269     LPCONSOLE_CURSOR_INFO cinfo)  /* [in] Address of cursor information */
1270 {
1271     struct set_console_info_request *req = get_req_buffer();
1272     char        buf[8];
1273     DWORD       xlen;
1274
1275     CONSOLE_make_complex(hcon);
1276     sprintf(buf,"\033[?25%c",cinfo->bVisible?'h':'l');
1277     WriteFile(hcon,buf,strlen(buf),&xlen,NULL);
1278
1279     req->handle         = hcon;
1280     req->cursor_size    = cinfo->dwSize;
1281     req->cursor_visible = cinfo->bVisible;
1282     req->mask           = SET_CONSOLE_INFO_CURSOR;
1283     return !server_call( REQ_SET_CONSOLE_INFO );
1284 }
1285
1286
1287 /******************************************************************************
1288  * SetConsoleWindowInfo [KERNEL32.634]  Sets size and position of console
1289  *
1290  * RETURNS
1291  *    Success: TRUE
1292  *    Failure: FALSE
1293  */
1294 BOOL WINAPI SetConsoleWindowInfo(
1295     HANDLE hcon,       /* [in] Handle to console screen buffer */
1296     BOOL bAbsolute,    /* [in] Coordinate type flag */
1297     LPSMALL_RECT window) /* [in] Address of new window rectangle */
1298 {
1299     FIXME("(%x,%d,%p): stub\n", hcon, bAbsolute, window);
1300     return TRUE;
1301 }
1302
1303
1304 /******************************************************************************
1305  * SetConsoleTextAttribute [KERNEL32.631]  Sets colors for text
1306  *
1307  * Sets the foreground and background color attributes of characters
1308  * written to the screen buffer.
1309  *
1310  * RETURNS
1311  *    Success: TRUE
1312  *    Failure: FALSE
1313  */
1314 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput,WORD wAttr)
1315 {
1316     const int colormap[8] = {
1317         0,4,2,6,
1318         1,5,3,7,
1319     };
1320     DWORD xlen;
1321     char buffer[20];
1322
1323     TRACE("(%d,%d)\n",hConsoleOutput,wAttr);
1324     sprintf(buffer,"%c[0;%s3%d;4%dm",
1325         27,
1326         (wAttr & FOREGROUND_INTENSITY)?"1;":"",
1327         colormap[wAttr&7],
1328         colormap[(wAttr&0x70)>>4]
1329     );
1330     WriteFile(hConsoleOutput,buffer,strlen(buffer),&xlen,NULL);
1331     return TRUE;
1332 }
1333
1334
1335 /******************************************************************************
1336  * SetConsoleScreenBufferSize [KERNEL32.630]  Changes size of console 
1337  *
1338  * PARAMS
1339  *    hConsoleOutput [I] Handle to console screen buffer
1340  *    dwSize         [I] New size in character rows and cols
1341  *
1342  * RETURNS
1343  *    Success: TRUE
1344  *    Failure: FALSE
1345  */
1346 BOOL WINAPI SetConsoleScreenBufferSize( HANDLE hConsoleOutput, 
1347                                           COORD dwSize )
1348 {
1349     FIXME("(%d,%dx%d): stub\n",hConsoleOutput,dwSize.X,dwSize.Y);
1350     return TRUE;
1351 }
1352
1353
1354 /******************************************************************************
1355  * FillConsoleOutputCharacterA [KERNEL32.242]
1356  *
1357  * PARAMS
1358  *    hConsoleOutput    [I] Handle to screen buffer
1359  *    cCharacter        [I] Character to write
1360  *    nLength           [I] Number of cells to write to
1361  *    dwCoord           [I] Coords of first cell
1362  *    lpNumCharsWritten [O] Pointer to number of cells written
1363  *
1364  * RETURNS
1365  *    Success: TRUE
1366  *    Failure: FALSE
1367  */
1368 BOOL WINAPI FillConsoleOutputCharacterA(
1369     HANDLE hConsoleOutput,
1370     BYTE cCharacter,
1371     DWORD nLength,
1372     COORD dwCoord,
1373     LPDWORD lpNumCharsWritten)
1374 {
1375     long        count;
1376     DWORD       xlen;
1377
1378     SetConsoleCursorPosition(hConsoleOutput,dwCoord);
1379     for(count=0;count<nLength;count++)
1380         WriteFile(hConsoleOutput,&cCharacter,1,&xlen,NULL);
1381     *lpNumCharsWritten = nLength;
1382     return TRUE;
1383 }
1384
1385
1386 /******************************************************************************
1387  * FillConsoleOutputCharacterW [KERNEL32.243]  Writes characters to console
1388  *
1389  * PARAMS
1390  *    hConsoleOutput    [I] Handle to screen buffer
1391  *    cCharacter        [I] Character to write
1392  *    nLength           [I] Number of cells to write to
1393  *    dwCoord           [I] Coords of first cell
1394  *    lpNumCharsWritten [O] Pointer to number of cells written
1395  *
1396  * RETURNS
1397  *    Success: TRUE
1398  *    Failure: FALSE
1399  */
1400 BOOL WINAPI FillConsoleOutputCharacterW(HANDLE hConsoleOutput,
1401                                             WCHAR cCharacter,
1402                                             DWORD nLength,
1403                                            COORD dwCoord, 
1404                                             LPDWORD lpNumCharsWritten)
1405 {
1406     long        count;
1407     DWORD       xlen;
1408
1409     SetConsoleCursorPosition(hConsoleOutput,dwCoord);
1410     /* FIXME: not quite correct ... but the lower part of UNICODE char comes
1411      * first 
1412      */
1413     for(count=0;count<nLength;count++)
1414         WriteFile(hConsoleOutput,&cCharacter,1,&xlen,NULL);
1415     *lpNumCharsWritten = nLength;
1416     return TRUE;
1417 }
1418
1419
1420 /******************************************************************************
1421  * FillConsoleOutputAttribute [KERNEL32.241]  Sets attributes for console
1422  *
1423  * PARAMS
1424  *    hConsoleOutput    [I] Handle to screen buffer
1425  *    wAttribute        [I] Color attribute to write
1426  *    nLength           [I] Number of cells to write to
1427  *    dwCoord           [I] Coords of first cell
1428  *    lpNumAttrsWritten [O] Pointer to number of cells written
1429  *
1430  * RETURNS
1431  *    Success: TRUE
1432  *    Failure: FALSE
1433  */
1434 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, 
1435               WORD wAttribute, DWORD nLength, COORD dwCoord, 
1436               LPDWORD lpNumAttrsWritten)
1437 {
1438     FIXME("(%d,%d,%ld,%dx%d,%p): stub\n", hConsoleOutput,
1439           wAttribute,nLength,dwCoord.X,dwCoord.Y,lpNumAttrsWritten);
1440     *lpNumAttrsWritten = nLength;
1441     return TRUE;
1442 }
1443
1444 /******************************************************************************
1445  * ReadConsoleOutputCharacterA [KERNEL32.573]
1446  * 
1447  * BUGS
1448  *   Unimplemented
1449  */
1450 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, 
1451               LPSTR lpstr, DWORD dword, COORD coord, LPDWORD lpdword)
1452 {
1453     FIXME("(%d,%p,%ld,%dx%d,%p): stub\n", hConsoleOutput,lpstr,
1454           dword,coord.X,coord.Y,lpdword);
1455     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1456     return FALSE;
1457 }
1458
1459 /******************************************************************************
1460  * ReadConsoleOutputCharacterW [KERNEL32.574]
1461  * 
1462  * BUGS
1463  *   Unimplemented
1464  */
1465 BOOL WINAPI ReadConsoleOutputCharacterW(HANDLE hConsoleOutput, 
1466               LPWSTR lpstr, DWORD dword, COORD coord, LPDWORD lpdword)
1467 {
1468     FIXME("(%d,%p,%ld,%dx%d,%p): stub\n", hConsoleOutput,lpstr,
1469           dword,coord.X,coord.Y,lpdword);
1470     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1471     return FALSE;
1472 }
1473
1474
1475 /******************************************************************************
1476  * ScrollConsoleScreenBufferA [KERNEL32.612]
1477  * 
1478  * BUGS
1479  *   Unimplemented
1480  */
1481 BOOL WINAPI ScrollConsoleScreenBufferA( HANDLE hConsoleOutput, 
1482               LPSMALL_RECT lpScrollRect, LPSMALL_RECT lpClipRect,
1483               COORD dwDestOrigin, LPCHAR_INFO lpFill)
1484 {
1485     FIXME("(%d,%p,%p,%dx%d,%p): stub\n", hConsoleOutput,lpScrollRect,
1486           lpClipRect,dwDestOrigin.X,dwDestOrigin.Y,lpFill);
1487     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1488     return FALSE;
1489 }
1490
1491 /******************************************************************************
1492  * ScrollConsoleScreenBufferW [KERNEL32.613]
1493  * 
1494  * BUGS
1495  *   Unimplemented
1496  */
1497 BOOL WINAPI ScrollConsoleScreenBufferW( HANDLE hConsoleOutput, 
1498               LPSMALL_RECT lpScrollRect, LPSMALL_RECT lpClipRect,
1499               COORD dwDestOrigin, LPCHAR_INFO lpFill)
1500 {
1501     FIXME("(%d,%p,%p,%dx%d,%p): stub\n", hConsoleOutput,lpScrollRect,
1502           lpClipRect,dwDestOrigin.X,dwDestOrigin.Y,lpFill);
1503     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1504     return FALSE;
1505 }
1506
1507 /******************************************************************************
1508  *  ReadConsoleOutputA [KERNEL32.571]
1509  * 
1510  * BUGS
1511  *   Unimplemented
1512  */
1513 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, 
1514                                 LPCHAR_INFO lpBuffer,
1515                                 COORD dwBufferSize,
1516                                 COORD dwBufferCoord,
1517                                 LPSMALL_RECT lpReadRegion )
1518 {
1519     FIXME("(%d,%p,%dx%d,%dx%d,%p): stub\n", hConsoleOutput, lpBuffer,
1520           dwBufferSize.X, dwBufferSize.Y, dwBufferSize.X, dwBufferSize.Y, 
1521           lpReadRegion);
1522     
1523     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1524     return FALSE;
1525 }
1526
1527 /******************************************************************************
1528  *  ReadConsoleOutputW [KERNEL32.575]
1529  * 
1530  * BUGS
1531  *   Unimplemented
1532  */
1533 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, 
1534                                 LPCHAR_INFO lpBuffer,
1535                                 COORD dwBufferSize,
1536                                 COORD dwBufferCoord,
1537                                 LPSMALL_RECT lpReadRegion )
1538 {
1539     FIXME("(%d,%p,%dx%d,%dx%d,%p): stub\n", hConsoleOutput, lpBuffer,
1540           dwBufferSize.X, dwBufferSize.Y, dwBufferSize.X, dwBufferSize.Y, 
1541           lpReadRegion);
1542     
1543     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1544     return FALSE;
1545 }
1546
1547 /******************************************************************************
1548  *  ReadConsoleOutputAttribute [KERNEL32.572]
1549  * 
1550  * BUGS
1551  *   Unimplemented
1552  */
1553 BOOL WINAPI ReadConsoleOutputAttribute( HANDLE hConsoleOutput, 
1554                                         LPWORD lpAttribute,
1555                                         DWORD nLength,
1556                                         COORD dwReadCoord,
1557                                         LPDWORD lpNumberOfAttrsRead)
1558 {
1559     FIXME("(%d,%p,%ld,%dx%d,%p): stub\n", hConsoleOutput, lpAttribute,
1560           nLength, dwReadCoord.X, dwReadCoord.Y, lpNumberOfAttrsRead);
1561     
1562     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1563     return FALSE;
1564 }
1565
1566 /******************************************************************************
1567  *  SetConsoleCP         [KERNEL32.572]
1568  * 
1569  * BUGS
1570  *   Unimplemented
1571  */
1572 BOOL WINAPI SetConsoleCP( UINT cp )
1573 {
1574     FIXME("(%d): stub\n", cp);
1575     
1576     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1577     return FALSE;
1578 }