Check, Radio & 3State buttons send WM_CTLCOLORSTATIC instead of
[wine/wine-kai.git] / win32 / console.c
blob8798ec4bf6022c3dc60cfd27f43493f4246d8082
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 * Copyright 2001 Eric Pouech
9 */
11 /* Reference applications:
12 * - IDA (interactive disassembler) full version 3.75. Works.
13 * - LYNX/W32. Works mostly, some keys crash it.
16 #include "config.h"
18 #include <stdio.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <assert.h>
23 #include "winbase.h"
24 #include "winnls.h"
25 #include "winerror.h"
26 #include "wincon.h"
27 #include "heap.h"
28 #include "wine/server.h"
29 #include "wine/exception.h"
30 #include "debugtools.h"
31 #include "options.h"
33 DEFAULT_DEBUG_CHANNEL(console);
35 /* editline.c */
36 extern WCHAR* CONSOLE_Readline(HANDLE, int);
38 static WCHAR* S_EditString /* = NULL */;
39 static unsigned S_EditStrPos /* = 0 */;
41 /***********************************************************************
42 * FreeConsole (KERNEL32.@)
44 BOOL WINAPI FreeConsole(VOID)
46 BOOL ret;
48 SERVER_START_REQ(free_console)
50 ret = !wine_server_call_err( req );
52 SERVER_END_REQ;
53 return ret;
56 /******************************************************************
57 * start_console_renderer
59 * helper for AllocConsole
60 * starts the renderer process
62 static BOOL start_console_renderer(void)
64 char buffer[256];
65 int ret;
66 STARTUPINFOA si;
67 PROCESS_INFORMATION pi;
68 HANDLE hEvent = 0;
69 LPSTR p, path = NULL;
70 OBJECT_ATTRIBUTES attr;
72 attr.Length = sizeof(attr);
73 attr.RootDirectory = 0;
74 attr.Attributes = OBJ_INHERIT;
75 attr.ObjectName = NULL;
76 attr.SecurityDescriptor = NULL;
77 attr.SecurityQualityOfService = NULL;
79 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
80 if (!hEvent) return FALSE;
82 memset(&si, 0, sizeof(si));
83 si.cb = sizeof(si);
85 /* FIXME: use dynamic allocation for most of the buffers below */
86 /* first try environment variable */
87 if ((p = getenv("WINECONSOLE")) != NULL)
89 ret = snprintf(buffer, sizeof(buffer), "%s -- --use-event=%d", p, hEvent);
90 if ((ret > -1) && (ret < sizeof(buffer)) &&
91 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
92 goto succeed;
93 ERR("Couldn't launch Wine console from WINECONSOLE env var... trying default access\n");
96 /* then the regular installation dir */
97 ret = snprintf(buffer, sizeof(buffer), "%s -- --use-event=%d", BINDIR "/wineconsole", hEvent);
98 if ((ret > -1) && (ret < sizeof(buffer)) &&
99 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
100 goto succeed;
102 /* then try the dir where we were started from */
103 if ((path = HeapAlloc(GetProcessHeap(), 0, strlen(full_argv0) + sizeof(buffer))))
105 int n;
107 if ((p = strrchr(strcpy( path, full_argv0 ), '/')))
109 p++;
110 sprintf(p, "wineconsole -- --use-event=%d", hEvent);
111 if (CreateProcessA(NULL, path, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
112 goto succeed;
113 sprintf(p, "programs/wineconsole/wineconsole -- --use-event=%d", hEvent);
114 if (CreateProcessA(NULL, path, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
115 goto succeed;
118 n = readlink(full_argv0, buffer, sizeof(buffer));
119 if (n != -1 && n < sizeof(buffer))
121 buffer[n] = 0;
122 if (buffer[0] == '/') /* absolute path ? */
123 strcpy(path, buffer);
124 else if ((p = strrchr(strcpy( path, full_argv0 ), '/')))
126 strcpy(p + 1, buffer);
128 else *path = 0;
130 if ((p = strrchr(path, '/')))
132 p++;
133 sprintf(p, "wineconsole -- --use-event=%d", hEvent);
134 if (CreateProcessA(NULL, path, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
135 goto succeed;
136 sprintf(p, "programs/wineconsole/wineconsole -- --use-event=%d", hEvent);
137 if (CreateProcessA(NULL, path, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
138 goto succeed;
140 } else perror("readlink");
142 HeapFree(GetProcessHeap(), 0, path); path = NULL;
145 /* then try the regular PATH */
146 sprintf(buffer, "wineconsole -- --use-event=%d\n", hEvent);
147 if (CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
148 goto succeed;
150 goto the_end;
152 succeed:
153 if (path) HeapFree(GetProcessHeap(), 0, path);
154 if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) goto the_end;
155 CloseHandle(hEvent);
157 TRACE("Started wineconsole pid=%08lx tid=%08lx\n", pi.dwProcessId, pi.dwThreadId);
159 return TRUE;
161 the_end:
162 ERR("Can't allocate console\n");
163 if (path) HeapFree(GetProcessHeap(), 0, path);
164 CloseHandle(hEvent);
165 return FALSE;
168 /***********************************************************************
169 * AllocConsole (KERNEL32.@)
171 * creates an xterm with a pty to our program
173 BOOL WINAPI AllocConsole(void)
175 HANDLE handle_in = INVALID_HANDLE_VALUE;
176 HANDLE handle_out = INVALID_HANDLE_VALUE;
177 HANDLE handle_err = INVALID_HANDLE_VALUE;
178 STARTUPINFOW si;
180 TRACE("()\n");
182 handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
183 0, NULL, OPEN_EXISTING, 0, 0 );
185 if (handle_in != INVALID_HANDLE_VALUE)
187 /* we already have a console opened on this process, don't create a new one */
188 CloseHandle(handle_in);
189 return FALSE;
192 if (!start_console_renderer())
193 goto the_end;
195 handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
196 0, NULL, OPEN_EXISTING, 0, 0 );
197 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
199 handle_out = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE,
200 0, NULL, OPEN_EXISTING, 0, 0 );
201 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
203 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(), &handle_err,
204 0, TRUE, DUPLICATE_SAME_ACCESS))
205 goto the_end;
207 /* NT resets the STD_*_HANDLEs on console alloc */
208 SetStdHandle(STD_INPUT_HANDLE, handle_in);
209 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
210 SetStdHandle(STD_ERROR_HANDLE, handle_err);
212 GetStartupInfoW(&si);
213 if (si.dwFlags & STARTF_USESIZE)
215 COORD c;
216 c.X = si.dwXCountChars;
217 c.Y = si.dwYCountChars;
218 SetConsoleScreenBufferSize(handle_out, c);
220 if (si.dwFlags & STARTF_USEFILLATTRIBUTE)
221 SetConsoleTextAttribute(handle_out, si.dwFillAttribute);
222 if (si.lpTitle)
223 SetConsoleTitleW(si.lpTitle);
225 SetLastError(ERROR_SUCCESS);
227 return TRUE;
229 the_end:
230 ERR("Can't allocate console\n");
231 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
232 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
233 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
234 FreeConsole();
235 return FALSE;
239 /******************************************************************************
240 * read_console_input
242 * Helper function for ReadConsole, ReadConsoleInput and PeekConsoleInput
244 static BOOL read_console_input(HANDLE handle, LPINPUT_RECORD buffer, DWORD count,
245 LPDWORD pRead, BOOL flush)
247 BOOL ret;
248 unsigned read = 0;
249 DWORD mode;
251 SERVER_START_REQ( read_console_input )
253 req->handle = handle;
254 req->flush = flush;
255 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
256 if ((ret = !wine_server_call_err( req ))) read = reply->read;
258 SERVER_END_REQ;
259 if (count && flush && GetConsoleMode(handle, &mode) && (mode & ENABLE_PROCESSED_INPUT))
261 int i;
263 for (i = 0; i < read; i++)
265 if (buffer[i].EventType == KEY_EVENT && buffer[i].Event.KeyEvent.bKeyDown &&
266 buffer[i].Event.KeyEvent.uChar.UnicodeChar == 'C' - 64 &&
267 !(buffer[i].Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
269 GenerateConsoleCtrlEvent(CTRL_C_EVENT, GetCurrentProcessId());
270 /* FIXME: this is hackish, but it easily disables IR handling afterwards */
271 buffer[i].Event.KeyEvent.uChar.UnicodeChar = 0;
275 if (pRead) *pRead = read;
276 return ret;
280 /***********************************************************************
281 * ReadConsoleA (KERNEL32.@)
283 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
284 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
286 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
287 DWORD ncr = 0;
288 BOOL ret;
290 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, 0)))
291 ncr = WideCharToMultiByte(CP_ACP, 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
293 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
294 HeapFree(GetProcessHeap(), 0, ptr);
296 return ret;
299 /***********************************************************************
300 * ReadConsoleW (KERNEL32.@)
302 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
303 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
305 DWORD charsread;
306 LPWSTR xbuf = (LPWSTR)lpBuffer;
307 DWORD mode;
309 TRACE("(%d,%p,%ld,%p,%p)\n",
310 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
312 if (!GetConsoleMode(hConsoleInput, &mode))
313 return FALSE;
315 if (mode & ENABLE_LINE_INPUT)
317 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
319 if (S_EditString) HeapFree(GetProcessHeap(), 0, S_EditString);
320 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, mode & WINE_ENABLE_LINE_INPUT_EMACS)))
321 return FALSE;
322 S_EditStrPos = 0;
324 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
325 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
326 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
327 S_EditStrPos += charsread;
329 else
331 INPUT_RECORD ir;
332 DWORD count;
334 /* FIXME: should we read at least 1 char? The SDK does not say */
335 /* wait for at least one available input record (it doesn't mean we'll have
336 * chars stored in xbuf...
338 WaitForSingleObject(hConsoleInput, INFINITE);
339 for (charsread = 0; charsread < nNumberOfCharsToRead;)
341 if (!read_console_input(hConsoleInput, &ir, 1, &count, TRUE)) return FALSE;
342 if (count && ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
343 ir.Event.KeyEvent.uChar.UnicodeChar &&
344 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
346 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
351 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
353 return TRUE;
357 /***********************************************************************
358 * ReadConsoleInputW (KERNEL32.@)
360 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, LPINPUT_RECORD lpBuffer,
361 DWORD nLength, LPDWORD lpNumberOfEventsRead)
363 DWORD count;
365 if (!nLength)
367 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
368 return TRUE;
371 /* loop until we get at least one event */
372 for (;;)
374 WaitForSingleObject(hConsoleInput, INFINITE);
375 if (!read_console_input(hConsoleInput, lpBuffer, nLength, &count, TRUE))
376 return FALSE;
377 if (count)
379 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = count;
380 return TRUE;
386 /******************************************************************************
387 * WriteConsoleOutputCharacterW [KERNEL32.@] Copies character to consecutive
388 * cells in the console screen buffer
390 * PARAMS
391 * hConsoleOutput [I] Handle to screen buffer
392 * str [I] Pointer to buffer with chars to write
393 * length [I] Number of cells to write to
394 * coord [I] Coords of first cell
395 * lpNumCharsWritten [O] Pointer to number of cells written
397 * RETURNS
398 * Success: TRUE
399 * Failure: FALSE
402 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
403 COORD coord, LPDWORD lpNumCharsWritten )
405 BOOL ret;
407 TRACE("(%d,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
408 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
410 SERVER_START_REQ( write_console_output )
412 req->handle = hConsoleOutput;
413 req->x = coord.X;
414 req->y = coord.Y;
415 req->mode = CHAR_INFO_MODE_TEXT;
416 req->wrap = TRUE;
417 wine_server_add_data( req, str, length * sizeof(WCHAR) );
418 if ((ret = !wine_server_call_err( req )))
420 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
423 SERVER_END_REQ;
424 return ret;
428 /******************************************************************************
429 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
431 * PARAMS
432 * title [I] Address of new title
434 * RETURNS
435 * Success: TRUE
436 * Failure: FALSE
438 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
440 BOOL ret;
442 SERVER_START_REQ( set_console_input_info )
444 req->handle = 0;
445 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
446 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
447 ret = !wine_server_call_err( req );
449 SERVER_END_REQ;
450 return ret;
454 /***********************************************************************
455 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
457 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
459 FIXME("(%p): stub\n", nrofbuttons);
460 *nrofbuttons = 2;
461 return TRUE;
464 /******************************************************************************
465 * SetConsoleInputExeNameW [KERNEL32.@]
467 * BUGS
468 * Unimplemented
470 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
472 FIXME("(%s): stub!\n", debugstr_w(name));
474 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
475 return TRUE;
478 /******************************************************************************
479 * SetConsoleInputExeNameA [KERNEL32.@]
481 * BUGS
482 * Unimplemented
484 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
486 int len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
487 LPWSTR xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
488 BOOL ret;
490 if (!xptr) return FALSE;
492 MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
493 ret = SetConsoleInputExeNameW(xptr);
494 HeapFree(GetProcessHeap(), 0, xptr);
496 return ret;
499 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
501 FIXME("Terminating process %lx on event %lx\n", GetCurrentProcessId(), dwCtrlType);
502 ExitProcess(0);
503 /* should never go here */
504 return TRUE;
507 /******************************************************************************
508 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
510 * PARAMS
511 * func [I] Address of handler function
512 * add [I] Handler to add or remove
514 * RETURNS
515 * Success: TRUE
516 * Failure: FALSE
518 * CHANGED
519 * James Sutherland (JamesSutherland@gmx.de)
520 * Added global variables console_ignore_ctrl_c and handlers[]
521 * Does not yet do any error checking, or set LastError if failed.
522 * This doesn't yet matter, since these handlers are not yet called...!
524 static unsigned int console_ignore_ctrl_c = 0; /* FIXME: this should be inherited somehow */
525 static PHANDLER_ROUTINE handlers[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,CONSOLE_DefaultHandler};
527 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
529 int alloc_loop = sizeof(handlers)/sizeof(handlers[0]) - 1;
531 FIXME("(%p,%i) - no error checking or testing yet\n", func, add);
533 if (!func)
535 console_ignore_ctrl_c = add;
536 return TRUE;
538 if (add)
540 for (; alloc_loop >= 0 && handlers[alloc_loop]; alloc_loop--);
541 if (alloc_loop <= 0)
543 FIXME("Out of space on CtrlHandler table\n");
544 return FALSE;
546 handlers[alloc_loop] = func;
548 else
550 for (; alloc_loop >= 0 && handlers[alloc_loop] != func; alloc_loop--);
551 if (alloc_loop <= 0)
553 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
554 return FALSE;
556 /* sanity check */
557 if (alloc_loop == sizeof(handlers)/sizeof(handlers[0]) - 1)
559 ERR("Who's trying to remove default handler???\n");
560 return FALSE;
562 if (alloc_loop)
563 memmove(&handlers[1], &handlers[0], alloc_loop * sizeof(handlers[0]));
564 handlers[0] = 0;
566 return TRUE;
569 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
571 TRACE("(%lx)\n", GetExceptionCode());
572 return EXCEPTION_EXECUTE_HANDLER;
575 /******************************************************************************
576 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
578 * PARAMS
579 * dwCtrlEvent [I] Type of event
580 * dwProcessGroupID [I] Process group ID to send event to
582 * NOTES
583 * Doesn't yet work...!
585 * RETURNS
586 * Success: True
587 * Failure: False (and *should* [but doesn't] set LastError)
589 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
590 DWORD dwProcessGroupID)
592 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
594 ERR("invalid event %ld for PGID %ld\n", dwCtrlEvent, dwProcessGroupID);
595 return FALSE;
598 if (dwProcessGroupID == GetCurrentProcessId() || dwProcessGroupID == 0)
600 int i;
602 FIXME("Attempt to send event %ld to self groupID, doing locally only\n", dwCtrlEvent);
604 /* this is only meaningfull when done locally, otherwise it will have to be done on
605 * the 'receive' side of the event generation
607 if (dwCtrlEvent == CTRL_C_EVENT && console_ignore_ctrl_c)
608 return TRUE;
610 /* try to pass the exception to the debugger
611 * if it continues, there's nothing more to do
612 * otherwise, we need to send the ctrl-event to the handlers
614 __TRY
616 RaiseException( (dwCtrlEvent == CTRL_C_EVENT) ? DBG_CONTROL_C : DBG_CONTROL_BREAK,
617 0, 0, NULL);
619 __EXCEPT(CONSOLE_CtrlEventHandler)
621 /* the debugger didn't continue... so, pass to ctrl handlers */
622 for (i = 0; i < sizeof(handlers)/sizeof(handlers[0]); i++)
624 if (handlers[i] && (handlers[i])(dwCtrlEvent)) break;
627 __ENDTRY;
628 return TRUE;
630 FIXME("event %ld to external PGID %ld - not implemented yet\n", dwCtrlEvent, dwProcessGroupID);
631 return FALSE;
635 /******************************************************************************
636 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
638 * PARAMS
639 * dwDesiredAccess [I] Access flag
640 * dwShareMode [I] Buffer share mode
641 * sa [I] Security attributes
642 * dwFlags [I] Type of buffer to create
643 * lpScreenBufferData [I] Reserved
645 * NOTES
646 * Should call SetLastError
648 * RETURNS
649 * Success: Handle to new console screen buffer
650 * Failure: INVALID_HANDLE_VALUE
652 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
653 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
654 LPVOID lpScreenBufferData)
656 HANDLE ret = INVALID_HANDLE_VALUE;
658 TRACE("(%ld,%ld,%p,%ld,%p)\n",
659 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
661 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
663 SetLastError(ERROR_INVALID_PARAMETER);
664 return INVALID_HANDLE_VALUE;
667 SERVER_START_REQ(create_console_output)
669 req->handle_in = 0;
670 req->access = dwDesiredAccess;
671 req->share = dwShareMode;
672 req->inherit = (sa && sa->bInheritHandle);
673 if (!wine_server_call_err( req )) ret = reply->handle_out;
675 SERVER_END_REQ;
677 return ret;
681 /***********************************************************************
682 * GetConsoleScreenBufferInfo (KERNEL32.@)
684 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
686 BOOL ret;
688 SERVER_START_REQ(get_console_output_info)
690 req->handle = hConsoleOutput;
691 if ((ret = !wine_server_call_err( req )))
693 csbi->dwSize.X = reply->width;
694 csbi->dwSize.Y = reply->height;
695 csbi->dwCursorPosition.X = reply->cursor_x;
696 csbi->dwCursorPosition.Y = reply->cursor_y;
697 csbi->wAttributes = reply->attr;
698 csbi->srWindow.Left = reply->win_left;
699 csbi->srWindow.Right = reply->win_right;
700 csbi->srWindow.Top = reply->win_top;
701 csbi->srWindow.Bottom = reply->win_bottom;
702 csbi->dwMaximumWindowSize.X = reply->max_width;
703 csbi->dwMaximumWindowSize.Y = reply->max_height;
706 SERVER_END_REQ;
708 return ret;
712 /******************************************************************************
713 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
715 * RETURNS
716 * Success: TRUE
717 * Failure: FALSE
719 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
721 BOOL ret;
723 TRACE("(%x)\n", hConsoleOutput);
725 SERVER_START_REQ( set_console_input_info )
727 req->handle = 0;
728 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
729 req->active_sb = hConsoleOutput;
730 ret = !wine_server_call_err( req );
732 SERVER_END_REQ;
733 return ret;
737 /***********************************************************************
738 * GetConsoleMode (KERNEL32.@)
740 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
742 BOOL ret;
744 SERVER_START_REQ(get_console_mode)
746 req->handle = hcon;
747 ret = !wine_server_call_err( req );
748 if (ret && mode) *mode = reply->mode;
750 SERVER_END_REQ;
751 return ret;
755 /******************************************************************************
756 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
758 * PARAMS
759 * hcon [I] Handle to console input or screen buffer
760 * mode [I] Input or output mode to set
762 * RETURNS
763 * Success: TRUE
764 * Failure: FALSE
766 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
768 BOOL ret;
770 TRACE("(%x,%lx)\n", hcon, mode);
772 SERVER_START_REQ(set_console_mode)
774 req->handle = hcon;
775 req->mode = mode;
776 ret = !wine_server_call_err( req );
778 SERVER_END_REQ;
779 /* FIXME: when resetting a console input to editline mode, I think we should
780 * empty the S_EditString buffer
782 return ret;
786 /******************************************************************
787 * write_char
789 * WriteConsoleOutput helper: hides server call semantics
791 static int write_char(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
793 int written = -1;
795 if (!nc) return 0;
797 SERVER_START_REQ( write_console_output )
799 req->handle = hCon;
800 req->x = pos->X;
801 req->y = pos->Y;
802 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
803 req->wrap = FALSE;
804 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
805 if (!wine_server_call_err( req )) written = reply->written;
807 SERVER_END_REQ;
809 if (written > 0) pos->X += written;
810 return written;
813 /******************************************************************
814 * next_line
816 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
819 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
821 SMALL_RECT src;
822 CHAR_INFO ci;
823 COORD dst;
825 csbi->dwCursorPosition.X = 0;
826 csbi->dwCursorPosition.Y++;
828 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
830 src.Top = 1;
831 src.Bottom = csbi->dwSize.Y - 1;
832 src.Left = 0;
833 src.Right = csbi->dwSize.X - 1;
835 dst.X = 0;
836 dst.Y = 0;
838 ci.Attributes = csbi->wAttributes;
839 ci.Char.UnicodeChar = ' ';
841 csbi->dwCursorPosition.Y--;
842 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
843 return 0;
844 return 1;
847 /******************************************************************
848 * write_block
850 * WriteConsoleOutput helper: writes a block of non special characters
853 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
854 DWORD mode, LPWSTR ptr, int len)
856 int blk; /* number of chars to write on first line */
858 if (len <= 0) return 1;
860 blk = min(len, csbi->dwSize.X - csbi->dwCursorPosition.X);
862 if (write_char(hCon, ptr, blk, &csbi->dwCursorPosition) != blk)
863 return 0;
865 if (blk < len) /* special handling for right border */
867 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
869 if (!next_line(hCon, csbi) ||
870 write_char(hCon, ptr + blk, len - blk, &csbi->dwCursorPosition) != len - blk)
871 return 0;
873 else /* all remaining chars should be written on last column, so only write the last one */
875 csbi->dwCursorPosition.X = csbi->dwSize.X - 1;
876 if (write_char(hCon, ptr + len - 1, 1, &csbi->dwCursorPosition) != 1)
877 return 0;
878 csbi->dwCursorPosition.X = csbi->dwSize.X - 1;
881 return 1;
884 /***********************************************************************
885 * WriteConsoleW (KERNEL32.@)
887 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
888 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
890 DWORD mode;
891 DWORD nw = 0;
892 WCHAR* psz = (WCHAR*)lpBuffer;
893 CONSOLE_SCREEN_BUFFER_INFO csbi;
894 int k, first = 0;
896 TRACE("%d %s %ld %p %p\n",
897 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
898 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
900 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
902 if (!GetConsoleMode(hConsoleOutput, &mode) ||
903 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
904 return FALSE;
906 if (mode & ENABLE_PROCESSED_OUTPUT)
908 int i;
910 for (i = 0; i < nNumberOfCharsToWrite; i++)
912 switch (psz[i])
914 case '\b': case '\t': case '\n': case '\a': case '\r':
915 /* don't handle here the i-th char... done below */
916 if ((k = i - first) > 0)
918 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
919 goto the_end;
920 nw += k;
922 first = i + 1;
923 nw++;
925 switch (psz[i])
927 case '\b':
928 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
929 break;
930 case '\t':
932 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
934 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
935 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
936 goto the_end;
938 break;
939 case '\n':
940 next_line(hConsoleOutput, &csbi);
941 break;
942 case '\a':
943 Beep(400, 300);
944 break;
945 case '\r':
946 csbi.dwCursorPosition.X = 0;
947 break;
948 default:
949 break;
954 /* write the remaining block (if any) if processed output is enabled, or the
955 * entire buffer otherwise
957 if ((k = nNumberOfCharsToWrite - first) > 0)
959 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
960 goto the_end;
961 nw += k;
964 the_end:
965 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
966 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
967 return nw != 0;
971 /***********************************************************************
972 * WriteConsoleA (KERNEL32.@)
974 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
975 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
977 BOOL ret;
978 LPWSTR xstring;
979 DWORD n;
981 n = MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
983 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
984 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
985 if (!xstring) return 0;
987 MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
989 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
991 HeapFree(GetProcessHeap(), 0, xstring);
993 return ret;
996 /******************************************************************************
997 * SetConsoleCursorPosition [KERNEL32.@]
998 * Sets the cursor position in console
1000 * PARAMS
1001 * hConsoleOutput [I] Handle of console screen buffer
1002 * dwCursorPosition [I] New cursor position coordinates
1004 * RETURNS STD
1006 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
1008 BOOL ret;
1009 CONSOLE_SCREEN_BUFFER_INFO csbi;
1010 int do_move = 0;
1011 int w, h;
1013 TRACE("%x %d %d\n", hcon, pos.X, pos.Y);
1015 SERVER_START_REQ(set_console_output_info)
1017 req->handle = hcon;
1018 req->cursor_x = pos.X;
1019 req->cursor_y = pos.Y;
1020 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
1021 ret = !wine_server_call_err( req );
1023 SERVER_END_REQ;
1025 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
1026 return FALSE;
1028 /* if cursor is no longer visible, scroll the visible window... */
1029 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
1030 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1031 if (pos.X < csbi.srWindow.Left)
1033 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
1034 do_move++;
1036 else if (pos.X > csbi.srWindow.Right)
1038 csbi.srWindow.Left = max(pos.X, w) - w + 1;
1039 do_move++;
1041 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
1043 if (pos.Y < csbi.srWindow.Top)
1045 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
1046 do_move++;
1048 else if (pos.Y > csbi.srWindow.Bottom)
1050 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
1051 do_move++;
1053 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
1055 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
1057 return ret;
1060 /******************************************************************************
1061 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
1063 * PARAMS
1064 * hcon [I] Handle to console screen buffer
1065 * cinfo [O] Address of cursor information
1067 * RETURNS
1068 * Success: TRUE
1069 * Failure: FALSE
1071 BOOL WINAPI GetConsoleCursorInfo(HANDLE hcon, LPCONSOLE_CURSOR_INFO cinfo)
1073 BOOL ret;
1075 SERVER_START_REQ(get_console_output_info)
1077 req->handle = hcon;
1078 ret = !wine_server_call_err( req );
1079 if (ret && cinfo)
1081 cinfo->dwSize = reply->cursor_size;
1082 cinfo->bVisible = reply->cursor_visible;
1085 SERVER_END_REQ;
1086 return ret;
1090 /******************************************************************************
1091 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
1093 * PARAMS
1094 * hcon [I] Handle to console screen buffer
1095 * cinfo [I] Address of cursor information
1096 * RETURNS
1097 * Success: TRUE
1098 * Failure: FALSE
1100 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
1102 BOOL ret;
1104 SERVER_START_REQ(set_console_output_info)
1106 req->handle = hCon;
1107 req->cursor_size = cinfo->dwSize;
1108 req->cursor_visible = cinfo->bVisible;
1109 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
1110 ret = !wine_server_call_err( req );
1112 SERVER_END_REQ;
1113 return ret;
1117 /******************************************************************************
1118 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
1120 * PARAMS
1121 * hcon [I] Handle to console screen buffer
1122 * bAbsolute [I] Coordinate type flag
1123 * window [I] Address of new window rectangle
1124 * RETURNS
1125 * Success: TRUE
1126 * Failure: FALSE
1128 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
1130 SMALL_RECT p = *window;
1131 BOOL ret;
1133 if (!bAbsolute)
1135 CONSOLE_SCREEN_BUFFER_INFO csbi;
1136 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
1137 return FALSE;
1138 p.Left += csbi.srWindow.Left;
1139 p.Top += csbi.srWindow.Top;
1140 p.Right += csbi.srWindow.Left;
1141 p.Bottom += csbi.srWindow.Top;
1143 SERVER_START_REQ(set_console_output_info)
1145 req->handle = hCon;
1146 req->win_left = p.Left;
1147 req->win_top = p.Top;
1148 req->win_right = p.Right;
1149 req->win_bottom = p.Bottom;
1150 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
1151 ret = !wine_server_call_err( req );
1153 SERVER_END_REQ;
1155 return ret;
1159 /******************************************************************************
1160 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
1162 * Sets the foreground and background color attributes of characters
1163 * written to the screen buffer.
1165 * RETURNS
1166 * Success: TRUE
1167 * Failure: FALSE
1169 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
1171 BOOL ret;
1173 SERVER_START_REQ(set_console_output_info)
1175 req->handle = hConsoleOutput;
1176 req->attr = wAttr;
1177 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
1178 ret = !wine_server_call_err( req );
1180 SERVER_END_REQ;
1181 return ret;
1185 /******************************************************************************
1186 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
1188 * PARAMS
1189 * hConsoleOutput [I] Handle to console screen buffer
1190 * dwSize [I] New size in character rows and cols
1192 * RETURNS
1193 * Success: TRUE
1194 * Failure: FALSE
1196 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
1198 BOOL ret;
1200 SERVER_START_REQ(set_console_output_info)
1202 req->handle = hConsoleOutput;
1203 req->width = dwSize.X;
1204 req->height = dwSize.Y;
1205 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
1206 ret = !wine_server_call_err( req );
1208 SERVER_END_REQ;
1209 return ret;
1213 /******************************************************************************
1214 * ScrollConsoleScreenBufferA [KERNEL32.@]
1217 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
1218 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
1219 LPCHAR_INFO lpFill)
1221 CHAR_INFO ciw;
1223 ciw.Attributes = lpFill->Attributes;
1224 MultiByteToWideChar(CP_ACP, 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
1226 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
1227 dwDestOrigin, &ciw);
1230 /******************************************************************
1231 * fill_line_uniform
1233 * Helper function for ScrollConsoleScreenBufferW
1234 * Fills a part of a line with a constant character info
1236 static void fill_line_uniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
1238 SERVER_START_REQ( fill_console_output )
1240 req->handle = hConsoleOutput;
1241 req->mode = CHAR_INFO_MODE_TEXTATTR;
1242 req->x = i;
1243 req->y = j;
1244 req->count = len;
1245 req->wrap = FALSE;
1246 req->data.ch = lpFill->Char.UnicodeChar;
1247 req->data.attr = lpFill->Attributes;
1248 wine_server_call_err( req );
1250 SERVER_END_REQ;
1253 /******************************************************************************
1254 * ScrollConsoleScreenBufferW [KERNEL32.@]
1258 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
1259 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
1260 LPCHAR_INFO lpFill)
1262 SMALL_RECT dst;
1263 DWORD ret;
1264 int i, j;
1265 int start = -1;
1266 SMALL_RECT clip;
1267 CONSOLE_SCREEN_BUFFER_INFO csbi;
1268 BOOL inside;
1270 if (lpClipRect)
1271 TRACE("(%d,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
1272 lpScrollRect->Left, lpScrollRect->Top,
1273 lpScrollRect->Right, lpScrollRect->Bottom,
1274 lpClipRect->Left, lpClipRect->Top,
1275 lpClipRect->Right, lpClipRect->Bottom,
1276 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
1277 else
1278 TRACE("(%d,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
1279 lpScrollRect->Left, lpScrollRect->Top,
1280 lpScrollRect->Right, lpScrollRect->Bottom,
1281 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
1283 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1284 return FALSE;
1286 /* step 1: get dst rect */
1287 dst.Left = dwDestOrigin.X;
1288 dst.Top = dwDestOrigin.Y;
1289 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
1290 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
1292 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
1293 if (lpClipRect)
1295 clip.Left = max(0, lpClipRect->Left);
1296 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
1297 clip.Top = max(0, lpClipRect->Top);
1298 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
1300 else
1302 clip.Left = 0;
1303 clip.Right = csbi.dwSize.X - 1;
1304 clip.Top = 0;
1305 clip.Bottom = csbi.dwSize.Y - 1;
1307 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
1309 /* step 2b: clip dst rect */
1310 if (dst.Left < clip.Left ) dst.Left = clip.Left;
1311 if (dst.Top < clip.Top ) dst.Top = clip.Top;
1312 if (dst.Right > clip.Right ) dst.Right = clip.Right;
1313 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
1315 /* step 3: transfer the bits */
1316 SERVER_START_REQ(move_console_output)
1318 req->handle = hConsoleOutput;
1319 req->x_src = lpScrollRect->Left;
1320 req->y_src = lpScrollRect->Top;
1321 req->x_dst = dst.Left;
1322 req->y_dst = dst.Top;
1323 req->w = dst.Right - dst.Left + 1;
1324 req->h = dst.Bottom - dst.Top + 1;
1325 ret = !wine_server_call_err( req );
1327 SERVER_END_REQ;
1329 if (!ret) return FALSE;
1331 /* step 4: clean out the exposed part */
1333 /* have to write celll [i,j] if it is not in dst rect (because it has already
1334 * been written to by the scroll) and is in clip (we shall not write
1335 * outside of clip)
1337 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
1339 inside = dst.Top <= j && j <= dst.Bottom;
1340 start = -1;
1341 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
1343 if (inside && dst.Left <= i && i <= dst.Right)
1345 if (start != -1)
1347 fill_line_uniform(hConsoleOutput, start, j, i - start, lpFill);
1348 start = -1;
1351 else
1353 if (start == -1) start = i;
1356 if (start != -1)
1357 fill_line_uniform(hConsoleOutput, start, j, i - start, lpFill);
1360 return TRUE;
1364 /* ====================================================================
1366 * Console manipulation functions
1368 * ====================================================================*/
1369 /* some missing functions...
1370 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
1371 * should get the right API and implement them
1372 * GetConsoleCommandHistory[AW] (dword dword dword)
1373 * GetConsoleCommandHistoryLength[AW]
1374 * SetConsoleCommandHistoryMode
1375 * SetConsoleNumberOfCommands[AW]
1377 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
1379 int len = 0;
1381 SERVER_START_REQ( get_console_input_history )
1383 req->handle = 0;
1384 req->index = idx;
1385 if (buf && buf_len > 1)
1387 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
1389 if (!wine_server_call_err( req ))
1391 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
1392 len = reply->total / sizeof(WCHAR) + 1;
1395 SERVER_END_REQ;
1396 return len;
1399 /******************************************************************
1400 * CONSOLE_AppendHistory
1404 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
1406 size_t len = strlenW(ptr);
1407 BOOL ret;
1409 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
1411 SERVER_START_REQ( append_console_input_history )
1413 req->handle = 0;
1414 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
1415 ret = !wine_server_call_err( req );
1417 SERVER_END_REQ;
1418 return ret;
1421 /******************************************************************
1422 * CONSOLE_GetNumHistoryEntries
1426 unsigned CONSOLE_GetNumHistoryEntries(void)
1428 unsigned ret = 0;
1429 SERVER_START_REQ(get_console_input_info)
1431 req->handle = 0;
1432 if (!wine_server_call_err( req )) ret = reply->history_index;
1434 SERVER_END_REQ;
1435 return ret;