Windows should be activated in these cases:
[wine/dcerpc.git] / win32 / console.c
blobb1669de00ae7ef613e7020f07ad647b1190c31ef
1 /*
2 * Win32 kernel functions
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 */
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 ?)
17 /* Reference applications:
18 * - IDA (interactive disassembler) full version 3.75. Works.
19 * - LYNX/W32. Works mostly, some keys crash it.
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <termios.h>
25 #include <string.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>
36 #include "winbase.h"
37 #include "wine/winuser16.h"
38 #include "wine/keyboard16.h"
39 #include "thread.h"
40 #include "async.h"
41 #include "file.h"
42 #include "process.h"
43 #include "winerror.h"
44 #include "wincon.h"
45 #include "heap.h"
46 #include "server.h"
47 #include "debugtools.h"
49 DEFAULT_DEBUG_CHANNEL(console)
52 /* FIXME: Should be in an internal header file. OK, so which one?
53 Used by CONSOLE_makecomplex. */
54 FILE *wine_openpty(int *master, int *slave, char *name,
55 struct termios *term, struct winsize *winsize);
57 /****************************************************************************
58 * CONSOLE_GetPid
60 static int CONSOLE_GetPid( HANDLE handle )
62 struct get_console_info_request *req = get_req_buffer();
63 req->handle = handle;
64 if (server_call( REQ_GET_CONSOLE_INFO )) return 0;
65 return req->pid;
68 /****************************************************************************
69 * XTERM_string_to_IR [internal]
71 * Transfers a string read from XTERM to INPUT_RECORDs and adds them to the
72 * queue. Does translation of vt100 style function keys and xterm-mouse clicks.
74 static void
75 CONSOLE_string_to_IR( HANDLE hConsoleInput,unsigned char *buf,int len) {
76 int j,k;
77 INPUT_RECORD ir;
78 DWORD junk;
80 for (j=0;j<len;j++) {
81 unsigned char inchar = buf[j];
83 if (inchar!=27) { /* no escape -> 'normal' keyboard event */
84 ir.EventType = 1; /* Key_event */
86 ir.Event.KeyEvent.bKeyDown = 1;
87 ir.Event.KeyEvent.wRepeatCount = 0;
89 ir.Event.KeyEvent.dwControlKeyState = 0;
90 if (inchar & 0x80) {
91 ir.Event.KeyEvent.dwControlKeyState|=LEFT_ALT_PRESSED;
92 inchar &= ~0x80;
94 ir.Event.KeyEvent.wVirtualKeyCode = VkKeyScan16(inchar);
95 if (ir.Event.KeyEvent.wVirtualKeyCode & 0x0100)
96 ir.Event.KeyEvent.dwControlKeyState|=SHIFT_PRESSED;
97 if (ir.Event.KeyEvent.wVirtualKeyCode & 0x0200)
98 ir.Event.KeyEvent.dwControlKeyState|=LEFT_CTRL_PRESSED;
99 if (ir.Event.KeyEvent.wVirtualKeyCode & 0x0400)
100 ir.Event.KeyEvent.dwControlKeyState|=LEFT_ALT_PRESSED;
101 ir.Event.KeyEvent.wVirtualScanCode = MapVirtualKey16(
102 ir.Event.KeyEvent.wVirtualKeyCode & 0x00ff,
103 0 /* VirtualKeyCodes to ScanCode */
105 ir.Event.KeyEvent.uChar.AsciiChar = inchar;
107 if (inchar==127) { /* backspace */
108 ir.Event.KeyEvent.uChar.AsciiChar = '\b'; /* FIXME: hmm */
109 ir.Event.KeyEvent.wVirtualScanCode = 0x0e;
110 ir.Event.KeyEvent.wVirtualKeyCode = VK_BACK;
111 } else {
112 if ((inchar=='\n')||(inchar=='\r')) {
113 ir.Event.KeyEvent.uChar.AsciiChar = '\r';
114 ir.Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
115 ir.Event.KeyEvent.wVirtualScanCode = 0x1c;
116 ir.Event.KeyEvent.dwControlKeyState = 0;
117 } else {
118 if (inchar<' ') {
119 /* FIXME: find good values for ^X */
120 ir.Event.KeyEvent.wVirtualKeyCode = 0xdead;
121 ir.Event.KeyEvent.wVirtualScanCode = 0xbeef;
126 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
127 ir.Event.KeyEvent.bKeyDown = 0;
128 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
129 continue;
131 /* inchar is ESC */
132 if ((j==len-1) || (buf[j+1]!='[')) {/* add ESCape on its own */
133 ir.EventType = 1; /* Key_event */
134 ir.Event.KeyEvent.bKeyDown = 1;
135 ir.Event.KeyEvent.wRepeatCount = 0;
137 ir.Event.KeyEvent.wVirtualKeyCode = VkKeyScan16(27);
138 ir.Event.KeyEvent.wVirtualScanCode = MapVirtualKey16(
139 ir.Event.KeyEvent.wVirtualKeyCode,0
141 ir.Event.KeyEvent.dwControlKeyState = 0;
142 ir.Event.KeyEvent.uChar.AsciiChar = 27;
143 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
144 ir.Event.KeyEvent.bKeyDown = 0;
145 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
146 continue;
148 for (k=j;k<len;k++) {
149 if (((buf[k]>='A') && (buf[k]<='Z')) ||
150 ((buf[k]>='a') && (buf[k]<='z')) ||
151 (buf[k]=='~')
153 break;
155 if (k<len) {
156 int subid,scancode=0;
158 ir.EventType = 1; /* Key_event */
159 ir.Event.KeyEvent.bKeyDown = 1;
160 ir.Event.KeyEvent.wRepeatCount = 0;
161 ir.Event.KeyEvent.dwControlKeyState = 0;
163 ir.Event.KeyEvent.wVirtualKeyCode = 0xad; /* FIXME */
164 ir.Event.KeyEvent.wVirtualScanCode = 0xad; /* FIXME */
165 ir.Event.KeyEvent.uChar.AsciiChar = 0;
167 switch (buf[k]) {
168 case '~':
169 sscanf(&buf[j+2],"%d",&subid);
170 switch (subid) {
171 case 2:/*INS */scancode = 0xe052;break;
172 case 3:/*DEL */scancode = 0xe053;break;
173 case 6:/*PGDW*/scancode = 0xe051;break;
174 case 5:/*PGUP*/scancode = 0xe049;break;
175 case 11:/*F1 */scancode = 0x003b;break;
176 case 12:/*F2 */scancode = 0x003c;break;
177 case 13:/*F3 */scancode = 0x003d;break;
178 case 14:/*F4 */scancode = 0x003e;break;
179 case 15:/*F5 */scancode = 0x003f;break;
180 case 17:/*F6 */scancode = 0x0040;break;
181 case 18:/*F7 */scancode = 0x0041;break;
182 case 19:/*F8 */scancode = 0x0042;break;
183 case 20:/*F9 */scancode = 0x0043;break;
184 case 21:/*F10 */scancode = 0x0044;break;
185 case 23:/*F11 */scancode = 0x00d9;break;
186 case 24:/*F12 */scancode = 0x00da;break;
187 /* FIXME: Shift-Fx */
188 default:
189 FIXME("parse ESC[%d~\n",subid);
190 break;
192 break;
193 case 'A': /* Cursor Up */scancode = 0xe048;break;
194 case 'B': /* Cursor Down */scancode = 0xe050;break;
195 case 'D': /* Cursor Left */scancode = 0xe04b;break;
196 case 'C': /* Cursor Right */scancode = 0xe04d;break;
197 case 'F': /* End */scancode = 0xe04f;break;
198 case 'H': /* Home */scancode = 0xe047;break;
199 case 'M':
200 /* Mouse Button Press (ESCM<button+'!'><x+'!'><y+'!'>) or
201 * Release (ESCM#<x+'!'><y+'!'>
203 if (k<len-3) {
204 ir.EventType = MOUSE_EVENT;
205 ir.Event.MouseEvent.dwMousePosition.x = buf[k+2]-'!';
206 ir.Event.MouseEvent.dwMousePosition.y = buf[k+3]-'!';
207 if (buf[k+1]=='#')
208 ir.Event.MouseEvent.dwButtonState = 0;
209 else
210 ir.Event.MouseEvent.dwButtonState = 1<<(buf[k+1]-' ');
211 ir.Event.MouseEvent.dwEventFlags = 0; /* FIXME */
212 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk));
213 j=k+3;
215 break;
216 case 'c':
217 j=k;
218 break;
220 if (scancode) {
221 ir.Event.KeyEvent.wVirtualScanCode = scancode;
222 ir.Event.KeyEvent.wVirtualKeyCode = MapVirtualKey16(scancode,1);
223 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
224 ir.Event.KeyEvent.bKeyDown = 0;
225 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
226 j=k;
227 continue;
233 /****************************************************************************
234 * CONSOLE_get_input (internal)
236 * Reads (nonblocking) as much input events as possible and stores them
237 * in an internal queue.
239 static void
240 CONSOLE_get_input( HANDLE handle, BOOL blockwait )
242 char *buf = HeapAlloc(GetProcessHeap(),0,1);
243 int len = 0;
245 while (1)
247 DWORD res;
248 char inchar;
249 if (WaitForSingleObject( handle, 0 )) break;
250 if (!ReadFile( handle, &inchar, 1, &res, NULL )) break;
251 if (!res) /* res 0 but readable means EOF? Hmm. */
252 break;
253 buf = HeapReAlloc(GetProcessHeap(),0,buf,len+1);
254 buf[len++]=inchar;
256 CONSOLE_string_to_IR(handle,buf,len);
257 HeapFree(GetProcessHeap(),0,buf);
260 /******************************************************************************
261 * SetConsoleCtrlHandler [KERNEL32.459] Adds function to calling process list
263 * PARAMS
264 * func [I] Address of handler function
265 * add [I] Handler to add or remove
267 * RETURNS
268 * Success: TRUE
269 * Failure: FALSE
271 * CHANGED
272 * James Sutherland (JamesSutherland@gmx.de)
273 * Added global variables console_ignore_ctrl_c and handlers[]
274 * Does not yet do any error checking, or set LastError if failed.
275 * This doesn't yet matter, since these handlers are not yet called...!
277 static unsigned int console_ignore_ctrl_c = 0;
278 static HANDLER_ROUTINE *handlers[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
279 BOOL WINAPI SetConsoleCtrlHandler( HANDLER_ROUTINE *func, BOOL add )
281 unsigned int alloc_loop = sizeof(handlers)/sizeof(HANDLER_ROUTINE *);
282 unsigned int done = 0;
283 FIXME("(%p,%i) - no error checking or testing yet\n", func, add);
284 if (!func)
286 console_ignore_ctrl_c = add;
287 return TRUE;
289 if (add)
291 for (;alloc_loop--;)
292 if (!handlers[alloc_loop] && !done)
294 handlers[alloc_loop] = func;
295 done++;
297 if (!done)
298 FIXME("Out of space on CtrlHandler table\n");
299 return(done);
301 else
303 for (;alloc_loop--;)
304 if (handlers[alloc_loop] == func && !done)
306 handlers[alloc_loop] = 0;
307 done++;
309 if (!done)
310 WARN("Attempt to remove non-installed CtrlHandler %p\n",
311 func);
312 return (done);
314 return (done);
318 /******************************************************************************
319 * GenerateConsoleCtrlEvent [KERNEL32.275] Simulate a CTRL-C or CTRL-BREAK
321 * PARAMS
322 * dwCtrlEvent [I] Type of event
323 * dwProcessGroupID [I] Process group ID to send event to
325 * NOTES
326 * Doesn't yet work...!
328 * RETURNS
329 * Success: True
330 * Failure: False (and *should* [but doesn't] set LastError)
332 BOOL WINAPI GenerateConsoleCtrlEvent( DWORD dwCtrlEvent,
333 DWORD dwProcessGroupID )
335 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
337 ERR("invalid event %d for PGID %ld\n",
338 (unsigned short)dwCtrlEvent, dwProcessGroupID );
339 return FALSE;
341 if (dwProcessGroupID == GetCurrentProcessId() )
343 FIXME("Attempt to send event %d to self - stub\n",
344 (unsigned short)dwCtrlEvent );
345 return FALSE;
347 FIXME("event %d to external PGID %ld - not implemented yet\n",
348 (unsigned short)dwCtrlEvent, dwProcessGroupID );
349 return FALSE;
353 /******************************************************************************
354 * CreateConsoleScreenBuffer [KERNEL32.151] Creates a console screen buffer
356 * PARAMS
357 * dwDesiredAccess [I] Access flag
358 * dwShareMode [I] Buffer share mode
359 * sa [I] Security attributes
360 * dwFlags [I] Type of buffer to create
361 * lpScreenBufferData [I] Reserved
363 * NOTES
364 * Should call SetLastError
366 * RETURNS
367 * Success: Handle to new console screen buffer
368 * Failure: INVALID_HANDLE_VALUE
370 HANDLE WINAPI CreateConsoleScreenBuffer( DWORD dwDesiredAccess,
371 DWORD dwShareMode, LPSECURITY_ATTRIBUTES sa,
372 DWORD dwFlags, LPVOID lpScreenBufferData )
374 FIXME("(%ld,%ld,%p,%ld,%p): stub\n",dwDesiredAccess,
375 dwShareMode, sa, dwFlags, lpScreenBufferData);
376 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
377 return INVALID_HANDLE_VALUE;
381 /***********************************************************************
382 * GetConsoleScreenBufferInfo (KERNEL32.190)
384 BOOL WINAPI GetConsoleScreenBufferInfo( HANDLE hConsoleOutput,
385 LPCONSOLE_SCREEN_BUFFER_INFO csbi )
387 csbi->dwSize.x = 80;
388 csbi->dwSize.y = 24;
389 csbi->dwCursorPosition.x = 0;
390 csbi->dwCursorPosition.y = 0;
391 csbi->wAttributes = 0;
392 csbi->srWindow.Left = 0;
393 csbi->srWindow.Right = 79;
394 csbi->srWindow.Top = 0;
395 csbi->srWindow.Bottom = 23;
396 csbi->dwMaximumWindowSize.x = 80;
397 csbi->dwMaximumWindowSize.y = 24;
398 return TRUE;
402 /******************************************************************************
403 * SetConsoleActiveScreenBuffer [KERNEL32.623] Sets buffer to current console
405 * RETURNS
406 * Success: TRUE
407 * Failure: FALSE
409 BOOL WINAPI SetConsoleActiveScreenBuffer(
410 HANDLE hConsoleOutput) /* [in] Handle to console screen buffer */
412 FIXME("(%x): stub\n", hConsoleOutput);
413 return FALSE;
417 /***********************************************************************
418 * GetLargestConsoleWindowSize (KERNEL32.226)
420 DWORD WINAPI GetLargestConsoleWindowSize( HANDLE hConsoleOutput )
422 return (DWORD)MAKELONG(80,24);
425 /***********************************************************************
426 * FreeConsole (KERNEL32.267)
428 BOOL WINAPI FreeConsole(VOID)
430 return !server_call( REQ_FREE_CONSOLE );
434 /*************************************************************************
435 * CONSOLE_OpenHandle
437 * Open a handle to the current process console.
439 HANDLE CONSOLE_OpenHandle( BOOL output, DWORD access, LPSECURITY_ATTRIBUTES sa )
441 int ret = -1;
442 struct open_console_request *req = get_req_buffer();
444 req->output = output;
445 req->access = access;
446 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
447 SetLastError(0);
448 if (!server_call( REQ_OPEN_CONSOLE )) ret = req->handle;
449 return ret;
453 /*************************************************************************
454 * CONSOLE_make_complex [internal]
456 * Turns a CONSOLE kernel object into a complex one.
457 * (switches from output/input using the terminal where WINE was started to
458 * its own xterm).
460 * This makes simple commandline tools pipeable, while complex commandline
461 * tools work without getting messed up by debugoutput.
463 * All other functions should work indedependend from this call.
465 * To test for complex console: pid == 0 -> simple, otherwise complex.
467 static BOOL CONSOLE_make_complex(HANDLE handle)
469 struct set_console_fd_request *req = get_req_buffer();
470 struct termios term;
471 char buf[256];
472 char c = '\0';
473 int i,xpid,master,slave,pty_handle;
475 if (CONSOLE_GetPid( handle )) return TRUE; /* already complex */
477 MESSAGE("Console: Making console complex (creating an xterm)...\n");
479 if (tcgetattr(0, &term) < 0) {
480 /* ignore failure, or we can't run from a script */
482 term.c_lflag = ~(ECHO|ICANON);
484 if (wine_openpty(&master, &slave, NULL, &term, NULL) < 0)
485 return FALSE;
487 if ((xpid=fork()) == 0) {
488 tcsetattr(slave, TCSADRAIN, &term);
489 close( slave );
490 sprintf(buf, "-Sxx%d", master);
491 /* "-fn vga" for VGA font. Harmless if vga is not present:
492 * xterm: unable to open font "vga", trying "fixed"....
494 execlp("xterm", "xterm", buf, "-fn","vga",NULL);
495 ERR("error creating AllocConsole xterm\n");
496 exit(1);
498 pty_handle = FILE_DupUnixHandle( slave, GENERIC_READ | GENERIC_WRITE );
499 close( master );
500 close( slave );
501 if (pty_handle == -1) return FALSE;
503 /* most xterms like to print their window ID when used with -S;
504 * read it and continue before the user has a chance...
506 for (i = 0; i < 10000; i++)
508 BOOL ok = ReadFile( pty_handle, &c, 1, NULL, NULL );
509 if (!ok && !c) usleep(100); /* wait for xterm to be created */
510 else if (c == '\n') break;
512 if (i == 10000)
514 ERR("can't read xterm WID\n");
515 CloseHandle( pty_handle );
516 return FALSE;
518 req->handle = handle;
519 req->file_handle = pty_handle;
520 req->pid = xpid;
521 server_call( REQ_SET_CONSOLE_FD );
522 CloseHandle( pty_handle );
524 /* enable mouseclicks */
525 strcpy( buf, "\033[?1001s\033[?1000h" );
526 WriteFile(handle,buf,strlen(buf),NULL,NULL);
528 strcpy( buf, "\033]2;" );
529 if (GetConsoleTitleA( buf + 4, sizeof(buf) - 5 ))
531 strcat( buf, "\a" );
532 WriteFile(handle,buf,strlen(buf),NULL,NULL);
534 return TRUE;
539 /***********************************************************************
540 * AllocConsole (KERNEL32.103)
542 * creates an xterm with a pty to our program
544 BOOL WINAPI AllocConsole(VOID)
546 struct alloc_console_request *req = get_req_buffer();
547 HANDLE hStderr;
548 int handle_in, handle_out;
550 TRACE("()\n");
551 req->access = GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE;
552 req->inherit = FALSE;
553 if (server_call( REQ_ALLOC_CONSOLE )) return FALSE;
554 handle_in = req->handle_in;
555 handle_out = req->handle_out;
557 if (!DuplicateHandle( GetCurrentProcess(), req->handle_out, GetCurrentProcess(), &hStderr,
558 0, TRUE, DUPLICATE_SAME_ACCESS ))
560 CloseHandle( handle_in );
561 CloseHandle( handle_out );
562 FreeConsole();
563 return FALSE;
566 /* NT resets the STD_*_HANDLEs on console alloc */
567 SetStdHandle( STD_INPUT_HANDLE, handle_in );
568 SetStdHandle( STD_OUTPUT_HANDLE, handle_out );
569 SetStdHandle( STD_ERROR_HANDLE, hStderr );
571 SetLastError(ERROR_SUCCESS);
572 SetConsoleTitleA("Wine Console");
573 return TRUE;
577 /******************************************************************************
578 * GetConsoleCP [KERNEL32.295] Returns the OEM code page for the console
580 * RETURNS
581 * Code page code
583 UINT WINAPI GetConsoleCP(VOID)
585 return GetACP();
589 /***********************************************************************
590 * GetConsoleOutputCP (KERNEL32.189)
592 UINT WINAPI GetConsoleOutputCP(VOID)
594 return GetConsoleCP();
597 /***********************************************************************
598 * GetConsoleMode (KERNEL32.188)
600 BOOL WINAPI GetConsoleMode(HANDLE hcon,LPDWORD mode)
602 BOOL ret = FALSE;
603 struct get_console_mode_request *req = get_req_buffer();
604 req->handle = hcon;
605 if (!server_call( REQ_GET_CONSOLE_MODE ))
607 if (mode) *mode = req->mode;
608 ret = TRUE;
610 return ret;
614 /******************************************************************************
615 * SetConsoleMode [KERNEL32.628] Sets input mode of console's input buffer
617 * PARAMS
618 * hcon [I] Handle to console input or screen buffer
619 * mode [I] Input or output mode to set
621 * RETURNS
622 * Success: TRUE
623 * Failure: FALSE
625 BOOL WINAPI SetConsoleMode( HANDLE hcon, DWORD mode )
627 struct set_console_mode_request *req = get_req_buffer();
628 req->handle = hcon;
629 req->mode = mode;
630 return !server_call( REQ_SET_CONSOLE_MODE );
634 /***********************************************************************
635 * GetConsoleTitleA (KERNEL32.191)
637 DWORD WINAPI GetConsoleTitleA(LPSTR title,DWORD size)
639 struct get_console_info_request *req = get_req_buffer();
640 DWORD ret = 0;
641 HANDLE hcon;
643 if ((hcon = CreateFileA( "CONOUT$", GENERIC_READ, 0, NULL,
644 OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
645 return 0;
646 req->handle = hcon;
647 if (!server_call( REQ_GET_CONSOLE_INFO ))
649 lstrcpynA( title, req->title, size );
650 ret = strlen(req->title);
652 CloseHandle( hcon );
653 return ret;
657 /******************************************************************************
658 * GetConsoleTitle32W [KERNEL32.192] Retrieves title string for console
660 * PARAMS
661 * title [O] Address of buffer for title
662 * size [I] Size of buffer
664 * RETURNS
665 * Success: Length of string copied
666 * Failure: 0
668 DWORD WINAPI GetConsoleTitleW( LPWSTR title, DWORD size )
670 char *tmp;
671 DWORD ret;
673 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, size ))) return 0;
674 ret = GetConsoleTitleA( tmp, size );
675 lstrcpyAtoW( title, tmp );
676 HeapFree( GetProcessHeap(), 0, tmp );
677 return ret;
681 /***********************************************************************
682 * WriteConsoleA (KERNEL32.729)
684 BOOL WINAPI WriteConsoleA( HANDLE hConsoleOutput,
685 LPCVOID lpBuffer,
686 DWORD nNumberOfCharsToWrite,
687 LPDWORD lpNumberOfCharsWritten,
688 LPVOID lpReserved )
690 /* FIXME: should I check if this is a console handle? */
691 return WriteFile(hConsoleOutput, lpBuffer, nNumberOfCharsToWrite,
692 lpNumberOfCharsWritten, NULL);
696 #define CADD(c) \
697 if (bufused==curbufsize-1) \
698 buffer = HeapReAlloc(GetProcessHeap(),0,buffer,(curbufsize+=100));\
699 buffer[bufused++]=c;
700 #define SADD(s) { char *x=s;while (*x) {CADD(*x);x++;}}
702 /***********************************************************************
703 * WriteConsoleOutputA (KERNEL32.732)
705 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput,
706 LPCHAR_INFO lpBuffer,
707 COORD dwBufferSize,
708 COORD dwBufferCoord,
709 LPSMALL_RECT lpWriteRegion)
711 int i,j,off=0,lastattr=-1;
712 char sbuf[20],*buffer=NULL;
713 int bufused=0,curbufsize = 100;
714 DWORD res;
715 const int colormap[8] = {
716 0,4,2,6,
717 1,5,3,7,
719 CONSOLE_make_complex(hConsoleOutput);
720 buffer = HeapAlloc(GetProcessHeap(),0,100);
721 curbufsize = 100;
723 TRACE("wr: top = %d, bottom=%d, left=%d,right=%d\n",
724 lpWriteRegion->Top,
725 lpWriteRegion->Bottom,
726 lpWriteRegion->Left,
727 lpWriteRegion->Right
730 for (i=lpWriteRegion->Top;i<=lpWriteRegion->Bottom;i++) {
731 sprintf(sbuf,"%c[%d;%dH",27,i+1,lpWriteRegion->Left+1);
732 SADD(sbuf);
733 for (j=lpWriteRegion->Left;j<=lpWriteRegion->Right;j++) {
734 if (lastattr!=lpBuffer[off].Attributes) {
735 lastattr = lpBuffer[off].Attributes;
736 sprintf(sbuf,"%c[0;%s3%d;4%dm",
738 (lastattr & FOREGROUND_INTENSITY)?"1;":"",
739 colormap[lastattr&7],
740 colormap[(lastattr&0x70)>>4]
742 /* FIXME: BACKGROUND_INTENSITY */
743 SADD(sbuf);
745 CADD(lpBuffer[off].Char.AsciiChar);
746 off++;
749 sprintf(sbuf,"%c[0m",27);SADD(sbuf);
750 WriteFile(hConsoleOutput,buffer,bufused,&res,NULL);
751 HeapFree(GetProcessHeap(),0,buffer);
752 return TRUE;
755 /***********************************************************************
756 * WriteConsoleW (KERNEL32.577)
758 BOOL WINAPI WriteConsoleW( HANDLE hConsoleOutput,
759 LPCVOID lpBuffer,
760 DWORD nNumberOfCharsToWrite,
761 LPDWORD lpNumberOfCharsWritten,
762 LPVOID lpReserved )
764 BOOL ret;
765 LPSTR xstring=HeapAlloc( GetProcessHeap(), 0, nNumberOfCharsToWrite );
767 lstrcpynWtoA( xstring, lpBuffer,nNumberOfCharsToWrite);
769 /* FIXME: should I check if this is a console handle? */
770 ret= WriteFile(hConsoleOutput, xstring, nNumberOfCharsToWrite,
771 lpNumberOfCharsWritten, NULL);
772 HeapFree( GetProcessHeap(), 0, xstring );
773 return ret;
777 /***********************************************************************
778 * ReadConsoleA (KERNEL32.419)
780 BOOL WINAPI ReadConsoleA( HANDLE hConsoleInput,
781 LPVOID lpBuffer,
782 DWORD nNumberOfCharsToRead,
783 LPDWORD lpNumberOfCharsRead,
784 LPVOID lpReserved )
786 int charsread = 0;
787 LPSTR xbuf = (LPSTR)lpBuffer;
788 LPINPUT_RECORD ir;
790 TRACE("(%d,%p,%ld,%p,%p)\n",
791 hConsoleInput,lpBuffer,nNumberOfCharsToRead,
792 lpNumberOfCharsRead,lpReserved
795 CONSOLE_get_input(hConsoleInput,FALSE);
797 /* FIXME: should we read at least 1 char? The SDK does not say */
798 while (charsread<nNumberOfCharsToRead)
800 struct read_console_input_request *req = get_req_buffer();
801 req->handle = hConsoleInput;
802 req->count = 1;
803 req->flush = 1;
804 if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
805 if (!req->read) break;
806 ir = (LPINPUT_RECORD)(req+1);
807 if (!ir->Event.KeyEvent.bKeyDown)
808 continue;
809 if (ir->EventType != KEY_EVENT)
810 continue;
811 *xbuf++ = ir->Event.KeyEvent.uChar.AsciiChar;
812 charsread++;
814 if (lpNumberOfCharsRead)
815 *lpNumberOfCharsRead = charsread;
816 return TRUE;
819 /***********************************************************************
820 * ReadConsoleW (KERNEL32.427)
822 BOOL WINAPI ReadConsoleW( HANDLE hConsoleInput,
823 LPVOID lpBuffer,
824 DWORD nNumberOfCharsToRead,
825 LPDWORD lpNumberOfCharsRead,
826 LPVOID lpReserved )
828 BOOL ret;
829 LPSTR buf = (LPSTR)HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead);
831 ret = ReadConsoleA(
832 hConsoleInput,
833 buf,
834 nNumberOfCharsToRead,
835 lpNumberOfCharsRead,
836 lpReserved
838 if (ret)
839 lstrcpynAtoW(lpBuffer,buf,nNumberOfCharsToRead);
840 HeapFree( GetProcessHeap(), 0, buf );
841 return ret;
845 /******************************************************************************
846 * ReadConsoleInput32A [KERNEL32.569] Reads data from a console
848 * PARAMS
849 * hConsoleInput [I] Handle to console input buffer
850 * lpBuffer [O] Address of buffer for read data
851 * nLength [I] Number of records to read
852 * lpNumberOfEventsRead [O] Address of number of records read
854 * RETURNS
855 * Success: TRUE
856 * Failure: FALSE
858 BOOL WINAPI ReadConsoleInputA(HANDLE hConsoleInput, LPINPUT_RECORD lpBuffer,
859 DWORD nLength, LPDWORD lpNumberOfEventsRead)
861 struct read_console_input_request *req = get_req_buffer();
863 /* loop until we get at least one event */
864 for (;;)
866 req->handle = hConsoleInput;
867 req->count = nLength;
868 req->flush = 1;
869 if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
870 if (req->read)
872 memcpy( lpBuffer, req + 1, req->read * sizeof(*lpBuffer) );
873 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = req->read;
874 return TRUE;
876 CONSOLE_get_input(hConsoleInput,TRUE);
877 /*WaitForSingleObject( hConsoleInput, INFINITE32 );*/
882 /***********************************************************************
883 * ReadConsoleInput32W (KERNEL32.570)
885 BOOL WINAPI ReadConsoleInputW( HANDLE handle, LPINPUT_RECORD buffer,
886 DWORD count, LPDWORD read )
888 /* FIXME: Fix this if we get UNICODE input. */
889 return ReadConsoleInputA( handle, buffer, count, read );
893 /***********************************************************************
894 * FlushConsoleInputBuffer (KERNEL32.132)
896 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
898 struct read_console_input_request *req = get_req_buffer();
899 req->handle = handle;
900 req->count = -1; /* get all records */
901 req->flush = 1;
902 return !server_call( REQ_READ_CONSOLE_INPUT );
906 /***********************************************************************
907 * PeekConsoleInputA (KERNEL32.550)
909 * Gets 'count' first events (or less) from input queue.
911 * Does not need a complex console.
913 BOOL WINAPI PeekConsoleInputA( HANDLE handle, LPINPUT_RECORD buffer,
914 DWORD count, LPDWORD read )
916 struct read_console_input_request *req = get_req_buffer();
918 CONSOLE_get_input(handle,FALSE);
920 req->handle = handle;
921 req->count = count;
922 req->flush = 0;
923 if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
924 if (req->read) memcpy( buffer, req + 1, req->read * sizeof(*buffer) );
925 if (read) *read = req->read;
926 return TRUE;
930 /***********************************************************************
931 * PeekConsoleInputW (KERNEL32.551)
933 BOOL WINAPI PeekConsoleInputW(HANDLE hConsoleInput,
934 LPINPUT_RECORD pirBuffer,
935 DWORD cInRecords,
936 LPDWORD lpcRead)
938 /* FIXME: Hmm. Fix this if we get UNICODE input. */
939 return PeekConsoleInputA(hConsoleInput,pirBuffer,cInRecords,lpcRead);
943 /******************************************************************************
944 * WriteConsoleInput32A [KERNEL32.730] Write data to a console input buffer
947 BOOL WINAPI WriteConsoleInputA( HANDLE handle, INPUT_RECORD *buffer,
948 DWORD count, LPDWORD written )
950 struct write_console_input_request *req = get_req_buffer();
951 const DWORD max = server_remaining( req + 1 ) / sizeof(INPUT_RECORD);
953 if (written) *written = 0;
954 while (count)
956 DWORD len = count < max ? count : max;
957 req->count = len;
958 req->handle = handle;
959 memcpy( req + 1, buffer, len * sizeof(*buffer) );
960 if (server_call( REQ_WRITE_CONSOLE_INPUT )) return FALSE;
961 if (written) *written += req->written;
962 count -= len;
963 buffer += len;
965 return TRUE;
969 /***********************************************************************
970 * SetConsoleTitle32A (KERNEL32.476)
972 * Sets the console title.
974 * We do not necessarily need to create a complex console for that,
975 * but should remember the title and set it on creation of the latter.
976 * (not fixed at this time).
978 BOOL WINAPI SetConsoleTitleA(LPCSTR title)
980 struct set_console_info_request *req = get_req_buffer();
981 HANDLE hcon;
982 DWORD written;
984 if ((hcon = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, NULL,
985 OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
986 return FALSE;
987 req->handle = hcon;
988 req->mask = SET_CONSOLE_INFO_TITLE;
989 lstrcpynA( req->title, title, server_remaining(req->title) );
990 if (server_call( REQ_SET_CONSOLE_INFO )) goto error;
991 if (CONSOLE_GetPid( hcon ))
993 /* only set title for complex console (own xterm) */
994 WriteFile( hcon, "\033]2;", 4, &written, NULL );
995 WriteFile( hcon, title, strlen(title), &written, NULL );
996 WriteFile( hcon, "\a", 1, &written, NULL );
998 CloseHandle( hcon );
999 return TRUE;
1000 error:
1001 CloseHandle( hcon );
1002 return FALSE;
1006 /******************************************************************************
1007 * SetConsoleTitle32W [KERNEL32.477] Sets title bar string for console
1009 * PARAMS
1010 * title [I] Address of new title
1012 * NOTES
1013 * This should not be calling the A version
1015 * RETURNS
1016 * Success: TRUE
1017 * Failure: FALSE
1019 BOOL WINAPI SetConsoleTitleW( LPCWSTR title )
1021 BOOL ret;
1023 LPSTR titleA = HEAP_strdupWtoA( GetProcessHeap(), 0, title );
1024 ret = SetConsoleTitleA(titleA);
1025 HeapFree( GetProcessHeap(), 0, titleA );
1026 return ret;
1029 /******************************************************************************
1030 * SetConsoleCursorPosition [KERNEL32.627]
1031 * Sets the cursor position in console
1033 * PARAMS
1034 * hConsoleOutput [I] Handle of console screen buffer
1035 * dwCursorPosition [I] New cursor position coordinates
1037 * RETURNS STD
1039 BOOL WINAPI SetConsoleCursorPosition( HANDLE hcon, COORD pos )
1041 char xbuf[20];
1042 DWORD xlen;
1044 /* make console complex only if we change lines, not just in the line */
1045 if (pos.y)
1046 CONSOLE_make_complex(hcon);
1048 TRACE("%d (%dx%d)\n", hcon, pos.x , pos.y );
1049 /* x are columns, y rows */
1050 if (pos.y)
1051 /* full screen cursor absolute positioning */
1052 sprintf(xbuf,"%c[%d;%dH", 0x1B, pos.y+1, pos.x+1);
1053 else
1054 /* relative cursor positioning in line (\r to go to 0) */
1055 sprintf(xbuf,"\r%c[%dC", 0x1B, pos.x);
1056 /* FIXME: store internal if we start using own console buffers */
1057 WriteFile(hcon,xbuf,strlen(xbuf),&xlen,NULL);
1058 return TRUE;
1061 /***********************************************************************
1062 * GetNumberOfConsoleInputEvents (KERNEL32.246)
1064 BOOL WINAPI GetNumberOfConsoleInputEvents(HANDLE hcon,LPDWORD nrofevents)
1066 CONSOLE_get_input(hcon,FALSE);
1067 *nrofevents = 1; /* UMM */
1068 return TRUE;
1071 /***********************************************************************
1072 * GetNumberOfConsoleMouseButtons (KERNEL32.358)
1074 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1076 FIXME("(%p): stub\n", nrofbuttons);
1077 *nrofbuttons = 2;
1078 return TRUE;
1081 /******************************************************************************
1082 * GetConsoleCursorInfo32 [KERNEL32.296] Gets size and visibility of console
1084 * PARAMS
1085 * hcon [I] Handle to console screen buffer
1086 * cinfo [O] Address of cursor information
1088 * RETURNS
1089 * Success: TRUE
1090 * Failure: FALSE
1092 BOOL WINAPI GetConsoleCursorInfo( HANDLE hcon, LPCONSOLE_CURSOR_INFO cinfo )
1094 struct get_console_info_request *req = get_req_buffer();
1095 req->handle = hcon;
1096 if (server_call( REQ_GET_CONSOLE_INFO )) return FALSE;
1097 if (cinfo)
1099 cinfo->dwSize = req->cursor_size;
1100 cinfo->bVisible = req->cursor_visible;
1102 return TRUE;
1106 /******************************************************************************
1107 * SetConsoleCursorInfo32 [KERNEL32.626] Sets size and visibility of cursor
1109 * RETURNS
1110 * Success: TRUE
1111 * Failure: FALSE
1113 BOOL WINAPI SetConsoleCursorInfo(
1114 HANDLE hcon, /* [in] Handle to console screen buffer */
1115 LPCONSOLE_CURSOR_INFO cinfo) /* [in] Address of cursor information */
1117 struct set_console_info_request *req = get_req_buffer();
1118 char buf[8];
1119 DWORD xlen;
1121 CONSOLE_make_complex(hcon);
1122 sprintf(buf,"\033[?25%c",cinfo->bVisible?'h':'l');
1123 WriteFile(hcon,buf,strlen(buf),&xlen,NULL);
1125 req->handle = hcon;
1126 req->cursor_size = cinfo->dwSize;
1127 req->cursor_visible = cinfo->bVisible;
1128 req->mask = SET_CONSOLE_INFO_CURSOR;
1129 return !server_call( REQ_SET_CONSOLE_INFO );
1133 /******************************************************************************
1134 * SetConsoleWindowInfo [KERNEL32.634] Sets size and position of console
1136 * RETURNS
1137 * Success: TRUE
1138 * Failure: FALSE
1140 BOOL WINAPI SetConsoleWindowInfo(
1141 HANDLE hcon, /* [in] Handle to console screen buffer */
1142 BOOL bAbsolute, /* [in] Coordinate type flag */
1143 LPSMALL_RECT window) /* [in] Address of new window rectangle */
1145 FIXME("(%x,%d,%p): stub\n", hcon, bAbsolute, window);
1146 return TRUE;
1150 /******************************************************************************
1151 * SetConsoleTextAttribute32 [KERNEL32.631] Sets colors for text
1153 * Sets the foreground and background color attributes of characters
1154 * written to the screen buffer.
1156 * RETURNS
1157 * Success: TRUE
1158 * Failure: FALSE
1160 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput,WORD wAttr)
1162 const int colormap[8] = {
1163 0,4,2,6,
1164 1,5,3,7,
1166 DWORD xlen;
1167 char buffer[20];
1169 TRACE("(%d,%d)\n",hConsoleOutput,wAttr);
1170 sprintf(buffer,"%c[0;%s3%d;4%dm",
1172 (wAttr & FOREGROUND_INTENSITY)?"1;":"",
1173 colormap[wAttr&7],
1174 colormap[(wAttr&0x70)>>4]
1176 WriteFile(hConsoleOutput,buffer,strlen(buffer),&xlen,NULL);
1177 return TRUE;
1181 /******************************************************************************
1182 * SetConsoleScreenBufferSize [KERNEL32.630] Changes size of console
1184 * PARAMS
1185 * hConsoleOutput [I] Handle to console screen buffer
1186 * dwSize [I] New size in character rows and cols
1188 * RETURNS
1189 * Success: TRUE
1190 * Failure: FALSE
1192 BOOL WINAPI SetConsoleScreenBufferSize( HANDLE hConsoleOutput,
1193 COORD dwSize )
1195 FIXME("(%d,%dx%d): stub\n",hConsoleOutput,dwSize.x,dwSize.y);
1196 return TRUE;
1200 /******************************************************************************
1201 * FillConsoleOutputCharacterA [KERNEL32.242]
1203 * PARAMS
1204 * hConsoleOutput [I] Handle to screen buffer
1205 * cCharacter [I] Character to write
1206 * nLength [I] Number of cells to write to
1207 * dwCoord [I] Coords of first cell
1208 * lpNumCharsWritten [O] Pointer to number of cells written
1210 * RETURNS
1211 * Success: TRUE
1212 * Failure: FALSE
1214 BOOL WINAPI FillConsoleOutputCharacterA(
1215 HANDLE hConsoleOutput,
1216 BYTE cCharacter,
1217 DWORD nLength,
1218 COORD dwCoord,
1219 LPDWORD lpNumCharsWritten)
1221 long count;
1222 DWORD xlen;
1224 SetConsoleCursorPosition(hConsoleOutput,dwCoord);
1225 for(count=0;count<nLength;count++)
1226 WriteFile(hConsoleOutput,&cCharacter,1,&xlen,NULL);
1227 *lpNumCharsWritten = nLength;
1228 return TRUE;
1232 /******************************************************************************
1233 * FillConsoleOutputCharacterW [KERNEL32.243] Writes characters to console
1235 * PARAMS
1236 * hConsoleOutput [I] Handle to screen buffer
1237 * cCharacter [I] Character to write
1238 * nLength [I] Number of cells to write to
1239 * dwCoord [I] Coords of first cell
1240 * lpNumCharsWritten [O] Pointer to number of cells written
1242 * RETURNS
1243 * Success: TRUE
1244 * Failure: FALSE
1246 BOOL WINAPI FillConsoleOutputCharacterW(HANDLE hConsoleOutput,
1247 WCHAR cCharacter,
1248 DWORD nLength,
1249 COORD dwCoord,
1250 LPDWORD lpNumCharsWritten)
1252 long count;
1253 DWORD xlen;
1255 SetConsoleCursorPosition(hConsoleOutput,dwCoord);
1256 /* FIXME: not quite correct ... but the lower part of UNICODE char comes
1257 * first
1259 for(count=0;count<nLength;count++)
1260 WriteFile(hConsoleOutput,&cCharacter,1,&xlen,NULL);
1261 *lpNumCharsWritten = nLength;
1262 return TRUE;
1266 /******************************************************************************
1267 * FillConsoleOutputAttribute [KERNEL32.241] Sets attributes for console
1269 * PARAMS
1270 * hConsoleOutput [I] Handle to screen buffer
1271 * wAttribute [I] Color attribute to write
1272 * nLength [I] Number of cells to write to
1273 * dwCoord [I] Coords of first cell
1274 * lpNumAttrsWritten [O] Pointer to number of cells written
1276 * RETURNS
1277 * Success: TRUE
1278 * Failure: FALSE
1280 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput,
1281 WORD wAttribute, DWORD nLength, COORD dwCoord,
1282 LPDWORD lpNumAttrsWritten)
1284 FIXME("(%d,%d,%ld,%dx%d,%p): stub\n", hConsoleOutput,
1285 wAttribute,nLength,dwCoord.x,dwCoord.y,lpNumAttrsWritten);
1286 *lpNumAttrsWritten = nLength;
1287 return TRUE;
1290 /******************************************************************************
1291 * ReadConsoleOutputCharacter32A [KERNEL32.573]
1293 * BUGS
1294 * Unimplemented
1296 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput,
1297 LPSTR lpstr, DWORD dword, COORD coord, LPDWORD lpdword)
1299 FIXME("(%d,%p,%ld,%dx%d,%p): stub\n", hConsoleOutput,lpstr,
1300 dword,coord.x,coord.y,lpdword);
1301 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1302 return FALSE;
1306 /******************************************************************************
1307 * ScrollConsoleScreenBuffer [KERNEL32.612]
1309 * BUGS
1310 * Unimplemented
1312 BOOL WINAPI ScrollConsoleScreenBuffer( HANDLE hConsoleOutput,
1313 LPSMALL_RECT lpScrollRect, LPSMALL_RECT lpClipRect,
1314 COORD dwDestOrigin, LPCHAR_INFO lpFill)
1316 FIXME("(%d,%p,%p,%dx%d,%p): stub\n", hConsoleOutput,lpScrollRect,
1317 lpClipRect,dwDestOrigin.x,dwDestOrigin.y,lpFill);
1318 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1319 return FALSE;