2 * Win32 console 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,2002,2004,2005 Eric Pouech
9 * Copyright 2001 Alexandre Julliard
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 /* Reference applications:
27 * - IDA (interactive disassembler) full version 3.75. Works.
28 * - LYNX/W32. Works mostly, some keys crash it.
32 #include "wine/port.h"
44 #ifdef HAVE_SYS_POLL_H
45 # include <sys/poll.h>
49 #define WIN32_NO_STATUS
55 #include "wine/server.h"
56 #include "wine/exception.h"
57 #include "wine/unicode.h"
58 #include "wine/debug.h"
60 #include "console_private.h"
61 #include "kernel_private.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(console);
65 static CRITICAL_SECTION CONSOLE_CritSect;
66 static CRITICAL_SECTION_DEBUG critsect_debug =
68 0, 0, &CONSOLE_CritSect,
69 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
70 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
72 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
74 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
75 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
77 /* FIXME: this is not thread safe */
78 static HANDLE console_wait_event;
80 /* map input records to ASCII */
81 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
86 for (i = 0; i < count; i++)
88 if (buffer[i].EventType != KEY_EVENT) continue;
89 WideCharToMultiByte( GetConsoleCP(), 0,
90 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
91 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
95 /* map input records to Unicode */
96 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
101 for (i = 0; i < count; i++)
103 if (buffer[i].EventType != KEY_EVENT) continue;
104 MultiByteToWideChar( GetConsoleCP(), 0,
105 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
106 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
110 /* map char infos to ASCII */
111 static void char_info_WtoA( CHAR_INFO *buffer, int count )
117 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
118 &ch, 1, NULL, NULL );
119 buffer->Char.AsciiChar = ch;
124 /* map char infos to Unicode */
125 static void char_info_AtoW( CHAR_INFO *buffer, int count )
131 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
132 buffer->Char.UnicodeChar = ch;
137 static struct termios S_termios; /* saved termios for bare consoles */
138 static BOOL S_termios_raw /* = FALSE */;
140 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
141 * - a bare console is created for all CUI programs started from command line (without
142 * wineconsole) (let's call those PS)
143 * - of course, every child of a PS which requires console inheritance will get it
144 * - the console termios attributes are saved at the start of program which is attached to be
146 * - if any program attached to a bare console requests input from console, the console is
147 * turned into raw mode
148 * - when the program which created the bare console (the program started from command line)
149 * exits, it will restore the console termios attributes it saved at startup (this
150 * will put back the console into cooked mode if it had been put in raw mode)
151 * - if any other program attached to this bare console is still alive, the Unix shell will put
152 * it in the background, hence forbidding access to the console. Therefore, reading console
153 * input will not be available when the bare console creator has died.
154 * FIXME: This is a limitation of current implementation
157 /* returns the fd for a bare console (-1 otherwise) */
158 static int get_console_bare_fd(HANDLE hin)
162 if (wine_server_handle_to_fd(wine_server_ptr_handle(console_handle_unmap(hin)),
163 0, &fd, NULL) == STATUS_SUCCESS)
168 static BOOL save_console_mode(HANDLE hin)
173 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
174 ret = tcgetattr(fd, &S_termios) >= 0;
179 static BOOL put_console_into_raw_mode(int fd)
181 RtlEnterCriticalSection(&CONSOLE_CritSect);
184 struct termios term = S_termios;
186 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
187 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
188 term.c_cflag &= ~(CSIZE | PARENB);
190 /* FIXME: we should actually disable output processing here
191 * and let kernel32/console.c do the job (with support of enable/disable of
194 /* term.c_oflag &= ~(OPOST); */
196 term.c_cc[VTIME] = 0;
197 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
199 RtlLeaveCriticalSection(&CONSOLE_CritSect);
201 return S_termios_raw;
204 /* put back the console in cooked mode iff we're the process which created the bare console
205 * we don't test if thie process has set the console in raw mode as it could be one of its
208 static BOOL restore_console_mode(HANDLE hin)
213 if (!S_termios_raw ||
214 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
216 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
217 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
222 /******************************************************************************
223 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
226 * Success: hwnd of the console window.
229 HWND WINAPI GetConsoleWindow(VOID)
233 SERVER_START_REQ(get_console_input_info)
236 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
244 /******************************************************************************
245 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
250 UINT WINAPI GetConsoleCP(VOID)
253 UINT codepage = GetOEMCP(); /* default value */
255 SERVER_START_REQ(get_console_input_info)
258 ret = !wine_server_call_err(req);
259 if (ret && reply->input_cp)
260 codepage = reply->input_cp;
268 /******************************************************************************
269 * SetConsoleCP [KERNEL32.@]
271 BOOL WINAPI SetConsoleCP(UINT cp)
275 if (!IsValidCodePage(cp))
277 SetLastError(ERROR_INVALID_PARAMETER);
281 SERVER_START_REQ(set_console_input_info)
284 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
286 ret = !wine_server_call_err(req);
294 /***********************************************************************
295 * GetConsoleOutputCP (KERNEL32.@)
297 UINT WINAPI GetConsoleOutputCP(VOID)
300 UINT codepage = GetOEMCP(); /* default value */
302 SERVER_START_REQ(get_console_input_info)
305 ret = !wine_server_call_err(req);
306 if (ret && reply->output_cp)
307 codepage = reply->output_cp;
315 /******************************************************************************
316 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
319 * cp [I] code page to set
325 BOOL WINAPI SetConsoleOutputCP(UINT cp)
329 if (!IsValidCodePage(cp))
331 SetLastError(ERROR_INVALID_PARAMETER);
335 SERVER_START_REQ(set_console_input_info)
338 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
340 ret = !wine_server_call_err(req);
348 /***********************************************************************
351 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
353 static const char beep = '\a';
354 /* dwFreq and dwDur are ignored by Win95 */
355 if (isatty(2)) write( 2, &beep, 1 );
360 /******************************************************************
361 * OpenConsoleW (KERNEL32.@)
364 * Open a handle to the current process console.
365 * Returns INVALID_HANDLE_VALUE on failure.
367 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
369 HANDLE output = INVALID_HANDLE_VALUE;
372 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
376 if (strcmpiW(coninW, name) == 0)
377 output = (HANDLE) FALSE;
378 else if (strcmpiW(conoutW, name) == 0)
379 output = (HANDLE) TRUE;
382 if (output == INVALID_HANDLE_VALUE)
384 SetLastError(ERROR_INVALID_PARAMETER);
385 return INVALID_HANDLE_VALUE;
387 else if (creation != OPEN_EXISTING)
389 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
390 SetLastError(ERROR_SHARING_VIOLATION);
392 SetLastError(ERROR_INVALID_PARAMETER);
393 return INVALID_HANDLE_VALUE;
396 SERVER_START_REQ( open_console )
398 req->from = wine_server_obj_handle( output );
399 req->access = access;
400 req->attributes = inherit ? OBJ_INHERIT : 0;
401 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
402 wine_server_call_err( req );
403 ret = wine_server_ptr_handle( reply->handle );
407 ret = console_handle_map(ret);
412 /******************************************************************
413 * VerifyConsoleIoHandle (KERNEL32.@)
417 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
421 if (!is_console_handle(handle)) return FALSE;
422 SERVER_START_REQ(get_console_mode)
424 req->handle = console_handle_unmap(handle);
425 ret = !wine_server_call( req );
431 /******************************************************************
432 * DuplicateConsoleHandle (KERNEL32.@)
436 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
441 if (!is_console_handle(handle) ||
442 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
443 GetCurrentProcess(), &ret, access, inherit, options))
444 return INVALID_HANDLE_VALUE;
445 return console_handle_map(ret);
448 /******************************************************************
449 * CloseConsoleHandle (KERNEL32.@)
453 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
455 if (!is_console_handle(handle))
457 SetLastError(ERROR_INVALID_PARAMETER);
460 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
463 /******************************************************************
464 * GetConsoleInputWaitHandle (KERNEL32.@)
468 HANDLE WINAPI GetConsoleInputWaitHandle(void)
470 if (!console_wait_event)
472 SERVER_START_REQ(get_console_wait_event)
474 if (!wine_server_call_err( req ))
475 console_wait_event = wine_server_ptr_handle( reply->handle );
479 return console_wait_event;
483 /******************************************************************************
484 * WriteConsoleInputA [KERNEL32.@]
486 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
487 DWORD count, LPDWORD written )
489 INPUT_RECORD *recW = NULL;
496 SetLastError( ERROR_INVALID_ACCESS );
500 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) )))
502 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
506 memcpy( recW, buffer, count * sizeof(*recW) );
507 input_records_AtoW( recW, count );
510 ret = WriteConsoleInputW( handle, recW, count, written );
511 HeapFree( GetProcessHeap(), 0, recW );
516 /******************************************************************************
517 * WriteConsoleInputW [KERNEL32.@]
519 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
520 DWORD count, LPDWORD written )
522 DWORD events_written = 0;
525 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
527 if (count > 0 && !buffer)
529 SetLastError(ERROR_INVALID_ACCESS);
533 SERVER_START_REQ( write_console_input )
535 req->handle = console_handle_unmap(handle);
536 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
537 if ((ret = !wine_server_call_err( req )))
538 events_written = reply->written;
542 if (written) *written = events_written;
545 SetLastError(ERROR_INVALID_ACCESS);
552 /***********************************************************************
553 * WriteConsoleOutputA (KERNEL32.@)
555 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
556 COORD size, COORD coord, LPSMALL_RECT region )
560 COORD new_size, new_coord;
563 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
564 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
566 if (new_size.X <= 0 || new_size.Y <= 0)
568 region->Bottom = region->Top + new_size.Y - 1;
569 region->Right = region->Left + new_size.X - 1;
573 /* only copy the useful rectangle */
574 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
576 for (y = 0; y < new_size.Y; y++)
578 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
579 new_size.X * sizeof(CHAR_INFO) );
580 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
582 new_coord.X = new_coord.Y = 0;
583 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
584 HeapFree( GetProcessHeap(), 0, ciw );
589 /***********************************************************************
590 * WriteConsoleOutputW (KERNEL32.@)
592 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
593 COORD size, COORD coord, LPSMALL_RECT region )
595 int width, height, y;
598 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
599 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
600 region->Left, region->Top, region->Right, region->Bottom);
602 width = min( region->Right - region->Left + 1, size.X - coord.X );
603 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
605 if (width > 0 && height > 0)
607 for (y = 0; y < height; y++)
609 SERVER_START_REQ( write_console_output )
611 req->handle = console_handle_unmap(hConsoleOutput);
612 req->x = region->Left;
613 req->y = region->Top + y;
614 req->mode = CHAR_INFO_MODE_TEXTATTR;
616 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
617 width * sizeof(CHAR_INFO));
618 if ((ret = !wine_server_call_err( req )))
620 width = min( width, reply->width - region->Left );
621 height = min( height, reply->height - region->Top );
628 region->Bottom = region->Top + height - 1;
629 region->Right = region->Left + width - 1;
634 /******************************************************************************
635 * WriteConsoleOutputCharacterA [KERNEL32.@]
637 * See WriteConsoleOutputCharacterW.
639 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
640 COORD coord, LPDWORD lpNumCharsWritten )
646 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
647 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
649 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
651 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
653 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
654 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
656 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
657 HeapFree( GetProcessHeap(), 0, strW );
662 /******************************************************************************
663 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
664 * the console screen buffer
667 * hConsoleOutput [I] Handle to screen buffer
668 * attr [I] Pointer to buffer with write attributes
669 * length [I] Number of cells to write to
670 * coord [I] Coords of first cell
671 * lpNumAttrsWritten [O] Pointer to number of cells written
678 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
679 COORD coord, LPDWORD lpNumAttrsWritten )
683 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
685 SERVER_START_REQ( write_console_output )
687 req->handle = console_handle_unmap(hConsoleOutput);
690 req->mode = CHAR_INFO_MODE_ATTR;
692 wine_server_add_data( req, attr, length * sizeof(WORD) );
693 if ((ret = !wine_server_call_err( req )))
695 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
703 /******************************************************************************
704 * FillConsoleOutputCharacterA [KERNEL32.@]
706 * See FillConsoleOutputCharacterW.
708 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
709 COORD coord, LPDWORD lpNumCharsWritten )
713 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
714 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
718 /******************************************************************************
719 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
722 * hConsoleOutput [I] Handle to screen buffer
723 * ch [I] Character to write
724 * length [I] Number of cells to write to
725 * coord [I] Coords of first cell
726 * lpNumCharsWritten [O] Pointer to number of cells written
732 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
733 COORD coord, LPDWORD lpNumCharsWritten)
737 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
738 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
740 SERVER_START_REQ( fill_console_output )
742 req->handle = console_handle_unmap(hConsoleOutput);
745 req->mode = CHAR_INFO_MODE_TEXT;
749 if ((ret = !wine_server_call_err( req )))
751 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
759 /******************************************************************************
760 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
763 * hConsoleOutput [I] Handle to screen buffer
764 * attr [I] Color attribute to write
765 * length [I] Number of cells to write to
766 * coord [I] Coords of first cell
767 * lpNumAttrsWritten [O] Pointer to number of cells written
773 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
774 COORD coord, LPDWORD lpNumAttrsWritten )
778 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
779 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
781 SERVER_START_REQ( fill_console_output )
783 req->handle = console_handle_unmap(hConsoleOutput);
786 req->mode = CHAR_INFO_MODE_ATTR;
788 req->data.attr = attr;
790 if ((ret = !wine_server_call_err( req )))
792 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
800 /******************************************************************************
801 * ReadConsoleOutputCharacterA [KERNEL32.@]
804 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
805 COORD coord, LPDWORD read_count)
809 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
811 if (read_count) *read_count = 0;
812 if (!wptr) return FALSE;
814 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
816 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
817 if (read_count) *read_count = read;
819 HeapFree( GetProcessHeap(), 0, wptr );
824 /******************************************************************************
825 * ReadConsoleOutputCharacterW [KERNEL32.@]
828 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
829 COORD coord, LPDWORD read_count )
833 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
835 SERVER_START_REQ( read_console_output )
837 req->handle = console_handle_unmap(hConsoleOutput);
840 req->mode = CHAR_INFO_MODE_TEXT;
842 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
843 if ((ret = !wine_server_call_err( req )))
845 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
853 /******************************************************************************
854 * ReadConsoleOutputAttribute [KERNEL32.@]
856 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
857 COORD coord, LPDWORD read_count)
861 TRACE("(%p,%p,%d,%dx%d,%p)\n",
862 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
864 SERVER_START_REQ( read_console_output )
866 req->handle = console_handle_unmap(hConsoleOutput);
869 req->mode = CHAR_INFO_MODE_ATTR;
871 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
872 if ((ret = !wine_server_call_err( req )))
874 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
882 /******************************************************************************
883 * ReadConsoleOutputA [KERNEL32.@]
886 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
887 COORD coord, LPSMALL_RECT region )
892 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
893 if (ret && region->Right >= region->Left)
895 for (y = 0; y <= region->Bottom - region->Top; y++)
897 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
898 region->Right - region->Left + 1 );
905 /******************************************************************************
906 * ReadConsoleOutputW [KERNEL32.@]
908 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
909 * think we need to be *that* compatible. -- AJ
911 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
912 COORD coord, LPSMALL_RECT region )
914 int width, height, y;
917 width = min( region->Right - region->Left + 1, size.X - coord.X );
918 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
920 if (width > 0 && height > 0)
922 for (y = 0; y < height; y++)
924 SERVER_START_REQ( read_console_output )
926 req->handle = console_handle_unmap(hConsoleOutput);
927 req->x = region->Left;
928 req->y = region->Top + y;
929 req->mode = CHAR_INFO_MODE_TEXTATTR;
931 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
932 width * sizeof(CHAR_INFO) );
933 if ((ret = !wine_server_call_err( req )))
935 width = min( width, reply->width - region->Left );
936 height = min( height, reply->height - region->Top );
943 region->Bottom = region->Top + height - 1;
944 region->Right = region->Left + width - 1;
949 /******************************************************************************
950 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
953 * handle [I] Handle to console input buffer
954 * buffer [O] Address of buffer for read data
955 * count [I] Number of records to read
956 * pRead [O] Address of number of records read
962 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
966 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
967 input_records_WtoA( buffer, read );
968 if (pRead) *pRead = read;
973 /***********************************************************************
974 * PeekConsoleInputA (KERNEL32.@)
976 * Gets 'count' first events (or less) from input queue.
978 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
982 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
983 input_records_WtoA( buffer, read );
984 if (pRead) *pRead = read;
989 /***********************************************************************
990 * PeekConsoleInputW (KERNEL32.@)
992 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
995 SERVER_START_REQ( read_console_input )
997 req->handle = console_handle_unmap(handle);
999 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1000 if ((ret = !wine_server_call_err( req )))
1002 if (read) *read = count ? reply->read : 0;
1010 /***********************************************************************
1011 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1013 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1016 SERVER_START_REQ( read_console_input )
1018 req->handle = console_handle_unmap(handle);
1020 if ((ret = !wine_server_call_err( req )))
1023 *nrofevents = reply->read;
1026 SetLastError(ERROR_INVALID_ACCESS);
1036 /******************************************************************************
1037 * read_console_input
1039 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1042 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1044 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1045 static const int vkkeyscan_table[256] =
1047 0,0,0,0,0,0,0,0,8,9,0,0,0,13,0,0,0,0,0,19,145,556,0,0,0,0,0,27,0,0,0,
1048 0,32,305,478,307,308,309,311,222,313,304,312,443,188,189,190,191,48,
1049 49,50,51,52,53,54,55,56,57,442,186,444,187,446,447,306,321,322,323,
1050 324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,
1051 341,342,343,344,345,346,219,220,221,310,445,192,65,66,67,68,69,70,71,
1052 72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,475,476,477,
1053 448,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1054 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1055 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1056 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,400,0,0,0,0,0,0
1059 static const int mapvkey_0[256] =
1061 0,0,0,0,0,0,0,0,14,15,0,0,0,28,0,0,42,29,56,69,58,0,0,0,0,0,0,1,0,0,
1062 0,0,57,73,81,79,71,75,72,77,80,0,0,0,55,82,83,0,11,2,3,4,5,6,7,8,9,
1063 10,0,0,0,0,0,0,0,30,48,46,32,18,33,34,35,23,36,37,38,50,49,24,25,16,
1064 19,31,20,22,47,17,45,21,44,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,55,78,0,74,
1065 0,53,59,60,61,62,63,64,65,66,67,68,87,88,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1066 0,0,0,0,0,0,69,70,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1067 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,39,13,51,12,52,53,41,0,0,0,0,0,0,0,0,0,
1068 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,43,27,40,76,96,0,0,0,0,0,0,0,0,
1069 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
1072 static inline void init_complex_char(INPUT_RECORD* ir, BOOL down, WORD vk, WORD kc, DWORD cks)
1074 ir->EventType = KEY_EVENT;
1075 ir->Event.KeyEvent.bKeyDown = down;
1076 ir->Event.KeyEvent.wRepeatCount = 1;
1077 ir->Event.KeyEvent.wVirtualScanCode = vk;
1078 ir->Event.KeyEvent.wVirtualKeyCode = kc;
1079 ir->Event.KeyEvent.dwControlKeyState = cks;
1080 ir->Event.KeyEvent.uChar.UnicodeChar = 0;
1083 /******************************************************************
1084 * handle_simple_char
1088 static BOOL handle_simple_char(HANDLE conin, unsigned real_inchar)
1093 unsigned numEvent = 0;
1094 DWORD cks = 0, written;
1097 switch (real_inchar)
1099 case 9: inchar = real_inchar;
1100 real_inchar = 27; /* so that we don't think key is ctrl- something */
1103 case 10: inchar = '\r';
1104 real_inchar = 27; /* Fixme: so that we don't think key is ctrl- something */
1106 case 127: inchar = '\b';
1109 inchar = real_inchar;
1112 if ((inchar & ~0xFF) != 0) FIXME("What a char (%u)\n", inchar);
1113 vk = vkkeyscan_table[inchar];
1115 init_complex_char(&ir[numEvent++], 1, 0x2a, 0x10, SHIFT_PRESSED);
1116 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1117 init_complex_char(&ir[numEvent++], 1, 0x1d, 0x11, LEFT_CTRL_PRESSED);
1119 init_complex_char(&ir[numEvent++], 1, 0x38, 0x12, LEFT_ALT_PRESSED);
1121 ir[numEvent].EventType = KEY_EVENT;
1122 ir[numEvent].Event.KeyEvent.bKeyDown = 1;
1123 ir[numEvent].Event.KeyEvent.wRepeatCount = 1;
1124 ir[numEvent].Event.KeyEvent.dwControlKeyState = cks;
1126 ir[numEvent].Event.KeyEvent.dwControlKeyState |= SHIFT_PRESSED;
1127 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1128 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_CTRL_PRESSED;
1130 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_ALT_PRESSED;
1131 ir[numEvent].Event.KeyEvent.wVirtualKeyCode = vk;
1132 ir[numEvent].Event.KeyEvent.wVirtualScanCode = mapvkey_0[vk & 0x00ff]; /* VirtualKeyCodes to ScanCode */
1135 MultiByteToWideChar(CP_UNIXCP, 0, &ch, 1, &ir[numEvent].Event.KeyEvent.uChar.UnicodeChar, 1);
1136 ir[numEvent + 1] = ir[numEvent];
1137 ir[numEvent + 1].Event.KeyEvent.bKeyDown = 0;
1142 init_complex_char(&ir[numEvent++], 0, 0x38, 0x12, LEFT_ALT_PRESSED);
1143 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1144 init_complex_char(&ir[numEvent++], 0, 0x1d, 0x11, 0);
1146 init_complex_char(&ir[numEvent++], 0, 0x2a, 0x10, 0);
1148 return WriteConsoleInputW(conin, ir, numEvent, &written);
1151 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1153 struct pollfd pollfd;
1155 enum read_console_input_return ret;
1158 pollfd.events = POLLIN;
1161 switch (poll(&pollfd, 1, timeout))
1164 RtlEnterCriticalSection(&CONSOLE_CritSect);
1165 switch (read(fd, &ch, 1))
1167 case 1: ret = handle_simple_char(handle, ch) ? rci_gotone : rci_error; break;
1168 /* actually another thread likely beat us to reading the char
1169 * return gotone, while not perfect, it should work in most of the cases (as the new event
1170 * should be now in the queue)
1172 case 0: ret = rci_gotone; break;
1173 default: ret = rci_error; break;
1175 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1177 case 0: return rci_timeout;
1178 default: return rci_error;
1182 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1185 enum read_console_input_return ret;
1187 if ((fd = get_console_bare_fd(handle)) != -1)
1189 put_console_into_raw_mode(fd);
1190 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1192 ret = bare_console_fetch_input(handle, fd, timeout);
1194 else ret = rci_gotone;
1196 if (ret != rci_gotone) return ret;
1200 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1202 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1206 SERVER_START_REQ( read_console_input )
1208 req->handle = console_handle_unmap(handle);
1210 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1211 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1212 else ret = rci_gotone;
1220 /***********************************************************************
1221 * FlushConsoleInputBuffer (KERNEL32.@)
1223 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1225 enum read_console_input_return last;
1228 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1230 return last == rci_timeout;
1234 /***********************************************************************
1235 * SetConsoleTitleA (KERNEL32.@)
1237 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1242 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1243 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1244 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1245 ret = SetConsoleTitleW(titleW);
1246 HeapFree(GetProcessHeap(), 0, titleW);
1251 /***********************************************************************
1252 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1254 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1256 FIXME( "stub %p\n", layoutName);
1260 /***********************************************************************
1261 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1263 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1265 FIXME( "stub %p\n", layoutName);
1269 static WCHAR input_exe[MAX_PATH + 1];
1271 /***********************************************************************
1272 * GetConsoleInputExeNameW (KERNEL32.@)
1274 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1276 TRACE("%u %p\n", buflen, buffer);
1278 RtlEnterCriticalSection(&CONSOLE_CritSect);
1279 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1280 else SetLastError(ERROR_BUFFER_OVERFLOW);
1281 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1286 /***********************************************************************
1287 * GetConsoleInputExeNameA (KERNEL32.@)
1289 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1291 TRACE("%u %p\n", buflen, buffer);
1293 RtlEnterCriticalSection(&CONSOLE_CritSect);
1294 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1295 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1296 else SetLastError(ERROR_BUFFER_OVERFLOW);
1297 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1302 /***********************************************************************
1303 * GetConsoleTitleA (KERNEL32.@)
1305 * See GetConsoleTitleW.
1307 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1309 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1313 ret = GetConsoleTitleW( ptr, size );
1316 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1317 ret = strlen(title);
1319 HeapFree(GetProcessHeap(), 0, ptr);
1324 /******************************************************************************
1325 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1328 * title [O] Address of buffer for title
1329 * size [I] Size of buffer
1332 * Success: Length of string copied
1335 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1339 SERVER_START_REQ( get_console_input_info )
1342 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1343 if (!wine_server_call_err( req ))
1345 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1354 /***********************************************************************
1355 * GetLargestConsoleWindowSize (KERNEL32.@)
1358 * This should return a COORD, but calling convention for returning
1359 * structures is different between Windows and gcc on i386.
1364 #undef GetLargestConsoleWindowSize
1365 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1373 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1376 #endif /* defined(__i386__) */
1379 /***********************************************************************
1380 * GetLargestConsoleWindowSize (KERNEL32.@)
1383 * This should return a COORD, but calling convention for returning
1384 * structures is different between Windows and gcc on i386.
1389 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1394 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1397 #endif /* defined(__i386__) */
1399 static WCHAR* S_EditString /* = NULL */;
1400 static unsigned S_EditStrPos /* = 0 */;
1402 /***********************************************************************
1403 * FreeConsole (KERNEL32.@)
1405 BOOL WINAPI FreeConsole(VOID)
1409 /* invalidate local copy of input event handle */
1410 console_wait_event = 0;
1412 SERVER_START_REQ(free_console)
1414 ret = !wine_server_call_err( req );
1420 /******************************************************************
1421 * start_console_renderer
1423 * helper for AllocConsole
1424 * starts the renderer process
1426 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1431 PROCESS_INFORMATION pi;
1433 /* FIXME: use dynamic allocation for most of the buffers below */
1434 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1435 if ((ret > -1) && (ret < sizeof(buffer)) &&
1436 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1437 NULL, NULL, si, &pi))
1443 wh[1] = pi.hProcess;
1444 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1446 CloseHandle(pi.hThread);
1447 CloseHandle(pi.hProcess);
1449 if (ret != WAIT_OBJECT_0) return FALSE;
1451 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1452 pi.dwProcessId, pi.dwThreadId);
1459 static BOOL start_console_renderer(STARTUPINFOA* si)
1463 OBJECT_ATTRIBUTES attr;
1466 attr.Length = sizeof(attr);
1467 attr.RootDirectory = 0;
1468 attr.Attributes = OBJ_INHERIT;
1469 attr.ObjectName = NULL;
1470 attr.SecurityDescriptor = NULL;
1471 attr.SecurityQualityOfService = NULL;
1473 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1474 if (!hEvent) return FALSE;
1476 /* first try environment variable */
1477 if ((p = getenv("WINECONSOLE")) != NULL)
1479 ret = start_console_renderer_helper(p, si, hEvent);
1481 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1482 "trying default access\n", p);
1485 /* then try the regular PATH */
1487 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1489 CloseHandle(hEvent);
1493 /***********************************************************************
1494 * AllocConsole (KERNEL32.@)
1496 * creates an xterm with a pty to our program
1498 BOOL WINAPI AllocConsole(void)
1500 HANDLE handle_in = INVALID_HANDLE_VALUE;
1501 HANDLE handle_out = INVALID_HANDLE_VALUE;
1502 HANDLE handle_err = INVALID_HANDLE_VALUE;
1503 STARTUPINFOA siCurrent;
1504 STARTUPINFOA siConsole;
1509 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1510 FALSE, OPEN_EXISTING );
1512 if (VerifyConsoleIoHandle(handle_in))
1514 /* we already have a console opened on this process, don't create a new one */
1515 CloseHandle(handle_in);
1519 /* invalidate local copy of input event handle */
1520 console_wait_event = 0;
1522 GetStartupInfoA(&siCurrent);
1524 memset(&siConsole, 0, sizeof(siConsole));
1525 siConsole.cb = sizeof(siConsole);
1526 /* setup a view arguments for wineconsole (it'll use them as default values) */
1527 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1529 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1530 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1531 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1533 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1535 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1536 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1538 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1540 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1541 siConsole.wShowWindow = siCurrent.wShowWindow;
1543 /* FIXME (should pass the unicode form) */
1544 if (siCurrent.lpTitle)
1545 siConsole.lpTitle = siCurrent.lpTitle;
1546 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1548 buffer[sizeof(buffer) - 1] = '\0';
1549 siConsole.lpTitle = buffer;
1552 if (!start_console_renderer(&siConsole))
1555 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1556 /* all std I/O handles are inheritable by default */
1557 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1558 TRUE, OPEN_EXISTING );
1559 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1561 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1562 TRUE, OPEN_EXISTING );
1563 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1565 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1566 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1569 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1570 handle_in = siCurrent.hStdInput;
1571 handle_out = siCurrent.hStdOutput;
1572 handle_err = siCurrent.hStdError;
1575 /* NT resets the STD_*_HANDLEs on console alloc */
1576 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1577 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1578 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1580 SetLastError(ERROR_SUCCESS);
1585 ERR("Can't allocate console\n");
1586 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1587 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1588 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1594 /***********************************************************************
1595 * ReadConsoleA (KERNEL32.@)
1597 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1598 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1600 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1604 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1605 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1607 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1608 HeapFree(GetProcessHeap(), 0, ptr);
1613 /***********************************************************************
1614 * ReadConsoleW (KERNEL32.@)
1616 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1617 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1620 LPWSTR xbuf = lpBuffer;
1622 BOOL is_bare = FALSE;
1625 TRACE("(%p,%p,%d,%p,%p)\n",
1626 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1628 if (!GetConsoleMode(hConsoleInput, &mode))
1630 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1635 if (mode & ENABLE_LINE_INPUT)
1637 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1639 HeapFree(GetProcessHeap(), 0, S_EditString);
1640 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1644 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1645 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1646 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1647 S_EditStrPos += charsread;
1652 DWORD timeout = INFINITE;
1654 /* FIXME: should we read at least 1 char? The SDK does not say */
1655 /* wait for at least one available input record (it doesn't mean we'll have
1656 * chars stored in xbuf...)
1658 * Although SDK doc keeps silence about 1 char, SDK examples assume
1659 * that we should wait for at least one character (not key). --KS
1664 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1665 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1666 ir.Event.KeyEvent.uChar.UnicodeChar)
1668 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1671 } while (charsread < nNumberOfCharsToRead);
1672 /* nothing has been read */
1673 if (timeout == INFINITE) return FALSE;
1676 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1682 /***********************************************************************
1683 * ReadConsoleInputW (KERNEL32.@)
1685 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1686 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1689 DWORD timeout = INFINITE;
1693 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1697 /* loop until we get at least one event */
1698 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1702 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1707 /******************************************************************************
1708 * WriteConsoleOutputCharacterW [KERNEL32.@]
1710 * Copy character to consecutive cells in the console screen buffer.
1713 * hConsoleOutput [I] Handle to screen buffer
1714 * str [I] Pointer to buffer with chars to write
1715 * length [I] Number of cells to write to
1716 * coord [I] Coords of first cell
1717 * lpNumCharsWritten [O] Pointer to number of cells written
1724 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1725 COORD coord, LPDWORD lpNumCharsWritten )
1729 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1730 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1732 if ((length > 0 && !str) || !lpNumCharsWritten)
1734 SetLastError(ERROR_INVALID_ACCESS);
1738 *lpNumCharsWritten = 0;
1740 SERVER_START_REQ( write_console_output )
1742 req->handle = console_handle_unmap(hConsoleOutput);
1745 req->mode = CHAR_INFO_MODE_TEXT;
1747 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1748 if ((ret = !wine_server_call_err( req )))
1749 *lpNumCharsWritten = reply->written;
1756 /******************************************************************************
1757 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1760 * title [I] Address of new title
1766 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1770 TRACE("(%s)\n", debugstr_w(title));
1771 SERVER_START_REQ( set_console_input_info )
1774 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1775 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1776 ret = !wine_server_call_err( req );
1783 /***********************************************************************
1784 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1786 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1788 FIXME("(%p): stub\n", nrofbuttons);
1793 /******************************************************************************
1794 * SetConsoleInputExeNameW [KERNEL32.@]
1796 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1798 TRACE("(%s)\n", debugstr_w(name));
1800 if (!name || !name[0])
1802 SetLastError(ERROR_INVALID_PARAMETER);
1806 RtlEnterCriticalSection(&CONSOLE_CritSect);
1807 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1808 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1813 /******************************************************************************
1814 * SetConsoleInputExeNameA [KERNEL32.@]
1816 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1822 if (!name || !name[0])
1824 SetLastError(ERROR_INVALID_PARAMETER);
1828 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1829 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1831 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1832 ret = SetConsoleInputExeNameW(nameW);
1833 HeapFree(GetProcessHeap(), 0, nameW);
1838 /******************************************************************
1839 * CONSOLE_DefaultHandler
1841 * Final control event handler
1843 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1845 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1847 /* should never go here */
1851 /******************************************************************************
1852 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1855 * func [I] Address of handler function
1856 * add [I] Handler to add or remove
1863 struct ConsoleHandler
1865 PHANDLER_ROUTINE handler;
1866 struct ConsoleHandler* next;
1869 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1870 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1872 /*****************************************************************************/
1874 /******************************************************************
1875 * SetConsoleCtrlHandler (KERNEL32.@)
1877 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1881 TRACE("(%p,%i)\n", func, add);
1885 RtlEnterCriticalSection(&CONSOLE_CritSect);
1887 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1889 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1890 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1894 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1896 if (!ch) return FALSE;
1898 RtlEnterCriticalSection(&CONSOLE_CritSect);
1899 ch->next = CONSOLE_Handlers;
1900 CONSOLE_Handlers = ch;
1901 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1905 struct ConsoleHandler** ch;
1906 RtlEnterCriticalSection(&CONSOLE_CritSect);
1907 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1909 if ((*ch)->handler == func) break;
1913 struct ConsoleHandler* rch = *ch;
1916 if (rch == &CONSOLE_DefaultConsoleHandler)
1918 ERR("Who's trying to remove default handler???\n");
1919 SetLastError(ERROR_INVALID_PARAMETER);
1925 HeapFree(GetProcessHeap(), 0, rch);
1930 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1931 SetLastError(ERROR_INVALID_PARAMETER);
1934 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1939 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1941 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1942 return EXCEPTION_EXECUTE_HANDLER;
1945 /******************************************************************
1946 * CONSOLE_SendEventThread
1948 * Internal helper to pass an event to the list on installed handlers
1950 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1952 DWORD_PTR event = (DWORD_PTR)pmt;
1953 struct ConsoleHandler* ch;
1955 if (event == CTRL_C_EVENT)
1957 BOOL caught_by_dbg = TRUE;
1958 /* First, try to pass the ctrl-C event to the debugger (if any)
1959 * If it continues, there's nothing more to do
1960 * Otherwise, we need to send the ctrl-C event to the handlers
1964 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1966 __EXCEPT(CONSOLE_CtrlEventHandler)
1968 caught_by_dbg = FALSE;
1971 if (caught_by_dbg) return 0;
1972 /* the debugger didn't continue... so, pass to ctrl handlers */
1974 RtlEnterCriticalSection(&CONSOLE_CritSect);
1975 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1977 if (ch->handler(event)) break;
1979 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1983 /******************************************************************
1984 * CONSOLE_HandleCtrlC
1986 * Check whether the shall manipulate CtrlC events
1988 int CONSOLE_HandleCtrlC(unsigned sig)
1990 /* FIXME: better test whether a console is attached to this process ??? */
1991 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1992 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1994 /* check if we have to ignore ctrl-C events */
1995 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1997 /* Create a separate thread to signal all the events.
1998 * This is needed because:
1999 * - this function can be called in an Unix signal handler (hence on an
2000 * different stack than the thread that's running). This breaks the
2001 * Win32 exception mechanisms (where the thread's stack is checked).
2002 * - since the current thread, while processing the signal, can hold the
2003 * console critical section, we need another execution environment where
2004 * we can wait on this critical section
2006 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2011 /******************************************************************************
2012 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2015 * dwCtrlEvent [I] Type of event
2016 * dwProcessGroupID [I] Process group ID to send event to
2020 * Failure: False (and *should* [but doesn't] set LastError)
2022 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2023 DWORD dwProcessGroupID)
2027 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2029 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2031 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2035 SERVER_START_REQ( send_console_signal )
2037 req->signal = dwCtrlEvent;
2038 req->group_id = dwProcessGroupID;
2039 ret = !wine_server_call_err( req );
2043 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2044 * have been handled by all processes in the given group?
2045 * As of today, we don't wait...
2051 /******************************************************************************
2052 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2055 * dwDesiredAccess [I] Access flag
2056 * dwShareMode [I] Buffer share mode
2057 * sa [I] Security attributes
2058 * dwFlags [I] Type of buffer to create
2059 * lpScreenBufferData [I] Reserved
2062 * Should call SetLastError
2065 * Success: Handle to new console screen buffer
2066 * Failure: INVALID_HANDLE_VALUE
2068 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2069 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2070 LPVOID lpScreenBufferData)
2072 HANDLE ret = INVALID_HANDLE_VALUE;
2074 TRACE("(%d,%d,%p,%d,%p)\n",
2075 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2077 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2079 SetLastError(ERROR_INVALID_PARAMETER);
2080 return INVALID_HANDLE_VALUE;
2083 SERVER_START_REQ(create_console_output)
2086 req->access = dwDesiredAccess;
2087 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2088 req->share = dwShareMode;
2090 if (!wine_server_call_err( req ))
2091 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2099 /***********************************************************************
2100 * GetConsoleScreenBufferInfo (KERNEL32.@)
2102 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2106 SERVER_START_REQ(get_console_output_info)
2108 req->handle = console_handle_unmap(hConsoleOutput);
2109 if ((ret = !wine_server_call_err( req )))
2111 csbi->dwSize.X = reply->width;
2112 csbi->dwSize.Y = reply->height;
2113 csbi->dwCursorPosition.X = reply->cursor_x;
2114 csbi->dwCursorPosition.Y = reply->cursor_y;
2115 csbi->wAttributes = reply->attr;
2116 csbi->srWindow.Left = reply->win_left;
2117 csbi->srWindow.Right = reply->win_right;
2118 csbi->srWindow.Top = reply->win_top;
2119 csbi->srWindow.Bottom = reply->win_bottom;
2120 csbi->dwMaximumWindowSize.X = reply->max_width;
2121 csbi->dwMaximumWindowSize.Y = reply->max_height;
2126 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2127 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2128 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2130 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2131 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2137 /******************************************************************************
2138 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2144 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2148 TRACE("(%p)\n", hConsoleOutput);
2150 SERVER_START_REQ( set_console_input_info )
2153 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2154 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2155 ret = !wine_server_call_err( req );
2162 /***********************************************************************
2163 * GetConsoleMode (KERNEL32.@)
2165 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2169 SERVER_START_REQ( get_console_mode )
2171 req->handle = console_handle_unmap(hcon);
2172 if ((ret = !wine_server_call_err( req )))
2174 if (mode) *mode = reply->mode;
2182 /******************************************************************************
2183 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2186 * hcon [I] Handle to console input or screen buffer
2187 * mode [I] Input or output mode to set
2194 * ENABLE_PROCESSED_INPUT 0x01
2195 * ENABLE_LINE_INPUT 0x02
2196 * ENABLE_ECHO_INPUT 0x04
2197 * ENABLE_WINDOW_INPUT 0x08
2198 * ENABLE_MOUSE_INPUT 0x10
2200 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2204 SERVER_START_REQ(set_console_mode)
2206 req->handle = console_handle_unmap(hcon);
2208 ret = !wine_server_call_err( req );
2211 /* FIXME: when resetting a console input to editline mode, I think we should
2212 * empty the S_EditString buffer
2215 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2221 /******************************************************************
2222 * CONSOLE_WriteChars
2224 * WriteConsoleOutput helper: hides server call semantics
2225 * writes a string at a given pos with standard attribute
2227 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2233 SERVER_START_REQ( write_console_output )
2235 req->handle = console_handle_unmap(hCon);
2238 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2240 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2241 if (!wine_server_call_err( req )) written = reply->written;
2245 if (written > 0) pos->X += written;
2249 /******************************************************************
2252 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2255 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2261 csbi->dwCursorPosition.X = 0;
2262 csbi->dwCursorPosition.Y++;
2264 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2267 src.Bottom = csbi->dwSize.Y - 1;
2269 src.Right = csbi->dwSize.X - 1;
2274 ci.Attributes = csbi->wAttributes;
2275 ci.Char.UnicodeChar = ' ';
2277 csbi->dwCursorPosition.Y--;
2278 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2283 /******************************************************************
2286 * WriteConsoleOutput helper: writes a block of non special characters
2287 * Block can spread on several lines, and wrapping, if needed, is
2291 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2292 DWORD mode, LPCWSTR ptr, int len)
2294 int blk; /* number of chars to write on current line */
2295 int done; /* number of chars already written */
2297 if (len <= 0) return 1;
2299 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2301 for (done = 0; done < len; done += blk)
2303 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2305 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2307 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2313 int pos = csbi->dwCursorPosition.X;
2314 /* FIXME: we could reduce the number of loops
2315 * but, in most cases we wouldn't gain lots of time (it would only
2316 * happen if we're asked to overwrite more than twice the part of the line,
2319 for (done = 0; done < len; done += blk)
2321 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2323 csbi->dwCursorPosition.X = pos;
2324 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2332 /***********************************************************************
2333 * WriteConsoleW (KERNEL32.@)
2335 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2336 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2340 const WCHAR* psz = lpBuffer;
2341 CONSOLE_SCREEN_BUFFER_INFO csbi;
2342 int k, first = 0, fd;
2344 TRACE("%p %s %d %p %p\n",
2345 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2346 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2348 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2350 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2357 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2360 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2361 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2364 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2365 ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2366 ptr, len, lpNumberOfCharsWritten, NULL);
2367 if (ret && lpNumberOfCharsWritten)
2369 if (*lpNumberOfCharsWritten == len)
2370 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2372 FIXME("Conversion not supported yet\n");
2374 HeapFree(GetProcessHeap(), 0, ptr);
2378 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2381 if (!nNumberOfCharsToWrite) return TRUE;
2383 if (mode & ENABLE_PROCESSED_OUTPUT)
2387 for (i = 0; i < nNumberOfCharsToWrite; i++)
2391 case '\b': case '\t': case '\n': case '\a': case '\r':
2392 /* don't handle here the i-th char... done below */
2393 if ((k = i - first) > 0)
2395 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2405 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2409 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2411 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2412 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2417 next_line(hConsoleOutput, &csbi);
2423 csbi.dwCursorPosition.X = 0;
2431 /* write the remaining block (if any) if processed output is enabled, or the
2432 * entire buffer otherwise
2434 if ((k = nNumberOfCharsToWrite - first) > 0)
2436 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2442 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2443 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2448 /***********************************************************************
2449 * WriteConsoleA (KERNEL32.@)
2451 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2452 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2458 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2460 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2461 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2462 if (!xstring) return 0;
2464 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2466 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2468 HeapFree(GetProcessHeap(), 0, xstring);
2473 /******************************************************************************
2474 * SetConsoleCursorPosition [KERNEL32.@]
2475 * Sets the cursor position in console
2478 * hConsoleOutput [I] Handle of console screen buffer
2479 * dwCursorPosition [I] New cursor position coordinates
2485 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2488 CONSOLE_SCREEN_BUFFER_INFO csbi;
2492 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2494 SERVER_START_REQ(set_console_output_info)
2496 req->handle = console_handle_unmap(hcon);
2497 req->cursor_x = pos.X;
2498 req->cursor_y = pos.Y;
2499 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2500 ret = !wine_server_call_err( req );
2504 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2507 /* if cursor is no longer visible, scroll the visible window... */
2508 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2509 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2510 if (pos.X < csbi.srWindow.Left)
2512 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2515 else if (pos.X > csbi.srWindow.Right)
2517 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2520 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2522 if (pos.Y < csbi.srWindow.Top)
2524 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2527 else if (pos.Y > csbi.srWindow.Bottom)
2529 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2532 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2534 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2539 /******************************************************************************
2540 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2543 * hcon [I] Handle to console screen buffer
2544 * cinfo [O] Address of cursor information
2550 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2554 SERVER_START_REQ(get_console_output_info)
2556 req->handle = console_handle_unmap(hCon);
2557 ret = !wine_server_call_err( req );
2560 cinfo->dwSize = reply->cursor_size;
2561 cinfo->bVisible = reply->cursor_visible;
2566 if (!ret) return FALSE;
2570 SetLastError(ERROR_INVALID_ACCESS);
2573 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2579 /******************************************************************************
2580 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2583 * hcon [I] Handle to console screen buffer
2584 * cinfo [I] Address of cursor information
2589 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2593 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2594 SERVER_START_REQ(set_console_output_info)
2596 req->handle = console_handle_unmap(hCon);
2597 req->cursor_size = cinfo->dwSize;
2598 req->cursor_visible = cinfo->bVisible;
2599 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2600 ret = !wine_server_call_err( req );
2607 /******************************************************************************
2608 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2611 * hcon [I] Handle to console screen buffer
2612 * bAbsolute [I] Coordinate type flag
2613 * window [I] Address of new window rectangle
2618 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2620 SMALL_RECT p = *window;
2623 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2627 CONSOLE_SCREEN_BUFFER_INFO csbi;
2629 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2631 p.Left += csbi.srWindow.Left;
2632 p.Top += csbi.srWindow.Top;
2633 p.Right += csbi.srWindow.Right;
2634 p.Bottom += csbi.srWindow.Bottom;
2636 SERVER_START_REQ(set_console_output_info)
2638 req->handle = console_handle_unmap(hCon);
2639 req->win_left = p.Left;
2640 req->win_top = p.Top;
2641 req->win_right = p.Right;
2642 req->win_bottom = p.Bottom;
2643 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2644 ret = !wine_server_call_err( req );
2652 /******************************************************************************
2653 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2655 * Sets the foreground and background color attributes of characters
2656 * written to the screen buffer.
2662 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2666 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2667 SERVER_START_REQ(set_console_output_info)
2669 req->handle = console_handle_unmap(hConsoleOutput);
2671 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2672 ret = !wine_server_call_err( req );
2679 /******************************************************************************
2680 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2683 * hConsoleOutput [I] Handle to console screen buffer
2684 * dwSize [I] New size in character rows and cols
2690 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2694 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2695 SERVER_START_REQ(set_console_output_info)
2697 req->handle = console_handle_unmap(hConsoleOutput);
2698 req->width = dwSize.X;
2699 req->height = dwSize.Y;
2700 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2701 ret = !wine_server_call_err( req );
2708 /******************************************************************************
2709 * ScrollConsoleScreenBufferA [KERNEL32.@]
2712 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2713 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2718 ciw.Attributes = lpFill->Attributes;
2719 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2721 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2722 dwDestOrigin, &ciw);
2725 /******************************************************************
2726 * CONSOLE_FillLineUniform
2728 * Helper function for ScrollConsoleScreenBufferW
2729 * Fills a part of a line with a constant character info
2731 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2733 SERVER_START_REQ( fill_console_output )
2735 req->handle = console_handle_unmap(hConsoleOutput);
2736 req->mode = CHAR_INFO_MODE_TEXTATTR;
2741 req->data.ch = lpFill->Char.UnicodeChar;
2742 req->data.attr = lpFill->Attributes;
2743 wine_server_call_err( req );
2748 /******************************************************************************
2749 * ScrollConsoleScreenBufferW [KERNEL32.@]
2753 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2754 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2762 CONSOLE_SCREEN_BUFFER_INFO csbi;
2767 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2768 lpScrollRect->Left, lpScrollRect->Top,
2769 lpScrollRect->Right, lpScrollRect->Bottom,
2770 lpClipRect->Left, lpClipRect->Top,
2771 lpClipRect->Right, lpClipRect->Bottom,
2772 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2774 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2775 lpScrollRect->Left, lpScrollRect->Top,
2776 lpScrollRect->Right, lpScrollRect->Bottom,
2777 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2779 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2782 src.X = lpScrollRect->Left;
2783 src.Y = lpScrollRect->Top;
2785 /* step 1: get dst rect */
2786 dst.Left = dwDestOrigin.X;
2787 dst.Top = dwDestOrigin.Y;
2788 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2789 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2791 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2794 clip.Left = max(0, lpClipRect->Left);
2795 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2796 clip.Top = max(0, lpClipRect->Top);
2797 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2802 clip.Right = csbi.dwSize.X - 1;
2804 clip.Bottom = csbi.dwSize.Y - 1;
2806 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2808 /* step 2b: clip dst rect */
2809 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2810 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2811 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2812 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2814 /* step 3: transfer the bits */
2815 SERVER_START_REQ(move_console_output)
2817 req->handle = console_handle_unmap(hConsoleOutput);
2820 req->x_dst = dst.Left;
2821 req->y_dst = dst.Top;
2822 req->w = dst.Right - dst.Left + 1;
2823 req->h = dst.Bottom - dst.Top + 1;
2824 ret = !wine_server_call_err( req );
2828 if (!ret) return FALSE;
2830 /* step 4: clean out the exposed part */
2832 /* have to write cell [i,j] if it is not in dst rect (because it has already
2833 * been written to by the scroll) and is in clip (we shall not write
2836 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2838 inside = dst.Top <= j && j <= dst.Bottom;
2840 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2842 if (inside && dst.Left <= i && i <= dst.Right)
2846 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2852 if (start == -1) start = i;
2856 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2862 /******************************************************************
2863 * AttachConsole (KERNEL32.@)
2865 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2867 FIXME("stub %x\n",dwProcessId);
2871 /******************************************************************
2872 * GetConsoleDisplayMode (KERNEL32.@)
2874 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2876 TRACE("semi-stub: %p\n", lpModeFlags);
2877 /* It is safe to successfully report windowed mode */
2882 /******************************************************************
2883 * SetConsoleDisplayMode (KERNEL32.@)
2885 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2886 COORD *lpNewScreenBufferDimensions)
2888 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2889 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2892 /* We cannot switch to fullscreen */
2899 /* ====================================================================
2901 * Console manipulation functions
2903 * ====================================================================*/
2905 /* some missing functions...
2906 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2907 * should get the right API and implement them
2908 * GetConsoleCommandHistory[AW] (dword dword dword)
2909 * GetConsoleCommandHistoryLength[AW]
2910 * SetConsoleCommandHistoryMode
2911 * SetConsoleNumberOfCommands[AW]
2913 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2917 SERVER_START_REQ( get_console_input_history )
2921 if (buf && buf_len > 1)
2923 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2925 if (!wine_server_call_err( req ))
2927 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2928 len = reply->total / sizeof(WCHAR) + 1;
2935 /******************************************************************
2936 * CONSOLE_AppendHistory
2940 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2942 size_t len = strlenW(ptr);
2945 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2946 if (!len) return FALSE;
2948 SERVER_START_REQ( append_console_input_history )
2951 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2952 ret = !wine_server_call_err( req );
2958 /******************************************************************
2959 * CONSOLE_GetNumHistoryEntries
2963 unsigned CONSOLE_GetNumHistoryEntries(void)
2966 SERVER_START_REQ(get_console_input_info)
2969 if (!wine_server_call_err( req )) ret = reply->history_index;
2975 /******************************************************************
2976 * CONSOLE_GetEditionMode
2980 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2982 unsigned ret = FALSE;
2983 SERVER_START_REQ(get_console_input_info)
2985 req->handle = console_handle_unmap(hConIn);
2986 if ((ret = !wine_server_call_err( req )))
2987 *mode = reply->edition_mode;
2993 /******************************************************************
2998 * 0 if an error occurred, non-zero for success
3001 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3002 DWORD TargetBufferLength, LPWSTR lpExename)
3004 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3005 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3009 /******************************************************************
3010 * GetConsoleProcessList (KERNEL32.@)
3012 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3014 FIXME("(%p,%d): stub\n", processlist, processcount);
3016 if (!processlist || processcount < 1)
3018 SetLastError(ERROR_INVALID_PARAMETER);
3025 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3027 memset(&S_termios, 0, sizeof(S_termios));
3028 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3032 /* FIXME: to be done even if program is a GUI ? */
3033 /* This is wine specific: we have no parent (we're started from unix)
3034 * so, create a simple console with bare handles
3036 wine_server_send_fd(0);
3037 SERVER_START_REQ( alloc_console )
3039 req->access = GENERIC_READ | GENERIC_WRITE;
3040 req->attributes = OBJ_INHERIT;
3041 req->pid = 0xffffffff;
3043 wine_server_call( req );
3044 conin = wine_server_ptr_handle( reply->handle_in );
3045 /* reply->event shouldn't be created by server */
3049 if (!params->hStdInput)
3050 params->hStdInput = conin;
3052 if (!params->hStdOutput)
3054 wine_server_send_fd(1);
3055 SERVER_START_REQ( create_console_output )
3057 req->handle_in = wine_server_obj_handle(conin);
3058 req->access = GENERIC_WRITE|GENERIC_READ;
3059 req->attributes = OBJ_INHERIT;
3060 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3062 wine_server_call(req);
3063 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3067 if (!params->hStdError)
3069 wine_server_send_fd(2);
3070 SERVER_START_REQ( create_console_output )
3072 req->handle_in = wine_server_obj_handle(conin);
3073 req->access = GENERIC_WRITE|GENERIC_READ;
3074 req->attributes = OBJ_INHERIT;
3075 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3077 wine_server_call(req);
3078 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3084 /* convert value from server:
3085 * + 0 => INVALID_HANDLE_VALUE
3086 * + console handle needs to be mapped
3088 if (!params->hStdInput)
3089 params->hStdInput = INVALID_HANDLE_VALUE;
3090 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3092 params->hStdInput = console_handle_map(params->hStdInput);
3093 save_console_mode(params->hStdInput);
3096 if (!params->hStdOutput)
3097 params->hStdOutput = INVALID_HANDLE_VALUE;
3098 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3099 params->hStdOutput = console_handle_map(params->hStdOutput);
3101 if (!params->hStdError)
3102 params->hStdError = INVALID_HANDLE_VALUE;
3103 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3104 params->hStdError = console_handle_map(params->hStdError);
3109 BOOL CONSOLE_Exit(void)
3111 /* the console is in raw mode, put it back in cooked mode */
3112 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));