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