Better implementation of GetShortPathNameA/W.
[wine/multimedia.git] / win32 / console.c
blob414a40ac036dc77b5e9245e9193fb069dc082a9c
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 <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>
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 "debug.h"
48 #include "server/request.h"
49 #include "server.h"
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_GetInfo
60 static BOOL CONSOLE_GetInfo( HANDLE handle, struct get_console_info_reply *reply )
62 struct get_console_info_request req;
64 req.handle = handle;
65 CLIENT_SendRequest( REQ_GET_CONSOLE_INFO, -1, 1, &req, sizeof(req) );
66 return !CLIENT_WaitSimpleReply( reply, sizeof(*reply), NULL );
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') {
114 ir.Event.KeyEvent.uChar.AsciiChar = '\r';
115 ir.Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
116 ir.Event.KeyEvent.wVirtualScanCode = 0x1c;
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(console,"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;
218 if (scancode) {
219 ir.Event.KeyEvent.wVirtualScanCode = scancode;
220 ir.Event.KeyEvent.wVirtualKeyCode = MapVirtualKey16(scancode,1);
221 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
222 ir.Event.KeyEvent.bKeyDown = 0;
223 assert(WriteConsoleInputA( hConsoleInput, &ir, 1, &junk ));
224 j=k;
225 continue;
231 /****************************************************************************
232 * CONSOLE_get_input (internal)
234 * Reads (nonblocking) as much input events as possible and stores them
235 * in an internal queue.
237 static void
238 CONSOLE_get_input( HANDLE handle, BOOL blockwait )
240 char *buf = HeapAlloc(GetProcessHeap(),0,1);
241 int len = 0;
243 while (1)
245 DWORD res;
246 char inchar;
247 if (WaitForSingleObject( handle, 0 )) break;
248 if (!ReadFile( handle, &inchar, 1, &res, NULL )) break;
249 if (!res) /* res 0 but readable means EOF? Hmm. */
250 break;
251 buf = HeapReAlloc(GetProcessHeap(),0,buf,len+1);
252 buf[len++]=inchar;
254 CONSOLE_string_to_IR(handle,buf,len);
255 HeapFree(GetProcessHeap(),0,buf);
258 /******************************************************************************
259 * SetConsoleCtrlHandler [KERNEL32.459] Adds function to calling process list
261 * PARAMS
262 * func [I] Address of handler function
263 * add [I] Handler to add or remove
265 * RETURNS
266 * Success: TRUE
267 * Failure: FALSE
269 * CHANGED
270 * James Sutherland (JamesSutherland@gmx.de)
271 * Added global variables console_ignore_ctrl_c and handlers[]
272 * Does not yet do any error checking, or set LastError if failed.
273 * This doesn't yet matter, since these handlers are not yet called...!
275 static unsigned int console_ignore_ctrl_c = 0;
276 static HANDLER_ROUTINE *handlers[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
277 BOOL WINAPI SetConsoleCtrlHandler( HANDLER_ROUTINE *func, BOOL add )
279 unsigned int alloc_loop = sizeof(handlers)/sizeof(HANDLER_ROUTINE *);
280 unsigned int done = 0;
281 FIXME(console, "(%p,%i) - no error checking or testing yet\n", func, add);
282 if (!func)
284 console_ignore_ctrl_c = add;
285 return TRUE;
287 if (add)
289 for (;alloc_loop--;)
290 if (!handlers[alloc_loop] && !done)
292 handlers[alloc_loop] = func;
293 done++;
295 if (!done)
296 FIXME(console, "Out of space on CtrlHandler table\n");
297 return(done);
299 else
301 for (;alloc_loop--;)
302 if (handlers[alloc_loop] == func && !done)
304 handlers[alloc_loop] = 0;
305 done++;
307 if (!done)
308 WARN(console, "Attempt to remove non-installed CtrlHandler %p\n",
309 func);
310 return (done);
312 return (done);
316 /******************************************************************************
317 * GenerateConsoleCtrlEvent [KERNEL32.275] Simulate a CTRL-C or CTRL-BREAK
319 * PARAMS
320 * dwCtrlEvent [I] Type of event
321 * dwProcessGroupID [I] Process group ID to send event to
323 * NOTES
324 * Doesn't yet work...!
326 * RETURNS
327 * Success: True
328 * Failure: False (and *should* [but doesn't] set LastError)
330 BOOL WINAPI GenerateConsoleCtrlEvent( DWORD dwCtrlEvent,
331 DWORD dwProcessGroupID )
333 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
335 ERR( console, "invalid event %d for PGID %ld\n",
336 (unsigned short)dwCtrlEvent, dwProcessGroupID );
337 return FALSE;
339 if (dwProcessGroupID == GetCurrentProcessId() )
341 FIXME( console, "Attempt to send event %d to self - stub\n",
342 (unsigned short)dwCtrlEvent );
343 return FALSE;
345 FIXME( console,"event %d to external PGID %ld - not implemented yet\n",
346 (unsigned short)dwCtrlEvent, dwProcessGroupID );
347 return FALSE;
351 /******************************************************************************
352 * CreateConsoleScreenBuffer [KERNEL32.151] Creates a console screen buffer
354 * PARAMS
355 * dwDesiredAccess [I] Access flag
356 * dwShareMode [I] Buffer share mode
357 * sa [I] Security attributes
358 * dwFlags [I] Type of buffer to create
359 * lpScreenBufferData [I] Reserved
361 * NOTES
362 * Should call SetLastError
364 * RETURNS
365 * Success: Handle to new console screen buffer
366 * Failure: INVALID_HANDLE_VALUE
368 HANDLE WINAPI CreateConsoleScreenBuffer( DWORD dwDesiredAccess,
369 DWORD dwShareMode, LPSECURITY_ATTRIBUTES sa,
370 DWORD dwFlags, LPVOID lpScreenBufferData )
372 FIXME(console, "(%ld,%ld,%p,%ld,%p): stub\n",dwDesiredAccess,
373 dwShareMode, sa, dwFlags, lpScreenBufferData);
374 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
375 return INVALID_HANDLE_VALUE;
379 /***********************************************************************
380 * GetConsoleScreenBufferInfo (KERNEL32.190)
382 BOOL WINAPI GetConsoleScreenBufferInfo( HANDLE hConsoleOutput,
383 LPCONSOLE_SCREEN_BUFFER_INFO csbi )
385 csbi->dwSize.x = 80;
386 csbi->dwSize.y = 24;
387 csbi->dwCursorPosition.x = 0;
388 csbi->dwCursorPosition.y = 0;
389 csbi->wAttributes = 0;
390 csbi->srWindow.Left = 0;
391 csbi->srWindow.Right = 79;
392 csbi->srWindow.Top = 0;
393 csbi->srWindow.Bottom = 23;
394 csbi->dwMaximumWindowSize.x = 80;
395 csbi->dwMaximumWindowSize.y = 24;
396 return TRUE;
400 /******************************************************************************
401 * SetConsoleActiveScreenBuffer [KERNEL32.623] Sets buffer to current console
403 * RETURNS
404 * Success: TRUE
405 * Failure: FALSE
407 BOOL WINAPI SetConsoleActiveScreenBuffer(
408 HANDLE hConsoleOutput) /* [in] Handle to console screen buffer */
410 FIXME(console, "(%x): stub\n", hConsoleOutput);
411 return FALSE;
415 /***********************************************************************
416 * GetLargestConsoleWindowSize (KERNEL32.226)
418 DWORD WINAPI GetLargestConsoleWindowSize( HANDLE hConsoleOutput )
420 return (DWORD)MAKELONG(80,24);
423 /***********************************************************************
424 * FreeConsole (KERNEL32.267)
426 BOOL WINAPI FreeConsole(VOID)
428 CLIENT_SendRequest( REQ_FREE_CONSOLE, -1, 0 );
429 return !CLIENT_WaitReply( NULL, NULL, 0 );
433 /*************************************************************************
434 * CONSOLE_OpenHandle
436 * Open a handle to the current process console.
438 HANDLE CONSOLE_OpenHandle( BOOL output, DWORD access, LPSECURITY_ATTRIBUTES sa )
440 struct open_console_request req;
441 struct open_console_reply reply;
443 req.output = output;
444 req.access = access;
445 req.inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
446 CLIENT_SendRequest( REQ_OPEN_CONSOLE, -1, 1, &req, sizeof(req) );
447 SetLastError(0);
448 CLIENT_WaitSimpleReply( &reply, sizeof(reply), NULL );
449 return reply.handle;
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;
470 struct get_console_info_reply info;
471 struct termios term;
472 char buf[256];
473 char c = '\0';
474 int status = 0;
475 int i,xpid,master,slave;
476 DWORD xlen;
478 if (!CONSOLE_GetInfo( handle, &info )) return FALSE;
479 if (info.pid) return TRUE; /* already complex */
481 MSG("Console: Making console complex (creating an xterm)...\n");
483 if (tcgetattr(0, &term) < 0) {
484 /* ignore failure, or we can't run from a script */
486 term.c_lflag = ~(ECHO|ICANON);
488 if (wine_openpty(&master, &slave, NULL, &term, NULL) < 0)
489 return FALSE;
491 if ((xpid=fork()) == 0) {
492 tcsetattr(slave, TCSADRAIN, &term);
493 sprintf(buf, "-Sxx%d", master);
494 /* "-fn vga" for VGA font. Harmless if vga is not present:
495 * xterm: unable to open font "vga", trying "fixed"....
497 execlp("xterm", "xterm", buf, "-fn","vga",NULL);
498 ERR(console, "error creating AllocConsole xterm\n");
499 exit(1);
502 req.handle = handle;
503 req.pid = xpid;
504 CLIENT_SendRequest( REQ_SET_CONSOLE_FD, dup(slave), 1, &req, sizeof(req) );
505 CLIENT_WaitReply( NULL, NULL, 0 );
507 /* most xterms like to print their window ID when used with -S;
508 * read it and continue before the user has a chance...
510 for (i=0; c!='\n'; (status=read(slave, &c, 1)), i++) {
511 if (status == -1 && c == '\0') {
512 /* wait for xterm to be created */
513 usleep(100);
515 if (i > 10000) {
516 ERR(console, "can't read xterm WID\n");
517 kill(xpid, SIGKILL);
518 return FALSE;
521 /* enable mouseclicks */
522 sprintf(buf,"%c[?1001s%c[?1000h",27,27);
523 WriteFile(handle,buf,strlen(buf),&xlen,NULL);
525 if (GetConsoleTitleA( buf, sizeof(buf) ))
527 WriteFile(handle,"\033]2;",4,&xlen,NULL);
528 WriteFile(handle,buf,strlen(buf),&xlen,NULL);
529 WriteFile(handle,"\a",1,&xlen,NULL);
531 return TRUE;
536 /***********************************************************************
537 * AllocConsole (KERNEL32.103)
539 * creates an xterm with a pty to our program
541 BOOL WINAPI AllocConsole(VOID)
543 struct open_console_request req;
544 struct open_console_reply reply;
545 HANDLE hIn, hOut, hErr;
547 CLIENT_SendRequest( REQ_ALLOC_CONSOLE, -1, 0 );
548 if (CLIENT_WaitReply( NULL, NULL, 0 ) != ERROR_SUCCESS) return FALSE;
550 req.output = 0;
551 req.access = GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE;
552 req.inherit = FALSE;
553 CLIENT_SendRequest( REQ_OPEN_CONSOLE, -1, 1, &req, sizeof(req) );
554 if (CLIENT_WaitSimpleReply( &reply, sizeof(reply), NULL ) != ERROR_SUCCESS)
556 /* FIXME: free console */
557 return FALSE;
559 hIn = reply.handle;
561 req.output = 1;
562 CLIENT_SendRequest( REQ_OPEN_CONSOLE, -1, 1, &req, sizeof(req) );
563 if (CLIENT_WaitSimpleReply( &reply, sizeof(reply), NULL ) != ERROR_SUCCESS)
565 CloseHandle(hIn);
566 /* FIXME: free console */
567 return FALSE;
569 hOut = reply.handle;
571 if (!DuplicateHandle( GetCurrentProcess(), hOut,
572 GetCurrentProcess(), &hErr,
573 0, TRUE, DUPLICATE_SAME_ACCESS ))
575 CloseHandle(hIn);
576 CloseHandle(hOut);
577 return FALSE;
580 /* NT resets the STD_*_HANDLEs on console alloc */
581 SetStdHandle(STD_INPUT_HANDLE, hIn);
582 SetStdHandle(STD_OUTPUT_HANDLE, hOut);
583 SetStdHandle(STD_ERROR_HANDLE, hErr);
585 SetLastError(ERROR_SUCCESS);
586 SetConsoleTitleA("Wine Console");
587 return TRUE;
591 /******************************************************************************
592 * GetConsoleCP [KERNEL32.295] Returns the OEM code page for the console
594 * RETURNS
595 * Code page code
597 UINT WINAPI GetConsoleCP(VOID)
599 return GetACP();
603 /***********************************************************************
604 * GetConsoleOutputCP (KERNEL32.189)
606 UINT WINAPI GetConsoleOutputCP(VOID)
608 return GetConsoleCP();
611 /***********************************************************************
612 * GetConsoleMode (KERNEL32.188)
614 BOOL WINAPI GetConsoleMode(HANDLE hcon,LPDWORD mode)
616 struct get_console_mode_request req;
617 struct get_console_mode_reply reply;
619 req.handle = hcon;
620 CLIENT_SendRequest( REQ_GET_CONSOLE_MODE, -1, 1, &req, sizeof(req));
621 if (CLIENT_WaitSimpleReply( &reply, sizeof(reply), NULL )) return FALSE;
622 *mode = reply.mode;
623 return TRUE;
627 /******************************************************************************
628 * SetConsoleMode [KERNEL32.628] Sets input mode of console's input buffer
630 * PARAMS
631 * hcon [I] Handle to console input or screen buffer
632 * mode [I] Input or output mode to set
634 * RETURNS
635 * Success: TRUE
636 * Failure: FALSE
638 BOOL WINAPI SetConsoleMode( HANDLE hcon, DWORD mode )
640 struct set_console_mode_request req;
642 req.handle = hcon;
643 req.mode = mode;
644 CLIENT_SendRequest( REQ_SET_CONSOLE_MODE, -1, 1, &req, sizeof(req));
645 return !CLIENT_WaitReply( NULL, NULL, 0 );
649 /***********************************************************************
650 * GetConsoleTitleA (KERNEL32.191)
652 DWORD WINAPI GetConsoleTitleA(LPSTR title,DWORD size)
654 struct get_console_info_request req;
655 struct get_console_info_reply reply;
656 int len;
657 DWORD ret = 0;
658 HANDLE hcon;
660 if ((hcon = CreateFileA( "CONOUT$", GENERIC_READ, 0, NULL,
661 OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
662 return 0;
663 req.handle = hcon;
664 CLIENT_SendRequest( REQ_GET_CONSOLE_INFO, -1, 1, &req, sizeof(req) );
665 if (!CLIENT_WaitReply( &len, NULL, 2, &reply, sizeof(reply), title, size ))
667 if (len > sizeof(reply)+size) title[size-1] = 0;
668 ret = strlen(title);
670 CloseHandle( hcon );
671 return ret;
675 /******************************************************************************
676 * GetConsoleTitle32W [KERNEL32.192] Retrieves title string for console
678 * PARAMS
679 * title [O] Address of buffer for title
680 * size [I] Size of buffer
682 * RETURNS
683 * Success: Length of string copied
684 * Failure: 0
686 DWORD WINAPI GetConsoleTitleW( LPWSTR title, DWORD size )
688 char *tmp;
689 DWORD ret;
691 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, size ))) return 0;
692 ret = GetConsoleTitleA( tmp, size );
693 lstrcpyAtoW( title, tmp );
694 HeapFree( GetProcessHeap(), 0, tmp );
695 return ret;
699 /***********************************************************************
700 * WriteConsoleA (KERNEL32.729)
702 BOOL WINAPI WriteConsoleA( HANDLE hConsoleOutput,
703 LPCVOID lpBuffer,
704 DWORD nNumberOfCharsToWrite,
705 LPDWORD lpNumberOfCharsWritten,
706 LPVOID lpReserved )
708 /* FIXME: should I check if this is a console handle? */
709 return WriteFile(hConsoleOutput, lpBuffer, nNumberOfCharsToWrite,
710 lpNumberOfCharsWritten, NULL);
714 #define CADD(c) \
715 if (bufused==curbufsize-1) \
716 buffer = HeapReAlloc(GetProcessHeap(),0,buffer,(curbufsize+=100));\
717 buffer[bufused++]=c;
718 #define SADD(s) { char *x=s;while (*x) {CADD(*x);x++;}}
720 /***********************************************************************
721 * WriteConsoleOutputA (KERNEL32.732)
723 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput,
724 LPCHAR_INFO lpBuffer,
725 COORD dwBufferSize,
726 COORD dwBufferCoord,
727 LPSMALL_RECT lpWriteRegion)
729 int i,j,off=0,lastattr=-1;
730 char sbuf[20],*buffer=NULL;
731 int bufused=0,curbufsize = 100;
732 DWORD res;
733 const int colormap[8] = {
734 0,4,2,6,
735 1,5,3,7,
737 CONSOLE_make_complex(hConsoleOutput);
738 buffer = HeapAlloc(GetProcessHeap(),0,100);;
739 curbufsize = 100;
741 TRACE(console,"wr: top = %d, bottom=%d, left=%d,right=%d\n",
742 lpWriteRegion->Top,
743 lpWriteRegion->Bottom,
744 lpWriteRegion->Left,
745 lpWriteRegion->Right
748 for (i=lpWriteRegion->Top;i<=lpWriteRegion->Bottom;i++) {
749 sprintf(sbuf,"%c[%d;%dH",27,i+1,lpWriteRegion->Left+1);
750 SADD(sbuf);
751 for (j=lpWriteRegion->Left;j<=lpWriteRegion->Right;j++) {
752 if (lastattr!=lpBuffer[off].Attributes) {
753 lastattr = lpBuffer[off].Attributes;
754 sprintf(sbuf,"%c[0;%s3%d;4%dm",
756 (lastattr & FOREGROUND_INTENSITY)?"1;":"",
757 colormap[lastattr&7],
758 colormap[(lastattr&0x70)>>4]
760 /* FIXME: BACKGROUND_INTENSITY */
761 SADD(sbuf);
763 CADD(lpBuffer[off].Char.AsciiChar);
764 off++;
767 sprintf(sbuf,"%c[0m",27);SADD(sbuf);
768 WriteFile(hConsoleOutput,buffer,bufused,&res,NULL);
769 HeapFree(GetProcessHeap(),0,buffer);
770 return TRUE;
773 /***********************************************************************
774 * WriteConsoleW (KERNEL32.577)
776 BOOL WINAPI WriteConsoleW( HANDLE hConsoleOutput,
777 LPCVOID lpBuffer,
778 DWORD nNumberOfCharsToWrite,
779 LPDWORD lpNumberOfCharsWritten,
780 LPVOID lpReserved )
782 BOOL ret;
783 LPSTR xstring=HeapAlloc( GetProcessHeap(), 0, nNumberOfCharsToWrite );
785 lstrcpynWtoA( xstring, lpBuffer,nNumberOfCharsToWrite);
787 /* FIXME: should I check if this is a console handle? */
788 ret= WriteFile(hConsoleOutput, xstring, nNumberOfCharsToWrite,
789 lpNumberOfCharsWritten, NULL);
790 HeapFree( GetProcessHeap(), 0, xstring );
791 return ret;
795 /***********************************************************************
796 * ReadConsoleA (KERNEL32.419)
798 BOOL WINAPI ReadConsoleA( HANDLE hConsoleInput,
799 LPVOID lpBuffer,
800 DWORD nNumberOfCharsToRead,
801 LPDWORD lpNumberOfCharsRead,
802 LPVOID lpReserved )
804 int charsread = 0;
805 LPSTR xbuf = (LPSTR)lpBuffer;
806 struct read_console_input_request req;
807 INPUT_RECORD ir;
809 TRACE(console,"(%d,%p,%ld,%p,%p)\n",
810 hConsoleInput,lpBuffer,nNumberOfCharsToRead,
811 lpNumberOfCharsRead,lpReserved
814 CONSOLE_get_input(hConsoleInput,FALSE);
816 req.handle = hConsoleInput;
817 req.count = 1;
818 req.flush = 1;
820 /* FIXME: should we read at least 1 char? The SDK does not say */
821 while (charsread<nNumberOfCharsToRead)
823 int len;
825 CLIENT_SendRequest( REQ_READ_CONSOLE_INPUT, -1, 1, &req, sizeof(req) );
826 if (CLIENT_WaitReply( &len, NULL, 1, &ir, sizeof(ir) ))
827 return FALSE;
828 assert( !(len % sizeof(ir)) );
829 if (!len) break;
830 if (!ir.Event.KeyEvent.bKeyDown)
831 continue;
832 if (ir.EventType != KEY_EVENT)
833 continue;
834 *xbuf++ = ir.Event.KeyEvent.uChar.AsciiChar;
835 charsread++;
837 if (lpNumberOfCharsRead)
838 *lpNumberOfCharsRead = charsread;
839 return TRUE;
842 /***********************************************************************
843 * ReadConsoleW (KERNEL32.427)
845 BOOL WINAPI ReadConsoleW( HANDLE hConsoleInput,
846 LPVOID lpBuffer,
847 DWORD nNumberOfCharsToRead,
848 LPDWORD lpNumberOfCharsRead,
849 LPVOID lpReserved )
851 BOOL ret;
852 LPSTR buf = (LPSTR)HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead);
854 ret = ReadConsoleA(
855 hConsoleInput,
856 buf,
857 nNumberOfCharsToRead,
858 lpNumberOfCharsRead,
859 lpReserved
861 if (ret)
862 lstrcpynAtoW(lpBuffer,buf,nNumberOfCharsToRead);
863 HeapFree( GetProcessHeap(), 0, buf );
864 return ret;
868 /******************************************************************************
869 * ReadConsoleInput32A [KERNEL32.569] Reads data from a console
871 * PARAMS
872 * hConsoleInput [I] Handle to console input buffer
873 * lpBuffer [O] Address of buffer for read data
874 * nLength [I] Number of records to read
875 * lpNumberOfEventsRead [O] Address of number of records read
877 * RETURNS
878 * Success: TRUE
879 * Failure: FALSE
881 BOOL WINAPI ReadConsoleInputA(HANDLE hConsoleInput,
882 LPINPUT_RECORD lpBuffer,
883 DWORD nLength, LPDWORD lpNumberOfEventsRead)
885 struct read_console_input_request req;
886 int len;
888 req.handle = hConsoleInput;
889 req.count = nLength;
890 req.flush = 1;
892 /* loop until we get at least one event */
893 for (;;)
895 CLIENT_SendRequest( REQ_READ_CONSOLE_INPUT, -1, 1, &req, sizeof(req) );
896 if (CLIENT_WaitReply( &len, NULL, 1, lpBuffer, nLength * sizeof(*lpBuffer) ))
897 return FALSE;
898 assert( !(len % sizeof(INPUT_RECORD)) );
899 if (len) break;
900 CONSOLE_get_input(hConsoleInput,TRUE);
901 /*WaitForSingleObject( hConsoleInput, INFINITE32 );*/
903 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = len / sizeof(INPUT_RECORD);
904 return TRUE;
908 /***********************************************************************
909 * ReadConsoleInput32W (KERNEL32.570)
911 BOOL WINAPI ReadConsoleInputW( HANDLE handle, LPINPUT_RECORD buffer,
912 DWORD count, LPDWORD read )
914 /* FIXME: Fix this if we get UNICODE input. */
915 return ReadConsoleInputA( handle, buffer, count, read );
919 /***********************************************************************
920 * FlushConsoleInputBuffer (KERNEL32.132)
922 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
924 struct read_console_input_request req;
925 int len;
927 req.handle = handle;
928 req.count = -1; /* get all records */
929 req.flush = 1;
930 CLIENT_SendRequest( REQ_READ_CONSOLE_INPUT, -1, 1, &req, sizeof(req) );
931 return !CLIENT_WaitReply( &len, NULL, 0 );
935 /***********************************************************************
936 * PeekConsoleInputA (KERNEL32.550)
938 * Gets 'count' first events (or less) from input queue.
940 * Does not need a complex console.
942 BOOL WINAPI PeekConsoleInputA( HANDLE handle, LPINPUT_RECORD buffer,
943 DWORD count, LPDWORD read )
945 struct read_console_input_request req;
946 int len;
948 CONSOLE_get_input(handle,FALSE);
949 req.handle = handle;
950 req.count = count;
951 req.flush = 0;
953 CLIENT_SendRequest( REQ_READ_CONSOLE_INPUT, -1, 1, &req, sizeof(req) );
954 if (CLIENT_WaitReply( &len, NULL, 1, buffer, count * sizeof(*buffer) ))
955 return FALSE;
956 assert( !(len % sizeof(INPUT_RECORD)) );
957 if (read) *read = len / sizeof(INPUT_RECORD);
958 return TRUE;
962 /***********************************************************************
963 * PeekConsoleInputW (KERNEL32.551)
965 BOOL WINAPI PeekConsoleInputW(HANDLE hConsoleInput,
966 LPINPUT_RECORD pirBuffer,
967 DWORD cInRecords,
968 LPDWORD lpcRead)
970 /* FIXME: Hmm. Fix this if we get UNICODE input. */
971 return PeekConsoleInputA(hConsoleInput,pirBuffer,cInRecords,lpcRead);
975 /******************************************************************************
976 * WriteConsoleInput32A [KERNEL32.730] Write data to a console input buffer
979 BOOL WINAPI WriteConsoleInputA( HANDLE handle, INPUT_RECORD *buffer,
980 DWORD count, LPDWORD written )
982 struct write_console_input_request req;
983 struct write_console_input_reply reply;
985 req.handle = handle;
986 req.count = count;
987 CLIENT_SendRequest( REQ_WRITE_CONSOLE_INPUT, -1, 2, &req, sizeof(req),
988 buffer, count * sizeof(*buffer) );
989 if (CLIENT_WaitSimpleReply( &reply, sizeof(reply), NULL )) return FALSE;
990 if (written) *written = reply.written;
991 return TRUE;
995 /***********************************************************************
996 * SetConsoleTitle32A (KERNEL32.476)
998 * Sets the console title.
1000 * We do not necessarily need to create a complex console for that,
1001 * but should remember the title and set it on creation of the latter.
1002 * (not fixed at this time).
1004 BOOL WINAPI SetConsoleTitleA(LPCSTR title)
1006 struct set_console_info_request req;
1007 struct get_console_info_reply info;
1008 HANDLE hcon;
1009 DWORD written;
1011 if ((hcon = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, NULL,
1012 OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
1013 return FALSE;
1014 req.handle = hcon;
1015 req.mask = SET_CONSOLE_INFO_TITLE;
1016 CLIENT_SendRequest( REQ_SET_CONSOLE_INFO, -1, 2, &req, sizeof(req),
1017 title, strlen(title)+1 );
1018 if (CLIENT_WaitReply( NULL, NULL, 0 )) goto error;
1019 if (CONSOLE_GetInfo( hcon, &info ) && info.pid)
1021 /* only set title for complex console (own xterm) */
1022 WriteFile( hcon, "\033]2;", 4, &written, NULL );
1023 WriteFile( hcon, title, strlen(title), &written, NULL );
1024 WriteFile( hcon, "\a", 1, &written, NULL );
1026 CloseHandle( hcon );
1027 return TRUE;
1028 error:
1029 CloseHandle( hcon );
1030 return FALSE;
1034 /******************************************************************************
1035 * SetConsoleTitle32W [KERNEL32.477] Sets title bar string for console
1037 * PARAMS
1038 * title [I] Address of new title
1040 * NOTES
1041 * This should not be calling the A version
1043 * RETURNS
1044 * Success: TRUE
1045 * Failure: FALSE
1047 BOOL WINAPI SetConsoleTitleW( LPCWSTR title )
1049 BOOL ret;
1051 LPSTR titleA = HEAP_strdupWtoA( GetProcessHeap(), 0, title );
1052 ret = SetConsoleTitleA(titleA);
1053 HeapFree( GetProcessHeap(), 0, titleA );
1054 return ret;
1057 /******************************************************************************
1058 * SetConsoleCursorPosition [KERNEL32.627]
1059 * Sets the cursor position in console
1061 * PARAMS
1062 * hConsoleOutput [I] Handle of console screen buffer
1063 * dwCursorPosition [I] New cursor position coordinates
1065 * RETURNS STD
1067 BOOL WINAPI SetConsoleCursorPosition( HANDLE hcon, COORD pos )
1069 char xbuf[20];
1070 DWORD xlen;
1072 /* make console complex only if we change lines, not just in the line */
1073 if (pos.y)
1074 CONSOLE_make_complex(hcon);
1076 TRACE(console, "%d (%dx%d)\n", hcon, pos.x , pos.y );
1077 /* x are columns, y rows */
1078 if (pos.y)
1079 /* full screen cursor absolute positioning */
1080 sprintf(xbuf,"%c[%d;%dH", 0x1B, pos.y+1, pos.x+1);
1081 else
1082 /* relative cursor positioning in line (\r to go to 0) */
1083 sprintf(xbuf,"\r%c[%dC", 0x1B, pos.x);
1084 /* FIXME: store internal if we start using own console buffers */
1085 WriteFile(hcon,xbuf,strlen(xbuf),&xlen,NULL);
1086 return TRUE;
1089 /***********************************************************************
1090 * GetNumberOfConsoleInputEvents (KERNEL32.246)
1092 BOOL WINAPI GetNumberOfConsoleInputEvents(HANDLE hcon,LPDWORD nrofevents)
1094 CONSOLE_get_input(hcon,FALSE);
1095 *nrofevents = 1; /* UMM */
1096 return TRUE;
1099 /***********************************************************************
1100 * GetNumberOfConsoleMouseButtons (KERNEL32.358)
1102 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1104 FIXME(console,"(%p): stub\n", nrofbuttons);
1105 *nrofbuttons = 2;
1106 return TRUE;
1109 /******************************************************************************
1110 * GetConsoleCursorInfo32 [KERNEL32.296] Gets size and visibility of console
1112 * PARAMS
1113 * hcon [I] Handle to console screen buffer
1114 * cinfo [O] Address of cursor information
1116 * RETURNS
1117 * Success: TRUE
1118 * Failure: FALSE
1120 BOOL WINAPI GetConsoleCursorInfo( HANDLE hcon,
1121 LPCONSOLE_CURSOR_INFO cinfo )
1123 struct get_console_info_reply reply;
1125 if (!CONSOLE_GetInfo( hcon, &reply )) return FALSE;
1126 if (cinfo)
1128 cinfo->dwSize = reply.cursor_size;
1129 cinfo->bVisible = reply.cursor_visible;
1131 return TRUE;
1135 /******************************************************************************
1136 * SetConsoleCursorInfo32 [KERNEL32.626] Sets size and visibility of cursor
1138 * RETURNS
1139 * Success: TRUE
1140 * Failure: FALSE
1142 BOOL WINAPI SetConsoleCursorInfo(
1143 HANDLE hcon, /* [in] Handle to console screen buffer */
1144 LPCONSOLE_CURSOR_INFO cinfo) /* [in] Address of cursor information */
1146 struct set_console_info_request req;
1147 char buf[8];
1148 DWORD xlen;
1150 req.handle = hcon;
1151 CONSOLE_make_complex(hcon);
1152 sprintf(buf,"\033[?25%c",cinfo->bVisible?'h':'l');
1153 WriteFile(hcon,buf,strlen(buf),&xlen,NULL);
1155 req.cursor_size = cinfo->dwSize;
1156 req.cursor_visible = cinfo->bVisible;
1157 req.mask = SET_CONSOLE_INFO_CURSOR;
1158 CLIENT_SendRequest( REQ_SET_CONSOLE_INFO, -1, 1, &req, sizeof(req) );
1159 return !CLIENT_WaitReply( NULL, NULL, 0 );
1163 /******************************************************************************
1164 * SetConsoleWindowInfo [KERNEL32.634] Sets size and position of console
1166 * RETURNS
1167 * Success: TRUE
1168 * Failure: FALSE
1170 BOOL WINAPI SetConsoleWindowInfo(
1171 HANDLE hcon, /* [in] Handle to console screen buffer */
1172 BOOL bAbsolute, /* [in] Coordinate type flag */
1173 LPSMALL_RECT window) /* [in] Address of new window rectangle */
1175 FIXME(console, "(%x,%d,%p): stub\n", hcon, bAbsolute, window);
1176 return TRUE;
1180 /******************************************************************************
1181 * SetConsoleTextAttribute32 [KERNEL32.631] Sets colors for text
1183 * Sets the foreground and background color attributes of characters
1184 * written to the screen buffer.
1186 * RETURNS
1187 * Success: TRUE
1188 * Failure: FALSE
1190 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput,WORD wAttr)
1192 const int colormap[8] = {
1193 0,4,2,6,
1194 1,5,3,7,
1196 DWORD xlen;
1197 char buffer[20];
1199 TRACE(console,"(%d,%d)\n",hConsoleOutput,wAttr);
1200 sprintf(buffer,"%c[0;%s3%d;4%dm",
1202 (wAttr & FOREGROUND_INTENSITY)?"1;":"",
1203 colormap[wAttr&7],
1204 colormap[(wAttr&0x70)>>4]
1206 WriteFile(hConsoleOutput,buffer,strlen(buffer),&xlen,NULL);
1207 return TRUE;
1211 /******************************************************************************
1212 * SetConsoleScreenBufferSize [KERNEL32.630] Changes size of console
1214 * PARAMS
1215 * hConsoleOutput [I] Handle to console screen buffer
1216 * dwSize [I] New size in character rows and cols
1218 * RETURNS
1219 * Success: TRUE
1220 * Failure: FALSE
1222 BOOL WINAPI SetConsoleScreenBufferSize( HANDLE hConsoleOutput,
1223 COORD dwSize )
1225 FIXME(console, "(%d,%dx%d): stub\n",hConsoleOutput,dwSize.x,dwSize.y);
1226 return TRUE;
1230 /******************************************************************************
1231 * FillConsoleOutputCharacterA [KERNEL32.242]
1233 * PARAMS
1234 * hConsoleOutput [I] Handle to screen buffer
1235 * cCharacter [I] Character to write
1236 * nLength [I] Number of cells to write to
1237 * dwCoord [I] Coords of first cell
1238 * lpNumCharsWritten [O] Pointer to number of cells written
1240 * RETURNS
1241 * Success: TRUE
1242 * Failure: FALSE
1244 BOOL WINAPI FillConsoleOutputCharacterA(
1245 HANDLE hConsoleOutput,
1246 BYTE cCharacter,
1247 DWORD nLength,
1248 COORD dwCoord,
1249 LPDWORD lpNumCharsWritten)
1251 long count;
1252 DWORD xlen;
1254 SetConsoleCursorPosition(hConsoleOutput,dwCoord);
1255 for(count=0;count<nLength;count++)
1256 WriteFile(hConsoleOutput,&cCharacter,1,&xlen,NULL);
1257 *lpNumCharsWritten = nLength;
1258 return TRUE;
1262 /******************************************************************************
1263 * FillConsoleOutputCharacterW [KERNEL32.243] Writes characters to console
1265 * PARAMS
1266 * hConsoleOutput [I] Handle to screen buffer
1267 * cCharacter [I] Character to write
1268 * nLength [I] Number of cells to write to
1269 * dwCoord [I] Coords of first cell
1270 * lpNumCharsWritten [O] Pointer to number of cells written
1272 * RETURNS
1273 * Success: TRUE
1274 * Failure: FALSE
1276 BOOL WINAPI FillConsoleOutputCharacterW(HANDLE hConsoleOutput,
1277 WCHAR cCharacter,
1278 DWORD nLength,
1279 COORD dwCoord,
1280 LPDWORD lpNumCharsWritten)
1282 long count;
1283 DWORD xlen;
1285 SetConsoleCursorPosition(hConsoleOutput,dwCoord);
1286 /* FIXME: not quite correct ... but the lower part of UNICODE char comes
1287 * first
1289 for(count=0;count<nLength;count++)
1290 WriteFile(hConsoleOutput,&cCharacter,1,&xlen,NULL);
1291 *lpNumCharsWritten = nLength;
1292 return TRUE;
1296 /******************************************************************************
1297 * FillConsoleOutputAttribute [KERNEL32.241] Sets attributes for console
1299 * PARAMS
1300 * hConsoleOutput [I] Handle to screen buffer
1301 * wAttribute [I] Color attribute to write
1302 * nLength [I] Number of cells to write to
1303 * dwCoord [I] Coords of first cell
1304 * lpNumAttrsWritten [O] Pointer to number of cells written
1306 * RETURNS
1307 * Success: TRUE
1308 * Failure: FALSE
1310 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput,
1311 WORD wAttribute, DWORD nLength, COORD dwCoord,
1312 LPDWORD lpNumAttrsWritten)
1314 FIXME(console, "(%d,%d,%ld,%dx%d,%p): stub\n", hConsoleOutput,
1315 wAttribute,nLength,dwCoord.x,dwCoord.y,lpNumAttrsWritten);
1316 *lpNumAttrsWritten = nLength;
1317 return TRUE;
1320 /******************************************************************************
1321 * ReadConsoleOutputCharacter32A [KERNEL32.573]
1323 * BUGS
1324 * Unimplemented
1326 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput,
1327 LPSTR lpstr, DWORD dword, COORD coord, LPDWORD lpdword)
1329 FIXME(console, "(%d,%p,%ld,%dx%d,%p): stub\n", hConsoleOutput,lpstr,
1330 dword,coord.x,coord.y,lpdword);
1331 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1332 return FALSE;
1336 /******************************************************************************
1337 * ScrollConsoleScreenBuffer [KERNEL32.612]
1339 * BUGS
1340 * Unimplemented
1342 BOOL WINAPI ScrollConsoleScreenBuffer( HANDLE hConsoleOutput,
1343 LPSMALL_RECT lpScrollRect, LPSMALL_RECT lpClipRect,
1344 COORD dwDestOrigin, LPCHAR_INFO lpFill)
1346 FIXME(console, "(%d,%p,%p,%dx%d,%p): stub\n", hConsoleOutput,lpScrollRect,
1347 lpClipRect,dwDestOrigin.x,dwDestOrigin.y,lpFill);
1348 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1349 return FALSE;