Release 990815.
[wine/multimedia.git] / win32 / console.c
blobca04d19977bebc03a6019dbc6d8949f39e50252b
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 #ifdef HAVE_SYS_ERRNO_H
33 #include <sys/errno.h>
34 #endif
35 #include <signal.h>
36 #include <assert.h>
38 #include "winbase.h"
39 #include "wine/winuser16.h"
40 #include "wine/keyboard16.h"
41 #include "thread.h"
42 #include "file.h"
43 #include "process.h"
44 #include "winerror.h"
45 #include "wincon.h"
46 #include "heap.h"
47 #include "server.h"
48 #include "debugtools.h"
50 DEFAULT_DEBUG_CHANNEL(console)
53 /* FIXME: Should be in an internal header file. OK, so which one?
54 Used by CONSOLE_makecomplex. */
55 int wine_openpty(int *master, int *slave, char *name,
56 struct termios *term, struct winsize *winsize);
58 /****************************************************************************
59 * CONSOLE_GetPid
61 static int CONSOLE_GetPid( HANDLE handle )
63 struct get_console_info_request *req = get_req_buffer();
64 req->handle = handle;
65 if (server_call( REQ_GET_CONSOLE_INFO )) return 0;
66 return req->pid;
69 /****************************************************************************
70 * XTERM_string_to_IR [internal]
72 * Transfers a string read from XTERM to INPUT_RECORDs and adds them to the
73 * queue. Does translation of vt100 style function keys and xterm-mouse clicks.
75 static void
76 CONSOLE_string_to_IR( HANDLE hConsoleInput,unsigned char *buf,int len) {
77 int j,k;
78 INPUT_RECORD ir;
79 DWORD junk;
81 for (j=0;j<len;j++) {
82 unsigned char inchar = buf[j];
84 if (inchar!=27) { /* no escape -> 'normal' keyboard event */
85 ir.EventType = 1; /* Key_event */
87 ir.Event.KeyEvent.bKeyDown = 1;
88 ir.Event.KeyEvent.wRepeatCount = 0;
90 ir.Event.KeyEvent.dwControlKeyState = 0;
91 if (inchar & 0x80) {
92 ir.Event.KeyEvent.dwControlKeyState|=LEFT_ALT_PRESSED;
93 inchar &= ~0x80;
95 ir.Event.KeyEvent.wVirtualKeyCode = VkKeyScan16(inchar);
96 if (ir.Event.KeyEvent.wVirtualKeyCode & 0x0100)
97 ir.Event.KeyEvent.dwControlKeyState|=SHIFT_PRESSED;
98 if (ir.Event.KeyEvent.wVirtualKeyCode & 0x0200)
99 ir.Event.KeyEvent.dwControlKeyState|=LEFT_CTRL_PRESSED;
100 if (ir.Event.KeyEvent.wVirtualKeyCode & 0x0400)
101 ir.Event.KeyEvent.dwControlKeyState|=LEFT_ALT_PRESSED;
102 ir.Event.KeyEvent.wVirtualScanCode = MapVirtualKey16(
103 ir.Event.KeyEvent.wVirtualKeyCode & 0x00ff,
104 0 /* VirtualKeyCodes to ScanCode */
106 ir.Event.KeyEvent.uChar.AsciiChar = inchar;
108 if (inchar==127) { /* backspace */
109 ir.Event.KeyEvent.uChar.AsciiChar = '\b'; /* FIXME: hmm */
110 ir.Event.KeyEvent.wVirtualScanCode = 0x0e;
111 ir.Event.KeyEvent.wVirtualKeyCode = VK_BACK;
112 } else {
113 if ((inchar=='\n')||(inchar=='\r')) {
114 ir.Event.KeyEvent.uChar.AsciiChar = '\r';
115 ir.Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
116 ir.Event.KeyEvent.wVirtualScanCode = 0x1c;
117 ir.Event.KeyEvent.dwControlKeyState = 0;
118 } else {
119 if (inchar<' ') {
120 /* FIXME: find good values for ^X */
121 ir.Event.KeyEvent.wVirtualKeyCode = 0xdead;
122 ir.Event.KeyEvent.wVirtualScanCode = 0xbeef;
127 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
128 ir.Event.KeyEvent.bKeyDown = 0;
129 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
130 continue;
132 /* inchar is ESC */
133 if ((j==len-1) || (buf[j+1]!='[')) {/* add ESCape on its own */
134 ir.EventType = 1; /* Key_event */
135 ir.Event.KeyEvent.bKeyDown = 1;
136 ir.Event.KeyEvent.wRepeatCount = 0;
138 ir.Event.KeyEvent.wVirtualKeyCode = VkKeyScan16(27);
139 ir.Event.KeyEvent.wVirtualScanCode = MapVirtualKey16(
140 ir.Event.KeyEvent.wVirtualKeyCode,0
142 ir.Event.KeyEvent.dwControlKeyState = 0;
143 ir.Event.KeyEvent.uChar.AsciiChar = 27;
144 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
145 ir.Event.KeyEvent.bKeyDown = 0;
146 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
147 continue;
149 for (k=j;k<len;k++) {
150 if (((buf[k]>='A') && (buf[k]<='Z')) ||
151 ((buf[k]>='a') && (buf[k]<='z')) ||
152 (buf[k]=='~')
154 break;
156 if (k<len) {
157 int subid,scancode=0;
159 ir.EventType = 1; /* Key_event */
160 ir.Event.KeyEvent.bKeyDown = 1;
161 ir.Event.KeyEvent.wRepeatCount = 0;
162 ir.Event.KeyEvent.dwControlKeyState = 0;
164 ir.Event.KeyEvent.wVirtualKeyCode = 0xad; /* FIXME */
165 ir.Event.KeyEvent.wVirtualScanCode = 0xad; /* FIXME */
166 ir.Event.KeyEvent.uChar.AsciiChar = 0;
168 switch (buf[k]) {
169 case '~':
170 sscanf(&buf[j+2],"%d",&subid);
171 switch (subid) {
172 case 2:/*INS */scancode = 0xe052;break;
173 case 3:/*DEL */scancode = 0xe053;break;
174 case 6:/*PGDW*/scancode = 0xe051;break;
175 case 5:/*PGUP*/scancode = 0xe049;break;
176 case 11:/*F1 */scancode = 0x003b;break;
177 case 12:/*F2 */scancode = 0x003c;break;
178 case 13:/*F3 */scancode = 0x003d;break;
179 case 14:/*F4 */scancode = 0x003e;break;
180 case 15:/*F5 */scancode = 0x003f;break;
181 case 17:/*F6 */scancode = 0x0040;break;
182 case 18:/*F7 */scancode = 0x0041;break;
183 case 19:/*F8 */scancode = 0x0042;break;
184 case 20:/*F9 */scancode = 0x0043;break;
185 case 21:/*F10 */scancode = 0x0044;break;
186 case 23:/*F11 */scancode = 0x00d9;break;
187 case 24:/*F12 */scancode = 0x00da;break;
188 /* FIXME: Shift-Fx */
189 default:
190 FIXME("parse ESC[%d~\n",subid);
191 break;
193 break;
194 case 'A': /* Cursor Up */scancode = 0xe048;break;
195 case 'B': /* Cursor Down */scancode = 0xe050;break;
196 case 'D': /* Cursor Left */scancode = 0xe04b;break;
197 case 'C': /* Cursor Right */scancode = 0xe04d;break;
198 case 'F': /* End */scancode = 0xe04f;break;
199 case 'H': /* Home */scancode = 0xe047;break;
200 case 'M':
201 /* Mouse Button Press (ESCM<button+'!'><x+'!'><y+'!'>) or
202 * Release (ESCM#<x+'!'><y+'!'>
204 if (k<len-3) {
205 ir.EventType = MOUSE_EVENT;
206 ir.Event.MouseEvent.dwMousePosition.x = buf[k+2]-'!';
207 ir.Event.MouseEvent.dwMousePosition.y = buf[k+3]-'!';
208 if (buf[k+1]=='#')
209 ir.Event.MouseEvent.dwButtonState = 0;
210 else
211 ir.Event.MouseEvent.dwButtonState = 1<<(buf[k+1]-' ');
212 ir.Event.MouseEvent.dwEventFlags = 0; /* FIXME */
213 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk));
214 j=k+3;
216 break;
217 case 'c':
218 j=k;
219 break;
221 if (scancode) {
222 ir.Event.KeyEvent.wVirtualScanCode = scancode;
223 ir.Event.KeyEvent.wVirtualKeyCode = MapVirtualKey16(scancode,1);
224 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
225 ir.Event.KeyEvent.bKeyDown = 0;
226 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
227 j=k;
228 continue;
234 /****************************************************************************
235 * CONSOLE_get_input (internal)
237 * Reads (nonblocking) as much input events as possible and stores them
238 * in an internal queue.
240 static void
241 CONSOLE_get_input( HANDLE handle, BOOL blockwait )
243 char *buf = HeapAlloc(GetProcessHeap(),0,1);
244 int len = 0;
246 while (1)
248 DWORD res;
249 char inchar;
250 if (WaitForSingleObject( handle, 0 )) break;
251 if (!ReadFile( handle, &inchar, 1, &res, NULL )) break;
252 if (!res) /* res 0 but readable means EOF? Hmm. */
253 break;
254 buf = HeapReAlloc(GetProcessHeap(),0,buf,len+1);
255 buf[len++]=inchar;
257 CONSOLE_string_to_IR(handle,buf,len);
258 HeapFree(GetProcessHeap(),0,buf);
261 /******************************************************************************
262 * SetConsoleCtrlHandler [KERNEL32.459] Adds function to calling process list
264 * PARAMS
265 * func [I] Address of handler function
266 * add [I] Handler to add or remove
268 * RETURNS
269 * Success: TRUE
270 * Failure: FALSE
272 * CHANGED
273 * James Sutherland (JamesSutherland@gmx.de)
274 * Added global variables console_ignore_ctrl_c and handlers[]
275 * Does not yet do any error checking, or set LastError if failed.
276 * This doesn't yet matter, since these handlers are not yet called...!
278 static unsigned int console_ignore_ctrl_c = 0;
279 static HANDLER_ROUTINE *handlers[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
280 BOOL WINAPI SetConsoleCtrlHandler( HANDLER_ROUTINE *func, BOOL add )
282 unsigned int alloc_loop = sizeof(handlers)/sizeof(HANDLER_ROUTINE *);
283 unsigned int done = 0;
284 FIXME("(%p,%i) - no error checking or testing yet\n", func, add);
285 if (!func)
287 console_ignore_ctrl_c = add;
288 return TRUE;
290 if (add)
292 for (;alloc_loop--;)
293 if (!handlers[alloc_loop] && !done)
295 handlers[alloc_loop] = func;
296 done++;
298 if (!done)
299 FIXME("Out of space on CtrlHandler table\n");
300 return(done);
302 else
304 for (;alloc_loop--;)
305 if (handlers[alloc_loop] == func && !done)
307 handlers[alloc_loop] = 0;
308 done++;
310 if (!done)
311 WARN("Attempt to remove non-installed CtrlHandler %p\n",
312 func);
313 return (done);
315 return (done);
319 /******************************************************************************
320 * GenerateConsoleCtrlEvent [KERNEL32.275] Simulate a CTRL-C or CTRL-BREAK
322 * PARAMS
323 * dwCtrlEvent [I] Type of event
324 * dwProcessGroupID [I] Process group ID to send event to
326 * NOTES
327 * Doesn't yet work...!
329 * RETURNS
330 * Success: True
331 * Failure: False (and *should* [but doesn't] set LastError)
333 BOOL WINAPI GenerateConsoleCtrlEvent( DWORD dwCtrlEvent,
334 DWORD dwProcessGroupID )
336 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
338 ERR("invalid event %d for PGID %ld\n",
339 (unsigned short)dwCtrlEvent, dwProcessGroupID );
340 return FALSE;
342 if (dwProcessGroupID == GetCurrentProcessId() )
344 FIXME("Attempt to send event %d to self - stub\n",
345 (unsigned short)dwCtrlEvent );
346 return FALSE;
348 FIXME("event %d to external PGID %ld - not implemented yet\n",
349 (unsigned short)dwCtrlEvent, dwProcessGroupID );
350 return FALSE;
354 /******************************************************************************
355 * CreateConsoleScreenBuffer [KERNEL32.151] Creates a console screen buffer
357 * PARAMS
358 * dwDesiredAccess [I] Access flag
359 * dwShareMode [I] Buffer share mode
360 * sa [I] Security attributes
361 * dwFlags [I] Type of buffer to create
362 * lpScreenBufferData [I] Reserved
364 * NOTES
365 * Should call SetLastError
367 * RETURNS
368 * Success: Handle to new console screen buffer
369 * Failure: INVALID_HANDLE_VALUE
371 HANDLE WINAPI CreateConsoleScreenBuffer( DWORD dwDesiredAccess,
372 DWORD dwShareMode, LPSECURITY_ATTRIBUTES sa,
373 DWORD dwFlags, LPVOID lpScreenBufferData )
375 FIXME("(%ld,%ld,%p,%ld,%p): stub\n",dwDesiredAccess,
376 dwShareMode, sa, dwFlags, lpScreenBufferData);
377 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
378 return INVALID_HANDLE_VALUE;
382 /***********************************************************************
383 * GetConsoleScreenBufferInfo (KERNEL32.190)
385 BOOL WINAPI GetConsoleScreenBufferInfo( HANDLE hConsoleOutput,
386 LPCONSOLE_SCREEN_BUFFER_INFO csbi )
388 csbi->dwSize.x = 80;
389 csbi->dwSize.y = 24;
390 csbi->dwCursorPosition.x = 0;
391 csbi->dwCursorPosition.y = 0;
392 csbi->wAttributes = 0;
393 csbi->srWindow.Left = 0;
394 csbi->srWindow.Right = 79;
395 csbi->srWindow.Top = 0;
396 csbi->srWindow.Bottom = 23;
397 csbi->dwMaximumWindowSize.x = 80;
398 csbi->dwMaximumWindowSize.y = 24;
399 return TRUE;
403 /******************************************************************************
404 * SetConsoleActiveScreenBuffer [KERNEL32.623] Sets buffer to current console
406 * RETURNS
407 * Success: TRUE
408 * Failure: FALSE
410 BOOL WINAPI SetConsoleActiveScreenBuffer(
411 HANDLE hConsoleOutput) /* [in] Handle to console screen buffer */
413 FIXME("(%x): stub\n", hConsoleOutput);
414 return FALSE;
418 /***********************************************************************
419 * GetLargestConsoleWindowSize (KERNEL32.226)
421 DWORD WINAPI GetLargestConsoleWindowSize( HANDLE hConsoleOutput )
423 return (DWORD)MAKELONG(80,24);
426 /***********************************************************************
427 * FreeConsole (KERNEL32.267)
429 BOOL WINAPI FreeConsole(VOID)
431 return !server_call( REQ_FREE_CONSOLE );
435 /*************************************************************************
436 * CONSOLE_OpenHandle
438 * Open a handle to the current process console.
440 HANDLE CONSOLE_OpenHandle( BOOL output, DWORD access, LPSECURITY_ATTRIBUTES sa )
442 int ret = -1;
443 struct open_console_request *req = get_req_buffer();
445 req->output = output;
446 req->access = access;
447 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
448 SetLastError(0);
449 if (!server_call( REQ_OPEN_CONSOLE )) ret = req->handle;
450 return ret;
454 /*************************************************************************
455 * CONSOLE_make_complex [internal]
457 * Turns a CONSOLE kernel object into a complex one.
458 * (switches from output/input using the terminal where WINE was started to
459 * its own xterm).
461 * This makes simple commandline tools pipeable, while complex commandline
462 * tools work without getting messed up by debugoutput.
464 * All other functions should work indedependend from this call.
466 * To test for complex console: pid == 0 -> simple, otherwise complex.
468 static BOOL CONSOLE_make_complex(HANDLE handle)
470 struct set_console_fd_request *req = get_req_buffer();
471 struct termios term;
472 char buf[256];
473 char c = '\0';
474 int i,xpid,master,slave,pty_handle;
476 if (CONSOLE_GetPid( handle )) return TRUE; /* already complex */
478 MESSAGE("Console: Making console complex (creating an xterm)...\n");
480 if (tcgetattr(0, &term) < 0) {
481 /* ignore failure, or we can't run from a script */
483 term.c_lflag = ~(ECHO|ICANON);
485 if (wine_openpty(&master, &slave, NULL, &term, NULL) < 0)
486 return FALSE;
488 if ((xpid=fork()) == 0) {
489 tcsetattr(slave, TCSADRAIN, &term);
490 close( slave );
491 sprintf(buf, "-Sxx%d", master);
492 /* "-fn vga" for VGA font. Harmless if vga is not present:
493 * xterm: unable to open font "vga", trying "fixed"....
495 execlp("xterm", "xterm", buf, "-fn","vga",NULL);
496 ERR("error creating AllocConsole xterm\n");
497 exit(1);
499 pty_handle = FILE_DupUnixHandle( slave, GENERIC_READ | GENERIC_WRITE );
500 close( master );
501 close( slave );
502 if (pty_handle == -1) return FALSE;
504 /* most xterms like to print their window ID when used with -S;
505 * read it and continue before the user has a chance...
507 for (i = 0; i < 10000; i++)
509 BOOL ok = ReadFile( pty_handle, &c, 1, NULL, NULL );
510 if (!ok && !c) usleep(100); /* wait for xterm to be created */
511 else if (c == '\n') break;
513 if (i == 10000)
515 ERR("can't read xterm WID\n");
516 CloseHandle( pty_handle );
517 return FALSE;
519 req->handle = handle;
520 req->file_handle = pty_handle;
521 req->pid = xpid;
522 server_call( REQ_SET_CONSOLE_FD );
523 CloseHandle( pty_handle );
525 /* enable mouseclicks */
526 strcpy( buf, "\033[?1001s\033[?1000h" );
527 WriteFile(handle,buf,strlen(buf),NULL,NULL);
529 strcpy( buf, "\033]2;" );
530 if (GetConsoleTitleA( buf + 4, sizeof(buf) - 5 ))
532 strcat( buf, "\a" );
533 WriteFile(handle,buf,strlen(buf),NULL,NULL);
535 return TRUE;
540 /***********************************************************************
541 * AllocConsole (KERNEL32.103)
543 * creates an xterm with a pty to our program
545 BOOL WINAPI AllocConsole(VOID)
547 struct alloc_console_request *req = get_req_buffer();
548 HANDLE hStderr;
549 int handle_in, handle_out;
551 TRACE("()\n");
552 req->access = GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE;
553 req->inherit = FALSE;
554 if (server_call( REQ_ALLOC_CONSOLE )) return FALSE;
555 handle_in = req->handle_in;
556 handle_out = req->handle_out;
558 if (!DuplicateHandle( GetCurrentProcess(), req->handle_out, GetCurrentProcess(), &hStderr,
559 0, TRUE, DUPLICATE_SAME_ACCESS ))
561 CloseHandle( handle_in );
562 CloseHandle( handle_out );
563 FreeConsole();
564 return FALSE;
567 /* NT resets the STD_*_HANDLEs on console alloc */
568 SetStdHandle( STD_INPUT_HANDLE, handle_in );
569 SetStdHandle( STD_OUTPUT_HANDLE, handle_out );
570 SetStdHandle( STD_ERROR_HANDLE, hStderr );
572 SetLastError(ERROR_SUCCESS);
573 SetConsoleTitleA("Wine Console");
574 return TRUE;
578 /******************************************************************************
579 * GetConsoleCP [KERNEL32.295] Returns the OEM code page for the console
581 * RETURNS
582 * Code page code
584 UINT WINAPI GetConsoleCP(VOID)
586 return GetACP();
590 /***********************************************************************
591 * GetConsoleOutputCP (KERNEL32.189)
593 UINT WINAPI GetConsoleOutputCP(VOID)
595 return GetConsoleCP();
598 /***********************************************************************
599 * GetConsoleMode (KERNEL32.188)
601 BOOL WINAPI GetConsoleMode(HANDLE hcon,LPDWORD mode)
603 BOOL ret = FALSE;
604 struct get_console_mode_request *req = get_req_buffer();
605 req->handle = hcon;
606 if (!server_call( REQ_GET_CONSOLE_MODE ))
608 if (mode) *mode = req->mode;
609 ret = TRUE;
611 return ret;
615 /******************************************************************************
616 * SetConsoleMode [KERNEL32.628] Sets input mode of console's input buffer
618 * PARAMS
619 * hcon [I] Handle to console input or screen buffer
620 * mode [I] Input or output mode to set
622 * RETURNS
623 * Success: TRUE
624 * Failure: FALSE
626 BOOL WINAPI SetConsoleMode( HANDLE hcon, DWORD mode )
628 struct set_console_mode_request *req = get_req_buffer();
629 req->handle = hcon;
630 req->mode = mode;
631 return !server_call( REQ_SET_CONSOLE_MODE );
635 /***********************************************************************
636 * GetConsoleTitleA (KERNEL32.191)
638 DWORD WINAPI GetConsoleTitleA(LPSTR title,DWORD size)
640 struct get_console_info_request *req = get_req_buffer();
641 DWORD ret = 0;
642 HANDLE hcon;
644 if ((hcon = CreateFileA( "CONOUT$", GENERIC_READ, 0, NULL,
645 OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
646 return 0;
647 req->handle = hcon;
648 if (!server_call( REQ_GET_CONSOLE_INFO ))
650 lstrcpynA( title, req->title, size );
651 ret = strlen(req->title);
653 CloseHandle( hcon );
654 return ret;
658 /******************************************************************************
659 * GetConsoleTitle32W [KERNEL32.192] Retrieves title string for console
661 * PARAMS
662 * title [O] Address of buffer for title
663 * size [I] Size of buffer
665 * RETURNS
666 * Success: Length of string copied
667 * Failure: 0
669 DWORD WINAPI GetConsoleTitleW( LPWSTR title, DWORD size )
671 char *tmp;
672 DWORD ret;
674 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, size ))) return 0;
675 ret = GetConsoleTitleA( tmp, size );
676 lstrcpyAtoW( title, tmp );
677 HeapFree( GetProcessHeap(), 0, tmp );
678 return ret;
682 /***********************************************************************
683 * WriteConsoleA (KERNEL32.729)
685 BOOL WINAPI WriteConsoleA( HANDLE hConsoleOutput,
686 LPCVOID lpBuffer,
687 DWORD nNumberOfCharsToWrite,
688 LPDWORD lpNumberOfCharsWritten,
689 LPVOID lpReserved )
691 /* FIXME: should I check if this is a console handle? */
692 return WriteFile(hConsoleOutput, lpBuffer, nNumberOfCharsToWrite,
693 lpNumberOfCharsWritten, NULL);
697 #define CADD(c) \
698 if (bufused==curbufsize-1) \
699 buffer = HeapReAlloc(GetProcessHeap(),0,buffer,(curbufsize+=100));\
700 buffer[bufused++]=c;
701 #define SADD(s) { char *x=s;while (*x) {CADD(*x);x++;}}
703 /***********************************************************************
704 * WriteConsoleOutputA (KERNEL32.732)
706 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput,
707 LPCHAR_INFO lpBuffer,
708 COORD dwBufferSize,
709 COORD dwBufferCoord,
710 LPSMALL_RECT lpWriteRegion)
712 int i,j,off=0,lastattr=-1;
713 char sbuf[20],*buffer=NULL;
714 int bufused=0,curbufsize = 100;
715 DWORD res;
716 const int colormap[8] = {
717 0,4,2,6,
718 1,5,3,7,
720 CONSOLE_make_complex(hConsoleOutput);
721 buffer = HeapAlloc(GetProcessHeap(),0,100);
722 curbufsize = 100;
724 TRACE("wr: top = %d, bottom=%d, left=%d,right=%d\n",
725 lpWriteRegion->Top,
726 lpWriteRegion->Bottom,
727 lpWriteRegion->Left,
728 lpWriteRegion->Right
731 for (i=lpWriteRegion->Top;i<=lpWriteRegion->Bottom;i++) {
732 sprintf(sbuf,"%c[%d;%dH",27,i+1,lpWriteRegion->Left+1);
733 SADD(sbuf);
734 for (j=lpWriteRegion->Left;j<=lpWriteRegion->Right;j++) {
735 if (lastattr!=lpBuffer[off].Attributes) {
736 lastattr = lpBuffer[off].Attributes;
737 sprintf(sbuf,"%c[0;%s3%d;4%dm",
739 (lastattr & FOREGROUND_INTENSITY)?"1;":"",
740 colormap[lastattr&7],
741 colormap[(lastattr&0x70)>>4]
743 /* FIXME: BACKGROUND_INTENSITY */
744 SADD(sbuf);
746 CADD(lpBuffer[off].Char.AsciiChar);
747 off++;
750 sprintf(sbuf,"%c[0m",27);SADD(sbuf);
751 WriteFile(hConsoleOutput,buffer,bufused,&res,NULL);
752 HeapFree(GetProcessHeap(),0,buffer);
753 return TRUE;
756 /***********************************************************************
757 * WriteConsoleW (KERNEL32.577)
759 BOOL WINAPI WriteConsoleW( HANDLE hConsoleOutput,
760 LPCVOID lpBuffer,
761 DWORD nNumberOfCharsToWrite,
762 LPDWORD lpNumberOfCharsWritten,
763 LPVOID lpReserved )
765 BOOL ret;
766 LPSTR xstring=HeapAlloc( GetProcessHeap(), 0, nNumberOfCharsToWrite );
768 lstrcpynWtoA( xstring, lpBuffer,nNumberOfCharsToWrite);
770 /* FIXME: should I check if this is a console handle? */
771 ret= WriteFile(hConsoleOutput, xstring, nNumberOfCharsToWrite,
772 lpNumberOfCharsWritten, NULL);
773 HeapFree( GetProcessHeap(), 0, xstring );
774 return ret;
778 /***********************************************************************
779 * ReadConsoleA (KERNEL32.419)
781 BOOL WINAPI ReadConsoleA( HANDLE hConsoleInput,
782 LPVOID lpBuffer,
783 DWORD nNumberOfCharsToRead,
784 LPDWORD lpNumberOfCharsRead,
785 LPVOID lpReserved )
787 int charsread = 0;
788 LPSTR xbuf = (LPSTR)lpBuffer;
789 LPINPUT_RECORD ir;
791 TRACE("(%d,%p,%ld,%p,%p)\n",
792 hConsoleInput,lpBuffer,nNumberOfCharsToRead,
793 lpNumberOfCharsRead,lpReserved
796 CONSOLE_get_input(hConsoleInput,FALSE);
798 /* FIXME: should we read at least 1 char? The SDK does not say */
799 while (charsread<nNumberOfCharsToRead)
801 struct read_console_input_request *req = get_req_buffer();
802 req->handle = hConsoleInput;
803 req->count = 1;
804 req->flush = 1;
805 if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
806 if (!req->read) break;
807 ir = (LPINPUT_RECORD)(req+1);
808 if (!ir->Event.KeyEvent.bKeyDown)
809 continue;
810 if (ir->EventType != KEY_EVENT)
811 continue;
812 *xbuf++ = ir->Event.KeyEvent.uChar.AsciiChar;
813 charsread++;
815 if (lpNumberOfCharsRead)
816 *lpNumberOfCharsRead = charsread;
817 return TRUE;
820 /***********************************************************************
821 * ReadConsoleW (KERNEL32.427)
823 BOOL WINAPI ReadConsoleW( HANDLE hConsoleInput,
824 LPVOID lpBuffer,
825 DWORD nNumberOfCharsToRead,
826 LPDWORD lpNumberOfCharsRead,
827 LPVOID lpReserved )
829 BOOL ret;
830 LPSTR buf = (LPSTR)HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead);
832 ret = ReadConsoleA(
833 hConsoleInput,
834 buf,
835 nNumberOfCharsToRead,
836 lpNumberOfCharsRead,
837 lpReserved
839 if (ret)
840 lstrcpynAtoW(lpBuffer,buf,nNumberOfCharsToRead);
841 HeapFree( GetProcessHeap(), 0, buf );
842 return ret;
846 /******************************************************************************
847 * ReadConsoleInput32A [KERNEL32.569] Reads data from a console
849 * PARAMS
850 * hConsoleInput [I] Handle to console input buffer
851 * lpBuffer [O] Address of buffer for read data
852 * nLength [I] Number of records to read
853 * lpNumberOfEventsRead [O] Address of number of records read
855 * RETURNS
856 * Success: TRUE
857 * Failure: FALSE
859 BOOL WINAPI ReadConsoleInputA(HANDLE hConsoleInput, LPINPUT_RECORD lpBuffer,
860 DWORD nLength, LPDWORD lpNumberOfEventsRead)
862 struct read_console_input_request *req = get_req_buffer();
864 /* loop until we get at least one event */
865 for (;;)
867 req->handle = hConsoleInput;
868 req->count = nLength;
869 req->flush = 1;
870 if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
871 if (req->read)
873 memcpy( lpBuffer, req + 1, req->read * sizeof(*lpBuffer) );
874 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = req->read;
875 return TRUE;
877 CONSOLE_get_input(hConsoleInput,TRUE);
878 /*WaitForSingleObject( hConsoleInput, INFINITE32 );*/
883 /***********************************************************************
884 * ReadConsoleInput32W (KERNEL32.570)
886 BOOL WINAPI ReadConsoleInputW( HANDLE handle, LPINPUT_RECORD buffer,
887 DWORD count, LPDWORD read )
889 /* FIXME: Fix this if we get UNICODE input. */
890 return ReadConsoleInputA( handle, buffer, count, read );
894 /***********************************************************************
895 * FlushConsoleInputBuffer (KERNEL32.132)
897 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
899 struct read_console_input_request *req = get_req_buffer();
900 req->handle = handle;
901 req->count = -1; /* get all records */
902 req->flush = 1;
903 return !server_call( REQ_READ_CONSOLE_INPUT );
907 /***********************************************************************
908 * PeekConsoleInputA (KERNEL32.550)
910 * Gets 'count' first events (or less) from input queue.
912 * Does not need a complex console.
914 BOOL WINAPI PeekConsoleInputA( HANDLE handle, LPINPUT_RECORD buffer,
915 DWORD count, LPDWORD read )
917 struct read_console_input_request *req = get_req_buffer();
919 CONSOLE_get_input(handle,FALSE);
921 req->handle = handle;
922 req->count = count;
923 req->flush = 0;
924 if (server_call( REQ_READ_CONSOLE_INPUT )) return FALSE;
925 if (req->read) memcpy( buffer, req + 1, req->read * sizeof(*buffer) );
926 if (read) *read = req->read;
927 return TRUE;
931 /***********************************************************************
932 * PeekConsoleInputW (KERNEL32.551)
934 BOOL WINAPI PeekConsoleInputW(HANDLE hConsoleInput,
935 LPINPUT_RECORD pirBuffer,
936 DWORD cInRecords,
937 LPDWORD lpcRead)
939 /* FIXME: Hmm. Fix this if we get UNICODE input. */
940 return PeekConsoleInputA(hConsoleInput,pirBuffer,cInRecords,lpcRead);
944 /******************************************************************************
945 * WriteConsoleInput32A [KERNEL32.730] Write data to a console input buffer
948 BOOL WINAPI WriteConsoleInputA( HANDLE handle, INPUT_RECORD *buffer,
949 DWORD count, LPDWORD written )
951 struct write_console_input_request *req = get_req_buffer();
952 const DWORD max = server_remaining( req + 1 ) / sizeof(INPUT_RECORD);
954 if (written) *written = 0;
955 while (count)
957 DWORD len = count < max ? count : max;
958 req->count = len;
959 req->handle = handle;
960 memcpy( req + 1, buffer, len * sizeof(*buffer) );
961 if (server_call( REQ_WRITE_CONSOLE_INPUT )) return FALSE;
962 if (written) *written += req->written;
963 count -= len;
964 buffer += len;
966 return TRUE;
970 /***********************************************************************
971 * SetConsoleTitle32A (KERNEL32.476)
973 * Sets the console title.
975 * We do not necessarily need to create a complex console for that,
976 * but should remember the title and set it on creation of the latter.
977 * (not fixed at this time).
979 BOOL WINAPI SetConsoleTitleA(LPCSTR title)
981 struct set_console_info_request *req = get_req_buffer();
982 HANDLE hcon;
983 DWORD written;
985 if ((hcon = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, NULL,
986 OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
987 return FALSE;
988 req->handle = hcon;
989 req->mask = SET_CONSOLE_INFO_TITLE;
990 lstrcpynA( req->title, title, server_remaining(req->title) );
991 if (server_call( REQ_SET_CONSOLE_INFO )) goto error;
992 if (CONSOLE_GetPid( hcon ))
994 /* only set title for complex console (own xterm) */
995 WriteFile( hcon, "\033]2;", 4, &written, NULL );
996 WriteFile( hcon, title, strlen(title), &written, NULL );
997 WriteFile( hcon, "\a", 1, &written, NULL );
999 CloseHandle( hcon );
1000 return TRUE;
1001 error:
1002 CloseHandle( hcon );
1003 return FALSE;
1007 /******************************************************************************
1008 * SetConsoleTitle32W [KERNEL32.477] Sets title bar string for console
1010 * PARAMS
1011 * title [I] Address of new title
1013 * NOTES
1014 * This should not be calling the A version
1016 * RETURNS
1017 * Success: TRUE
1018 * Failure: FALSE
1020 BOOL WINAPI SetConsoleTitleW( LPCWSTR title )
1022 BOOL ret;
1024 LPSTR titleA = HEAP_strdupWtoA( GetProcessHeap(), 0, title );
1025 ret = SetConsoleTitleA(titleA);
1026 HeapFree( GetProcessHeap(), 0, titleA );
1027 return ret;
1030 /******************************************************************************
1031 * SetConsoleCursorPosition [KERNEL32.627]
1032 * Sets the cursor position in console
1034 * PARAMS
1035 * hConsoleOutput [I] Handle of console screen buffer
1036 * dwCursorPosition [I] New cursor position coordinates
1038 * RETURNS STD
1040 BOOL WINAPI SetConsoleCursorPosition( HANDLE hcon, COORD pos )
1042 char xbuf[20];
1043 DWORD xlen;
1045 /* make console complex only if we change lines, not just in the line */
1046 if (pos.y)
1047 CONSOLE_make_complex(hcon);
1049 TRACE("%d (%dx%d)\n", hcon, pos.x , pos.y );
1050 /* x are columns, y rows */
1051 if (pos.y)
1052 /* full screen cursor absolute positioning */
1053 sprintf(xbuf,"%c[%d;%dH", 0x1B, pos.y+1, pos.x+1);
1054 else
1055 /* relative cursor positioning in line (\r to go to 0) */
1056 sprintf(xbuf,"\r%c[%dC", 0x1B, pos.x);
1057 /* FIXME: store internal if we start using own console buffers */
1058 WriteFile(hcon,xbuf,strlen(xbuf),&xlen,NULL);
1059 return TRUE;
1062 /***********************************************************************
1063 * GetNumberOfConsoleInputEvents (KERNEL32.246)
1065 BOOL WINAPI GetNumberOfConsoleInputEvents(HANDLE hcon,LPDWORD nrofevents)
1067 CONSOLE_get_input(hcon,FALSE);
1068 *nrofevents = 1; /* UMM */
1069 return TRUE;
1072 /***********************************************************************
1073 * GetNumberOfConsoleMouseButtons (KERNEL32.358)
1075 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1077 FIXME("(%p): stub\n", nrofbuttons);
1078 *nrofbuttons = 2;
1079 return TRUE;
1082 /******************************************************************************
1083 * GetConsoleCursorInfo32 [KERNEL32.296] Gets size and visibility of console
1085 * PARAMS
1086 * hcon [I] Handle to console screen buffer
1087 * cinfo [O] Address of cursor information
1089 * RETURNS
1090 * Success: TRUE
1091 * Failure: FALSE
1093 BOOL WINAPI GetConsoleCursorInfo( HANDLE hcon, LPCONSOLE_CURSOR_INFO cinfo )
1095 struct get_console_info_request *req = get_req_buffer();
1096 req->handle = hcon;
1097 if (server_call( REQ_GET_CONSOLE_INFO )) return FALSE;
1098 if (cinfo)
1100 cinfo->dwSize = req->cursor_size;
1101 cinfo->bVisible = req->cursor_visible;
1103 return TRUE;
1107 /******************************************************************************
1108 * SetConsoleCursorInfo32 [KERNEL32.626] Sets size and visibility of cursor
1110 * RETURNS
1111 * Success: TRUE
1112 * Failure: FALSE
1114 BOOL WINAPI SetConsoleCursorInfo(
1115 HANDLE hcon, /* [in] Handle to console screen buffer */
1116 LPCONSOLE_CURSOR_INFO cinfo) /* [in] Address of cursor information */
1118 struct set_console_info_request *req = get_req_buffer();
1119 char buf[8];
1120 DWORD xlen;
1122 CONSOLE_make_complex(hcon);
1123 sprintf(buf,"\033[?25%c",cinfo->bVisible?'h':'l');
1124 WriteFile(hcon,buf,strlen(buf),&xlen,NULL);
1126 req->handle = hcon;
1127 req->cursor_size = cinfo->dwSize;
1128 req->cursor_visible = cinfo->bVisible;
1129 req->mask = SET_CONSOLE_INFO_CURSOR;
1130 return !server_call( REQ_SET_CONSOLE_INFO );
1134 /******************************************************************************
1135 * SetConsoleWindowInfo [KERNEL32.634] Sets size and position of console
1137 * RETURNS
1138 * Success: TRUE
1139 * Failure: FALSE
1141 BOOL WINAPI SetConsoleWindowInfo(
1142 HANDLE hcon, /* [in] Handle to console screen buffer */
1143 BOOL bAbsolute, /* [in] Coordinate type flag */
1144 LPSMALL_RECT window) /* [in] Address of new window rectangle */
1146 FIXME("(%x,%d,%p): stub\n", hcon, bAbsolute, window);
1147 return TRUE;
1151 /******************************************************************************
1152 * SetConsoleTextAttribute32 [KERNEL32.631] Sets colors for text
1154 * Sets the foreground and background color attributes of characters
1155 * written to the screen buffer.
1157 * RETURNS
1158 * Success: TRUE
1159 * Failure: FALSE
1161 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput,WORD wAttr)
1163 const int colormap[8] = {
1164 0,4,2,6,
1165 1,5,3,7,
1167 DWORD xlen;
1168 char buffer[20];
1170 TRACE("(%d,%d)\n",hConsoleOutput,wAttr);
1171 sprintf(buffer,"%c[0;%s3%d;4%dm",
1173 (wAttr & FOREGROUND_INTENSITY)?"1;":"",
1174 colormap[wAttr&7],
1175 colormap[(wAttr&0x70)>>4]
1177 WriteFile(hConsoleOutput,buffer,strlen(buffer),&xlen,NULL);
1178 return TRUE;
1182 /******************************************************************************
1183 * SetConsoleScreenBufferSize [KERNEL32.630] Changes size of console
1185 * PARAMS
1186 * hConsoleOutput [I] Handle to console screen buffer
1187 * dwSize [I] New size in character rows and cols
1189 * RETURNS
1190 * Success: TRUE
1191 * Failure: FALSE
1193 BOOL WINAPI SetConsoleScreenBufferSize( HANDLE hConsoleOutput,
1194 COORD dwSize )
1196 FIXME("(%d,%dx%d): stub\n",hConsoleOutput,dwSize.x,dwSize.y);
1197 return TRUE;
1201 /******************************************************************************
1202 * FillConsoleOutputCharacterA [KERNEL32.242]
1204 * PARAMS
1205 * hConsoleOutput [I] Handle to screen buffer
1206 * cCharacter [I] Character to write
1207 * nLength [I] Number of cells to write to
1208 * dwCoord [I] Coords of first cell
1209 * lpNumCharsWritten [O] Pointer to number of cells written
1211 * RETURNS
1212 * Success: TRUE
1213 * Failure: FALSE
1215 BOOL WINAPI FillConsoleOutputCharacterA(
1216 HANDLE hConsoleOutput,
1217 BYTE cCharacter,
1218 DWORD nLength,
1219 COORD dwCoord,
1220 LPDWORD lpNumCharsWritten)
1222 long count;
1223 DWORD xlen;
1225 SetConsoleCursorPosition(hConsoleOutput,dwCoord);
1226 for(count=0;count<nLength;count++)
1227 WriteFile(hConsoleOutput,&cCharacter,1,&xlen,NULL);
1228 *lpNumCharsWritten = nLength;
1229 return TRUE;
1233 /******************************************************************************
1234 * FillConsoleOutputCharacterW [KERNEL32.243] Writes characters to console
1236 * PARAMS
1237 * hConsoleOutput [I] Handle to screen buffer
1238 * cCharacter [I] Character to write
1239 * nLength [I] Number of cells to write to
1240 * dwCoord [I] Coords of first cell
1241 * lpNumCharsWritten [O] Pointer to number of cells written
1243 * RETURNS
1244 * Success: TRUE
1245 * Failure: FALSE
1247 BOOL WINAPI FillConsoleOutputCharacterW(HANDLE hConsoleOutput,
1248 WCHAR cCharacter,
1249 DWORD nLength,
1250 COORD dwCoord,
1251 LPDWORD lpNumCharsWritten)
1253 long count;
1254 DWORD xlen;
1256 SetConsoleCursorPosition(hConsoleOutput,dwCoord);
1257 /* FIXME: not quite correct ... but the lower part of UNICODE char comes
1258 * first
1260 for(count=0;count<nLength;count++)
1261 WriteFile(hConsoleOutput,&cCharacter,1,&xlen,NULL);
1262 *lpNumCharsWritten = nLength;
1263 return TRUE;
1267 /******************************************************************************
1268 * FillConsoleOutputAttribute [KERNEL32.241] Sets attributes for console
1270 * PARAMS
1271 * hConsoleOutput [I] Handle to screen buffer
1272 * wAttribute [I] Color attribute to write
1273 * nLength [I] Number of cells to write to
1274 * dwCoord [I] Coords of first cell
1275 * lpNumAttrsWritten [O] Pointer to number of cells written
1277 * RETURNS
1278 * Success: TRUE
1279 * Failure: FALSE
1281 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput,
1282 WORD wAttribute, DWORD nLength, COORD dwCoord,
1283 LPDWORD lpNumAttrsWritten)
1285 FIXME("(%d,%d,%ld,%dx%d,%p): stub\n", hConsoleOutput,
1286 wAttribute,nLength,dwCoord.x,dwCoord.y,lpNumAttrsWritten);
1287 *lpNumAttrsWritten = nLength;
1288 return TRUE;
1291 /******************************************************************************
1292 * ReadConsoleOutputCharacter32A [KERNEL32.573]
1294 * BUGS
1295 * Unimplemented
1297 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput,
1298 LPSTR lpstr, DWORD dword, COORD coord, LPDWORD lpdword)
1300 FIXME("(%d,%p,%ld,%dx%d,%p): stub\n", hConsoleOutput,lpstr,
1301 dword,coord.x,coord.y,lpdword);
1302 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1303 return FALSE;
1307 /******************************************************************************
1308 * ScrollConsoleScreenBuffer [KERNEL32.612]
1310 * BUGS
1311 * Unimplemented
1313 BOOL WINAPI ScrollConsoleScreenBuffer( HANDLE hConsoleOutput,
1314 LPSMALL_RECT lpScrollRect, LPSMALL_RECT lpClipRect,
1315 COORD dwDestOrigin, LPCHAR_INFO lpFill)
1317 FIXME("(%d,%p,%p,%dx%d,%p): stub\n", hConsoleOutput,lpScrollRect,
1318 lpClipRect,dwDestOrigin.x,dwDestOrigin.y,lpFill);
1319 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1320 return FALSE;