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