Added a pass-through msvcrt20.
[wine/dcerpc.git] / win32 / console.c
bloba5b8f122d3d9722f0e78cfb76de8d419fdc6dadc
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...!
525 static unsigned int console_ignore_ctrl_c = 0; /* FIXME: this should be inherited somehow */
526 static PHANDLER_ROUTINE handlers[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,CONSOLE_DefaultHandler};
528 /*****************************************************************************/
530 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
532 int alloc_loop = sizeof(handlers)/sizeof(handlers[0]) - 1;
534 FIXME("(%p,%i) - no error checking or testing yet\n", func, add);
536 if (!func)
538 console_ignore_ctrl_c = add;
539 return TRUE;
541 if (add)
543 for (; alloc_loop >= 0 && handlers[alloc_loop]; alloc_loop--);
544 if (alloc_loop <= 0)
546 FIXME("Out of space on CtrlHandler table\n");
547 return FALSE;
549 handlers[alloc_loop] = func;
551 else
553 for (; alloc_loop >= 0 && handlers[alloc_loop] != func; alloc_loop--);
554 if (alloc_loop <= 0)
556 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
557 return FALSE;
559 /* sanity check */
560 if (alloc_loop == sizeof(handlers)/sizeof(handlers[0]) - 1)
562 ERR("Who's trying to remove default handler???\n");
563 return FALSE;
565 if (alloc_loop)
566 memmove(&handlers[1], &handlers[0], alloc_loop * sizeof(handlers[0]));
567 handlers[0] = 0;
569 return TRUE;
572 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
574 TRACE("(%lx)\n", GetExceptionCode());
575 return EXCEPTION_EXECUTE_HANDLER;
578 /******************************************************************************
579 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
581 * PARAMS
582 * dwCtrlEvent [I] Type of event
583 * dwProcessGroupID [I] Process group ID to send event to
585 * NOTES
586 * Doesn't yet work...!
588 * RETURNS
589 * Success: True
590 * Failure: False (and *should* [but doesn't] set LastError)
592 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
593 DWORD dwProcessGroupID)
595 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
597 ERR("invalid event %ld for PGID %ld\n", dwCtrlEvent, dwProcessGroupID);
598 return FALSE;
601 if (dwProcessGroupID == GetCurrentProcessId() || dwProcessGroupID == 0)
603 int i;
605 FIXME("Attempt to send event %ld to self groupID, doing locally only\n", dwCtrlEvent);
607 /* this is only meaningfull when done locally, otherwise it will have to be done on
608 * the 'receive' side of the event generation
610 if (dwCtrlEvent == CTRL_C_EVENT && console_ignore_ctrl_c)
611 return TRUE;
613 /* try to pass the exception to the debugger
614 * if it continues, there's nothing more to do
615 * otherwise, we need to send the ctrl-event to the handlers
617 __TRY
619 RaiseException( (dwCtrlEvent == CTRL_C_EVENT) ? DBG_CONTROL_C : DBG_CONTROL_BREAK,
620 0, 0, NULL);
622 __EXCEPT(CONSOLE_CtrlEventHandler)
624 /* the debugger didn't continue... so, pass to ctrl handlers */
625 for (i = 0; i < sizeof(handlers)/sizeof(handlers[0]); i++)
627 if (handlers[i] && (handlers[i])(dwCtrlEvent)) break;
630 __ENDTRY;
631 return TRUE;
633 FIXME("event %ld to external PGID %ld - not implemented yet\n", dwCtrlEvent, dwProcessGroupID);
634 return FALSE;
638 /******************************************************************************
639 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
641 * PARAMS
642 * dwDesiredAccess [I] Access flag
643 * dwShareMode [I] Buffer share mode
644 * sa [I] Security attributes
645 * dwFlags [I] Type of buffer to create
646 * lpScreenBufferData [I] Reserved
648 * NOTES
649 * Should call SetLastError
651 * RETURNS
652 * Success: Handle to new console screen buffer
653 * Failure: INVALID_HANDLE_VALUE
655 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
656 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
657 LPVOID lpScreenBufferData)
659 HANDLE ret = INVALID_HANDLE_VALUE;
661 TRACE("(%ld,%ld,%p,%ld,%p)\n",
662 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
664 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
666 SetLastError(ERROR_INVALID_PARAMETER);
667 return INVALID_HANDLE_VALUE;
670 SERVER_START_REQ(create_console_output)
672 req->handle_in = 0;
673 req->access = dwDesiredAccess;
674 req->share = dwShareMode;
675 req->inherit = (sa && sa->bInheritHandle);
676 if (!wine_server_call_err( req )) ret = reply->handle_out;
678 SERVER_END_REQ;
680 return ret;
684 /***********************************************************************
685 * GetConsoleScreenBufferInfo (KERNEL32.@)
687 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
689 BOOL ret;
691 SERVER_START_REQ(get_console_output_info)
693 req->handle = hConsoleOutput;
694 if ((ret = !wine_server_call_err( req )))
696 csbi->dwSize.X = reply->width;
697 csbi->dwSize.Y = reply->height;
698 csbi->dwCursorPosition.X = reply->cursor_x;
699 csbi->dwCursorPosition.Y = reply->cursor_y;
700 csbi->wAttributes = reply->attr;
701 csbi->srWindow.Left = reply->win_left;
702 csbi->srWindow.Right = reply->win_right;
703 csbi->srWindow.Top = reply->win_top;
704 csbi->srWindow.Bottom = reply->win_bottom;
705 csbi->dwMaximumWindowSize.X = reply->max_width;
706 csbi->dwMaximumWindowSize.Y = reply->max_height;
709 SERVER_END_REQ;
711 return ret;
715 /******************************************************************************
716 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
718 * RETURNS
719 * Success: TRUE
720 * Failure: FALSE
722 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
724 BOOL ret;
726 TRACE("(%x)\n", hConsoleOutput);
728 SERVER_START_REQ( set_console_input_info )
730 req->handle = 0;
731 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
732 req->active_sb = hConsoleOutput;
733 ret = !wine_server_call_err( req );
735 SERVER_END_REQ;
736 return ret;
740 /***********************************************************************
741 * GetConsoleMode (KERNEL32.@)
743 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
745 BOOL ret;
747 SERVER_START_REQ(get_console_mode)
749 req->handle = hcon;
750 ret = !wine_server_call_err( req );
751 if (ret && mode) *mode = reply->mode;
753 SERVER_END_REQ;
754 return ret;
758 /******************************************************************************
759 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
761 * PARAMS
762 * hcon [I] Handle to console input or screen buffer
763 * mode [I] Input or output mode to set
765 * RETURNS
766 * Success: TRUE
767 * Failure: FALSE
769 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
771 BOOL ret;
773 TRACE("(%x,%lx)\n", hcon, mode);
775 SERVER_START_REQ(set_console_mode)
777 req->handle = hcon;
778 req->mode = mode;
779 ret = !wine_server_call_err( req );
781 SERVER_END_REQ;
782 /* FIXME: when resetting a console input to editline mode, I think we should
783 * empty the S_EditString buffer
785 return ret;
789 /******************************************************************
790 * write_char
792 * WriteConsoleOutput helper: hides server call semantics
794 static int write_char(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
796 int written = -1;
798 if (!nc) return 0;
800 SERVER_START_REQ( write_console_output )
802 req->handle = hCon;
803 req->x = pos->X;
804 req->y = pos->Y;
805 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
806 req->wrap = FALSE;
807 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
808 if (!wine_server_call_err( req )) written = reply->written;
810 SERVER_END_REQ;
812 if (written > 0) pos->X += written;
813 return written;
816 /******************************************************************
817 * next_line
819 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
822 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
824 SMALL_RECT src;
825 CHAR_INFO ci;
826 COORD dst;
828 csbi->dwCursorPosition.X = 0;
829 csbi->dwCursorPosition.Y++;
831 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
833 src.Top = 1;
834 src.Bottom = csbi->dwSize.Y - 1;
835 src.Left = 0;
836 src.Right = csbi->dwSize.X - 1;
838 dst.X = 0;
839 dst.Y = 0;
841 ci.Attributes = csbi->wAttributes;
842 ci.Char.UnicodeChar = ' ';
844 csbi->dwCursorPosition.Y--;
845 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
846 return 0;
847 return 1;
850 /******************************************************************
851 * write_block
853 * WriteConsoleOutput helper: writes a block of non special characters
856 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
857 DWORD mode, LPWSTR ptr, int len)
859 int blk; /* number of chars to write on first line */
861 if (len <= 0) return 1;
863 blk = min(len, csbi->dwSize.X - csbi->dwCursorPosition.X);
865 if (write_char(hCon, ptr, blk, &csbi->dwCursorPosition) != blk)
866 return 0;
868 if (blk < len) /* special handling for right border */
870 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
872 if (!next_line(hCon, csbi) ||
873 write_char(hCon, ptr + blk, len - blk, &csbi->dwCursorPosition) != len - blk)
874 return 0;
876 else /* all remaining chars should be written on last column, so only write the last one */
878 csbi->dwCursorPosition.X = csbi->dwSize.X - 1;
879 if (write_char(hCon, ptr + len - 1, 1, &csbi->dwCursorPosition) != 1)
880 return 0;
881 csbi->dwCursorPosition.X = csbi->dwSize.X - 1;
884 return 1;
887 /***********************************************************************
888 * WriteConsoleW (KERNEL32.@)
890 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
891 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
893 DWORD mode;
894 DWORD nw = 0;
895 WCHAR* psz = (WCHAR*)lpBuffer;
896 CONSOLE_SCREEN_BUFFER_INFO csbi;
897 int k, first = 0;
899 TRACE("%d %s %ld %p %p\n",
900 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
901 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
903 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
905 if (!GetConsoleMode(hConsoleOutput, &mode) ||
906 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
907 return FALSE;
909 if (mode & ENABLE_PROCESSED_OUTPUT)
911 int i;
913 for (i = 0; i < nNumberOfCharsToWrite; i++)
915 switch (psz[i])
917 case '\b': case '\t': case '\n': case '\a': case '\r':
918 /* don't handle here the i-th char... done below */
919 if ((k = i - first) > 0)
921 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
922 goto the_end;
923 nw += k;
925 first = i + 1;
926 nw++;
928 switch (psz[i])
930 case '\b':
931 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
932 break;
933 case '\t':
935 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
937 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
938 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
939 goto the_end;
941 break;
942 case '\n':
943 next_line(hConsoleOutput, &csbi);
944 break;
945 case '\a':
946 Beep(400, 300);
947 break;
948 case '\r':
949 csbi.dwCursorPosition.X = 0;
950 break;
951 default:
952 break;
957 /* write the remaining block (if any) if processed output is enabled, or the
958 * entire buffer otherwise
960 if ((k = nNumberOfCharsToWrite - first) > 0)
962 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
963 goto the_end;
964 nw += k;
967 the_end:
968 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
969 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
970 return nw != 0;
974 /***********************************************************************
975 * WriteConsoleA (KERNEL32.@)
977 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
978 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
980 BOOL ret;
981 LPWSTR xstring;
982 DWORD n;
984 n = MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
986 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
987 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
988 if (!xstring) return 0;
990 MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
992 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
994 HeapFree(GetProcessHeap(), 0, xstring);
996 return ret;
999 /******************************************************************************
1000 * SetConsoleCursorPosition [KERNEL32.@]
1001 * Sets the cursor position in console
1003 * PARAMS
1004 * hConsoleOutput [I] Handle of console screen buffer
1005 * dwCursorPosition [I] New cursor position coordinates
1007 * RETURNS STD
1009 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
1011 BOOL ret;
1012 CONSOLE_SCREEN_BUFFER_INFO csbi;
1013 int do_move = 0;
1014 int w, h;
1016 TRACE("%x %d %d\n", hcon, pos.X, pos.Y);
1018 SERVER_START_REQ(set_console_output_info)
1020 req->handle = hcon;
1021 req->cursor_x = pos.X;
1022 req->cursor_y = pos.Y;
1023 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
1024 ret = !wine_server_call_err( req );
1026 SERVER_END_REQ;
1028 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
1029 return FALSE;
1031 /* if cursor is no longer visible, scroll the visible window... */
1032 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
1033 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1034 if (pos.X < csbi.srWindow.Left)
1036 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
1037 do_move++;
1039 else if (pos.X > csbi.srWindow.Right)
1041 csbi.srWindow.Left = max(pos.X, w) - w + 1;
1042 do_move++;
1044 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
1046 if (pos.Y < csbi.srWindow.Top)
1048 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
1049 do_move++;
1051 else if (pos.Y > csbi.srWindow.Bottom)
1053 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
1054 do_move++;
1056 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
1058 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
1060 return ret;
1063 /******************************************************************************
1064 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
1066 * PARAMS
1067 * hcon [I] Handle to console screen buffer
1068 * cinfo [O] Address of cursor information
1070 * RETURNS
1071 * Success: TRUE
1072 * Failure: FALSE
1074 BOOL WINAPI GetConsoleCursorInfo(HANDLE hcon, LPCONSOLE_CURSOR_INFO cinfo)
1076 BOOL ret;
1078 SERVER_START_REQ(get_console_output_info)
1080 req->handle = hcon;
1081 ret = !wine_server_call_err( req );
1082 if (ret && cinfo)
1084 cinfo->dwSize = reply->cursor_size;
1085 cinfo->bVisible = reply->cursor_visible;
1088 SERVER_END_REQ;
1089 return ret;
1093 /******************************************************************************
1094 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
1096 * PARAMS
1097 * hcon [I] Handle to console screen buffer
1098 * cinfo [I] Address of cursor information
1099 * RETURNS
1100 * Success: TRUE
1101 * Failure: FALSE
1103 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
1105 BOOL ret;
1107 SERVER_START_REQ(set_console_output_info)
1109 req->handle = hCon;
1110 req->cursor_size = cinfo->dwSize;
1111 req->cursor_visible = cinfo->bVisible;
1112 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
1113 ret = !wine_server_call_err( req );
1115 SERVER_END_REQ;
1116 return ret;
1120 /******************************************************************************
1121 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
1123 * PARAMS
1124 * hcon [I] Handle to console screen buffer
1125 * bAbsolute [I] Coordinate type flag
1126 * window [I] Address of new window rectangle
1127 * RETURNS
1128 * Success: TRUE
1129 * Failure: FALSE
1131 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
1133 SMALL_RECT p = *window;
1134 BOOL ret;
1136 if (!bAbsolute)
1138 CONSOLE_SCREEN_BUFFER_INFO csbi;
1139 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
1140 return FALSE;
1141 p.Left += csbi.srWindow.Left;
1142 p.Top += csbi.srWindow.Top;
1143 p.Right += csbi.srWindow.Left;
1144 p.Bottom += csbi.srWindow.Top;
1146 SERVER_START_REQ(set_console_output_info)
1148 req->handle = hCon;
1149 req->win_left = p.Left;
1150 req->win_top = p.Top;
1151 req->win_right = p.Right;
1152 req->win_bottom = p.Bottom;
1153 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
1154 ret = !wine_server_call_err( req );
1156 SERVER_END_REQ;
1158 return ret;
1162 /******************************************************************************
1163 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
1165 * Sets the foreground and background color attributes of characters
1166 * written to the screen buffer.
1168 * RETURNS
1169 * Success: TRUE
1170 * Failure: FALSE
1172 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
1174 BOOL ret;
1176 SERVER_START_REQ(set_console_output_info)
1178 req->handle = hConsoleOutput;
1179 req->attr = wAttr;
1180 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
1181 ret = !wine_server_call_err( req );
1183 SERVER_END_REQ;
1184 return ret;
1188 /******************************************************************************
1189 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
1191 * PARAMS
1192 * hConsoleOutput [I] Handle to console screen buffer
1193 * dwSize [I] New size in character rows and cols
1195 * RETURNS
1196 * Success: TRUE
1197 * Failure: FALSE
1199 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
1201 BOOL ret;
1203 SERVER_START_REQ(set_console_output_info)
1205 req->handle = hConsoleOutput;
1206 req->width = dwSize.X;
1207 req->height = dwSize.Y;
1208 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
1209 ret = !wine_server_call_err( req );
1211 SERVER_END_REQ;
1212 return ret;
1216 /******************************************************************************
1217 * ScrollConsoleScreenBufferA [KERNEL32.@]
1220 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
1221 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
1222 LPCHAR_INFO lpFill)
1224 CHAR_INFO ciw;
1226 ciw.Attributes = lpFill->Attributes;
1227 MultiByteToWideChar(CP_ACP, 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
1229 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
1230 dwDestOrigin, &ciw);
1233 /******************************************************************
1234 * fill_line_uniform
1236 * Helper function for ScrollConsoleScreenBufferW
1237 * Fills a part of a line with a constant character info
1239 static void fill_line_uniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
1241 SERVER_START_REQ( fill_console_output )
1243 req->handle = hConsoleOutput;
1244 req->mode = CHAR_INFO_MODE_TEXTATTR;
1245 req->x = i;
1246 req->y = j;
1247 req->count = len;
1248 req->wrap = FALSE;
1249 req->data.ch = lpFill->Char.UnicodeChar;
1250 req->data.attr = lpFill->Attributes;
1251 wine_server_call_err( req );
1253 SERVER_END_REQ;
1256 /******************************************************************************
1257 * ScrollConsoleScreenBufferW [KERNEL32.@]
1261 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
1262 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
1263 LPCHAR_INFO lpFill)
1265 SMALL_RECT dst;
1266 DWORD ret;
1267 int i, j;
1268 int start = -1;
1269 SMALL_RECT clip;
1270 CONSOLE_SCREEN_BUFFER_INFO csbi;
1271 BOOL inside;
1273 if (lpClipRect)
1274 TRACE("(%d,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
1275 lpScrollRect->Left, lpScrollRect->Top,
1276 lpScrollRect->Right, lpScrollRect->Bottom,
1277 lpClipRect->Left, lpClipRect->Top,
1278 lpClipRect->Right, lpClipRect->Bottom,
1279 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
1280 else
1281 TRACE("(%d,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
1282 lpScrollRect->Left, lpScrollRect->Top,
1283 lpScrollRect->Right, lpScrollRect->Bottom,
1284 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
1286 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1287 return FALSE;
1289 /* step 1: get dst rect */
1290 dst.Left = dwDestOrigin.X;
1291 dst.Top = dwDestOrigin.Y;
1292 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
1293 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
1295 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
1296 if (lpClipRect)
1298 clip.Left = max(0, lpClipRect->Left);
1299 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
1300 clip.Top = max(0, lpClipRect->Top);
1301 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
1303 else
1305 clip.Left = 0;
1306 clip.Right = csbi.dwSize.X - 1;
1307 clip.Top = 0;
1308 clip.Bottom = csbi.dwSize.Y - 1;
1310 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
1312 /* step 2b: clip dst rect */
1313 if (dst.Left < clip.Left ) dst.Left = clip.Left;
1314 if (dst.Top < clip.Top ) dst.Top = clip.Top;
1315 if (dst.Right > clip.Right ) dst.Right = clip.Right;
1316 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
1318 /* step 3: transfer the bits */
1319 SERVER_START_REQ(move_console_output)
1321 req->handle = hConsoleOutput;
1322 req->x_src = lpScrollRect->Left;
1323 req->y_src = lpScrollRect->Top;
1324 req->x_dst = dst.Left;
1325 req->y_dst = dst.Top;
1326 req->w = dst.Right - dst.Left + 1;
1327 req->h = dst.Bottom - dst.Top + 1;
1328 ret = !wine_server_call_err( req );
1330 SERVER_END_REQ;
1332 if (!ret) return FALSE;
1334 /* step 4: clean out the exposed part */
1336 /* have to write celll [i,j] if it is not in dst rect (because it has already
1337 * been written to by the scroll) and is in clip (we shall not write
1338 * outside of clip)
1340 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
1342 inside = dst.Top <= j && j <= dst.Bottom;
1343 start = -1;
1344 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
1346 if (inside && dst.Left <= i && i <= dst.Right)
1348 if (start != -1)
1350 fill_line_uniform(hConsoleOutput, start, j, i - start, lpFill);
1351 start = -1;
1354 else
1356 if (start == -1) start = i;
1359 if (start != -1)
1360 fill_line_uniform(hConsoleOutput, start, j, i - start, lpFill);
1363 return TRUE;
1367 /* ====================================================================
1369 * Console manipulation functions
1371 * ====================================================================*/
1372 /* some missing functions...
1373 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
1374 * should get the right API and implement them
1375 * GetConsoleCommandHistory[AW] (dword dword dword)
1376 * GetConsoleCommandHistoryLength[AW]
1377 * SetConsoleCommandHistoryMode
1378 * SetConsoleNumberOfCommands[AW]
1380 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
1382 int len = 0;
1384 SERVER_START_REQ( get_console_input_history )
1386 req->handle = 0;
1387 req->index = idx;
1388 if (buf && buf_len > 1)
1390 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
1392 if (!wine_server_call_err( req ))
1394 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
1395 len = reply->total / sizeof(WCHAR) + 1;
1398 SERVER_END_REQ;
1399 return len;
1402 /******************************************************************
1403 * CONSOLE_AppendHistory
1407 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
1409 size_t len = strlenW(ptr);
1410 BOOL ret;
1412 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
1414 SERVER_START_REQ( append_console_input_history )
1416 req->handle = 0;
1417 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
1418 ret = !wine_server_call_err( req );
1420 SERVER_END_REQ;
1421 return ret;
1424 /******************************************************************
1425 * CONSOLE_GetNumHistoryEntries
1429 unsigned CONSOLE_GetNumHistoryEntries(void)
1431 unsigned ret = 0;
1432 SERVER_START_REQ(get_console_input_info)
1434 req->handle = 0;
1435 if (!wine_server_call_err( req )) ret = reply->history_index;
1437 SERVER_END_REQ;
1438 return ret;