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