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);
653 SetLastError( ERROR_INVALID_ACCESS );
657 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
659 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
661 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
665 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
668 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
669 HeapFree( GetProcessHeap(), 0, strW );
674 /******************************************************************************
675 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
676 * the console screen buffer
679 * hConsoleOutput [I] Handle to screen buffer
680 * attr [I] Pointer to buffer with write attributes
681 * length [I] Number of cells to write to
682 * coord [I] Coords of first cell
683 * lpNumAttrsWritten [O] Pointer to number of cells written
690 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
691 COORD coord, LPDWORD lpNumAttrsWritten )
695 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
697 if ((length > 0 && !attr) || !lpNumAttrsWritten)
699 SetLastError(ERROR_INVALID_ACCESS);
703 *lpNumAttrsWritten = 0;
705 SERVER_START_REQ( write_console_output )
707 req->handle = console_handle_unmap(hConsoleOutput);
710 req->mode = CHAR_INFO_MODE_ATTR;
712 wine_server_add_data( req, attr, length * sizeof(WORD) );
713 if ((ret = !wine_server_call_err( req )))
714 *lpNumAttrsWritten = reply->written;
721 /******************************************************************************
722 * FillConsoleOutputCharacterA [KERNEL32.@]
724 * See FillConsoleOutputCharacterW.
726 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
727 COORD coord, LPDWORD lpNumCharsWritten )
731 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
732 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
736 /******************************************************************************
737 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
740 * hConsoleOutput [I] Handle to screen buffer
741 * ch [I] Character to write
742 * length [I] Number of cells to write to
743 * coord [I] Coords of first cell
744 * lpNumCharsWritten [O] Pointer to number of cells written
750 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
751 COORD coord, LPDWORD lpNumCharsWritten)
755 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
756 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
758 if (!lpNumCharsWritten)
760 SetLastError(ERROR_INVALID_ACCESS);
764 *lpNumCharsWritten = 0;
766 SERVER_START_REQ( fill_console_output )
768 req->handle = console_handle_unmap(hConsoleOutput);
771 req->mode = CHAR_INFO_MODE_TEXT;
775 if ((ret = !wine_server_call_err( req )))
776 *lpNumCharsWritten = reply->written;
783 /******************************************************************************
784 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
787 * hConsoleOutput [I] Handle to screen buffer
788 * attr [I] Color attribute to write
789 * length [I] Number of cells to write to
790 * coord [I] Coords of first cell
791 * lpNumAttrsWritten [O] Pointer to number of cells written
797 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
798 COORD coord, LPDWORD lpNumAttrsWritten )
802 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
803 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
805 if (!lpNumAttrsWritten)
807 SetLastError(ERROR_INVALID_ACCESS);
811 *lpNumAttrsWritten = 0;
813 SERVER_START_REQ( fill_console_output )
815 req->handle = console_handle_unmap(hConsoleOutput);
818 req->mode = CHAR_INFO_MODE_ATTR;
820 req->data.attr = attr;
822 if ((ret = !wine_server_call_err( req )))
823 *lpNumAttrsWritten = reply->written;
830 /******************************************************************************
831 * ReadConsoleOutputCharacterA [KERNEL32.@]
834 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
835 COORD coord, LPDWORD read_count)
843 SetLastError(ERROR_INVALID_ACCESS);
849 if (!(wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR))))
851 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
855 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
857 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
860 HeapFree( GetProcessHeap(), 0, wptr );
865 /******************************************************************************
866 * ReadConsoleOutputCharacterW [KERNEL32.@]
869 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
870 COORD coord, LPDWORD read_count )
874 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
878 SetLastError(ERROR_INVALID_ACCESS);
884 SERVER_START_REQ( read_console_output )
886 req->handle = console_handle_unmap(hConsoleOutput);
889 req->mode = CHAR_INFO_MODE_TEXT;
891 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
892 if ((ret = !wine_server_call_err( req )))
893 *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
900 /******************************************************************************
901 * ReadConsoleOutputAttribute [KERNEL32.@]
903 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
904 COORD coord, LPDWORD read_count)
908 TRACE("(%p,%p,%d,%dx%d,%p)\n",
909 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
911 SERVER_START_REQ( read_console_output )
913 req->handle = console_handle_unmap(hConsoleOutput);
916 req->mode = CHAR_INFO_MODE_ATTR;
918 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
919 if ((ret = !wine_server_call_err( req )))
921 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
929 /******************************************************************************
930 * ReadConsoleOutputA [KERNEL32.@]
933 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
934 COORD coord, LPSMALL_RECT region )
939 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
940 if (ret && region->Right >= region->Left)
942 for (y = 0; y <= region->Bottom - region->Top; y++)
944 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
945 region->Right - region->Left + 1 );
952 /******************************************************************************
953 * ReadConsoleOutputW [KERNEL32.@]
955 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
956 * think we need to be *that* compatible. -- AJ
958 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
959 COORD coord, LPSMALL_RECT region )
961 int width, height, y;
964 width = min( region->Right - region->Left + 1, size.X - coord.X );
965 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
967 if (width > 0 && height > 0)
969 for (y = 0; y < height; y++)
971 SERVER_START_REQ( read_console_output )
973 req->handle = console_handle_unmap(hConsoleOutput);
974 req->x = region->Left;
975 req->y = region->Top + y;
976 req->mode = CHAR_INFO_MODE_TEXTATTR;
978 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
979 width * sizeof(CHAR_INFO) );
980 if ((ret = !wine_server_call_err( req )))
982 width = min( width, reply->width - region->Left );
983 height = min( height, reply->height - region->Top );
990 region->Bottom = region->Top + height - 1;
991 region->Right = region->Left + width - 1;
996 /******************************************************************************
997 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
1000 * handle [I] Handle to console input buffer
1001 * buffer [O] Address of buffer for read data
1002 * count [I] Number of records to read
1003 * pRead [O] Address of number of records read
1009 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1013 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
1014 input_records_WtoA( buffer, read );
1015 if (pRead) *pRead = read;
1020 /***********************************************************************
1021 * PeekConsoleInputA (KERNEL32.@)
1023 * Gets 'count' first events (or less) from input queue.
1025 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1029 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
1030 input_records_WtoA( buffer, read );
1031 if (pRead) *pRead = read;
1036 /***********************************************************************
1037 * PeekConsoleInputW (KERNEL32.@)
1039 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
1042 SERVER_START_REQ( read_console_input )
1044 req->handle = console_handle_unmap(handle);
1046 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1047 if ((ret = !wine_server_call_err( req )))
1049 if (read) *read = count ? reply->read : 0;
1057 /***********************************************************************
1058 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1060 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1063 SERVER_START_REQ( read_console_input )
1065 req->handle = console_handle_unmap(handle);
1067 if ((ret = !wine_server_call_err( req )))
1070 *nrofevents = reply->read;
1073 SetLastError(ERROR_INVALID_ACCESS);
1083 /******************************************************************************
1084 * read_console_input
1086 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1089 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1091 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1092 static const int vkkeyscan_table[256] =
1094 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,
1095 0,32,305,478,307,308,309,311,222,313,304,312,443,188,189,190,191,48,
1096 49,50,51,52,53,54,55,56,57,442,186,444,187,446,447,306,321,322,323,
1097 324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,
1098 341,342,343,344,345,346,219,220,221,310,445,192,65,66,67,68,69,70,71,
1099 72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,475,476,477,
1100 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,
1101 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,
1102 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,
1103 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
1106 static const int mapvkey_0[256] =
1108 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,
1109 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,
1110 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,
1111 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,
1112 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,
1113 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,
1114 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,
1115 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,
1116 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
1119 static inline void init_complex_char(INPUT_RECORD* ir, BOOL down, WORD vk, WORD kc, DWORD cks)
1121 ir->EventType = KEY_EVENT;
1122 ir->Event.KeyEvent.bKeyDown = down;
1123 ir->Event.KeyEvent.wRepeatCount = 1;
1124 ir->Event.KeyEvent.wVirtualScanCode = vk;
1125 ir->Event.KeyEvent.wVirtualKeyCode = kc;
1126 ir->Event.KeyEvent.dwControlKeyState = cks;
1127 ir->Event.KeyEvent.uChar.UnicodeChar = 0;
1130 /******************************************************************
1131 * handle_simple_char
1135 static BOOL handle_simple_char(HANDLE conin, unsigned real_inchar)
1140 unsigned numEvent = 0;
1141 DWORD cks = 0, written;
1144 switch (real_inchar)
1146 case 9: inchar = real_inchar;
1147 real_inchar = 27; /* so that we don't think key is ctrl- something */
1150 case 10: inchar = '\r';
1151 real_inchar = 27; /* Fixme: so that we don't think key is ctrl- something */
1153 case 127: inchar = '\b';
1156 inchar = real_inchar;
1159 if ((inchar & ~0xFF) != 0) FIXME("What a char (%u)\n", inchar);
1160 vk = vkkeyscan_table[inchar];
1162 init_complex_char(&ir[numEvent++], 1, 0x2a, 0x10, SHIFT_PRESSED);
1163 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1164 init_complex_char(&ir[numEvent++], 1, 0x1d, 0x11, LEFT_CTRL_PRESSED);
1166 init_complex_char(&ir[numEvent++], 1, 0x38, 0x12, LEFT_ALT_PRESSED);
1168 ir[numEvent].EventType = KEY_EVENT;
1169 ir[numEvent].Event.KeyEvent.bKeyDown = 1;
1170 ir[numEvent].Event.KeyEvent.wRepeatCount = 1;
1171 ir[numEvent].Event.KeyEvent.dwControlKeyState = cks;
1173 ir[numEvent].Event.KeyEvent.dwControlKeyState |= SHIFT_PRESSED;
1174 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1175 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_CTRL_PRESSED;
1177 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_ALT_PRESSED;
1178 ir[numEvent].Event.KeyEvent.wVirtualKeyCode = vk;
1179 ir[numEvent].Event.KeyEvent.wVirtualScanCode = mapvkey_0[vk & 0x00ff]; /* VirtualKeyCodes to ScanCode */
1182 MultiByteToWideChar(CP_UNIXCP, 0, &ch, 1, &ir[numEvent].Event.KeyEvent.uChar.UnicodeChar, 1);
1183 ir[numEvent + 1] = ir[numEvent];
1184 ir[numEvent + 1].Event.KeyEvent.bKeyDown = 0;
1189 init_complex_char(&ir[numEvent++], 0, 0x38, 0x12, LEFT_ALT_PRESSED);
1190 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1191 init_complex_char(&ir[numEvent++], 0, 0x1d, 0x11, 0);
1193 init_complex_char(&ir[numEvent++], 0, 0x2a, 0x10, 0);
1195 return WriteConsoleInputW(conin, ir, numEvent, &written);
1198 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1200 struct pollfd pollfd;
1202 enum read_console_input_return ret;
1205 pollfd.events = POLLIN;
1208 switch (poll(&pollfd, 1, timeout))
1211 RtlEnterCriticalSection(&CONSOLE_CritSect);
1212 switch (read(fd, &ch, 1))
1214 case 1: ret = handle_simple_char(handle, ch) ? rci_gotone : rci_error; break;
1215 /* actually another thread likely beat us to reading the char
1216 * return gotone, while not perfect, it should work in most of the cases (as the new event
1217 * should be now in the queue)
1219 case 0: ret = rci_gotone; break;
1220 default: ret = rci_error; break;
1222 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1224 case 0: return rci_timeout;
1225 default: return rci_error;
1229 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1232 enum read_console_input_return ret;
1234 if ((fd = get_console_bare_fd(handle)) != -1)
1236 put_console_into_raw_mode(fd);
1237 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1239 ret = bare_console_fetch_input(handle, fd, timeout);
1241 else ret = rci_gotone;
1243 if (ret != rci_gotone) return ret;
1247 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1249 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1253 SERVER_START_REQ( read_console_input )
1255 req->handle = console_handle_unmap(handle);
1257 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1258 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1259 else ret = rci_gotone;
1267 /***********************************************************************
1268 * FlushConsoleInputBuffer (KERNEL32.@)
1270 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1272 enum read_console_input_return last;
1275 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1277 return last == rci_timeout;
1281 /***********************************************************************
1282 * SetConsoleTitleA (KERNEL32.@)
1284 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1289 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1290 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1291 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1292 ret = SetConsoleTitleW(titleW);
1293 HeapFree(GetProcessHeap(), 0, titleW);
1298 /***********************************************************************
1299 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1301 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1303 FIXME( "stub %p\n", layoutName);
1307 /***********************************************************************
1308 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1310 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1312 FIXME( "stub %p\n", layoutName);
1316 static WCHAR input_exe[MAX_PATH + 1];
1318 /***********************************************************************
1319 * GetConsoleInputExeNameW (KERNEL32.@)
1321 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1323 TRACE("%u %p\n", buflen, buffer);
1325 RtlEnterCriticalSection(&CONSOLE_CritSect);
1326 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1327 else SetLastError(ERROR_BUFFER_OVERFLOW);
1328 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1333 /***********************************************************************
1334 * GetConsoleInputExeNameA (KERNEL32.@)
1336 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1338 TRACE("%u %p\n", buflen, buffer);
1340 RtlEnterCriticalSection(&CONSOLE_CritSect);
1341 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1342 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1343 else SetLastError(ERROR_BUFFER_OVERFLOW);
1344 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1349 /***********************************************************************
1350 * GetConsoleTitleA (KERNEL32.@)
1352 * See GetConsoleTitleW.
1354 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1356 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1360 ret = GetConsoleTitleW( ptr, size );
1363 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1364 ret = strlen(title);
1366 HeapFree(GetProcessHeap(), 0, ptr);
1371 /******************************************************************************
1372 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1375 * title [O] Address of buffer for title
1376 * size [I] Size of buffer
1379 * Success: Length of string copied
1382 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1386 SERVER_START_REQ( get_console_input_info )
1389 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1390 if (!wine_server_call_err( req ))
1392 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1401 /***********************************************************************
1402 * GetLargestConsoleWindowSize (KERNEL32.@)
1405 * This should return a COORD, but calling convention for returning
1406 * structures is different between Windows and gcc on i386.
1411 #undef GetLargestConsoleWindowSize
1412 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1420 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1423 #endif /* defined(__i386__) */
1426 /***********************************************************************
1427 * GetLargestConsoleWindowSize (KERNEL32.@)
1430 * This should return a COORD, but calling convention for returning
1431 * structures is different between Windows and gcc on i386.
1436 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1441 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1444 #endif /* defined(__i386__) */
1446 static WCHAR* S_EditString /* = NULL */;
1447 static unsigned S_EditStrPos /* = 0 */;
1449 /***********************************************************************
1450 * FreeConsole (KERNEL32.@)
1452 BOOL WINAPI FreeConsole(VOID)
1456 /* invalidate local copy of input event handle */
1457 console_wait_event = 0;
1459 SERVER_START_REQ(free_console)
1461 ret = !wine_server_call_err( req );
1467 /******************************************************************
1468 * start_console_renderer
1470 * helper for AllocConsole
1471 * starts the renderer process
1473 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1478 PROCESS_INFORMATION pi;
1480 /* FIXME: use dynamic allocation for most of the buffers below */
1481 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1482 if ((ret > -1) && (ret < sizeof(buffer)) &&
1483 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1484 NULL, NULL, si, &pi))
1490 wh[1] = pi.hProcess;
1491 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1493 CloseHandle(pi.hThread);
1494 CloseHandle(pi.hProcess);
1496 if (ret != WAIT_OBJECT_0) return FALSE;
1498 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1499 pi.dwProcessId, pi.dwThreadId);
1506 static BOOL start_console_renderer(STARTUPINFOA* si)
1510 OBJECT_ATTRIBUTES attr;
1513 attr.Length = sizeof(attr);
1514 attr.RootDirectory = 0;
1515 attr.Attributes = OBJ_INHERIT;
1516 attr.ObjectName = NULL;
1517 attr.SecurityDescriptor = NULL;
1518 attr.SecurityQualityOfService = NULL;
1520 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1521 if (!hEvent) return FALSE;
1523 /* first try environment variable */
1524 if ((p = getenv("WINECONSOLE")) != NULL)
1526 ret = start_console_renderer_helper(p, si, hEvent);
1528 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1529 "trying default access\n", p);
1532 /* then try the regular PATH */
1534 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1536 CloseHandle(hEvent);
1540 /***********************************************************************
1541 * AllocConsole (KERNEL32.@)
1543 * creates an xterm with a pty to our program
1545 BOOL WINAPI AllocConsole(void)
1547 HANDLE handle_in = INVALID_HANDLE_VALUE;
1548 HANDLE handle_out = INVALID_HANDLE_VALUE;
1549 HANDLE handle_err = INVALID_HANDLE_VALUE;
1550 STARTUPINFOA siCurrent;
1551 STARTUPINFOA siConsole;
1556 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1557 FALSE, OPEN_EXISTING );
1559 if (VerifyConsoleIoHandle(handle_in))
1561 /* we already have a console opened on this process, don't create a new one */
1562 CloseHandle(handle_in);
1566 /* invalidate local copy of input event handle */
1567 console_wait_event = 0;
1569 GetStartupInfoA(&siCurrent);
1571 memset(&siConsole, 0, sizeof(siConsole));
1572 siConsole.cb = sizeof(siConsole);
1573 /* setup a view arguments for wineconsole (it'll use them as default values) */
1574 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1576 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1577 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1578 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1580 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1582 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1583 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1585 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1587 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1588 siConsole.wShowWindow = siCurrent.wShowWindow;
1590 /* FIXME (should pass the unicode form) */
1591 if (siCurrent.lpTitle)
1592 siConsole.lpTitle = siCurrent.lpTitle;
1593 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1595 buffer[sizeof(buffer) - 1] = '\0';
1596 siConsole.lpTitle = buffer;
1599 if (!start_console_renderer(&siConsole))
1602 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1603 /* all std I/O handles are inheritable by default */
1604 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1605 TRUE, OPEN_EXISTING );
1606 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1608 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1609 TRUE, OPEN_EXISTING );
1610 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1612 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1613 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1616 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1617 handle_in = siCurrent.hStdInput;
1618 handle_out = siCurrent.hStdOutput;
1619 handle_err = siCurrent.hStdError;
1622 /* NT resets the STD_*_HANDLEs on console alloc */
1623 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1624 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1625 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1627 SetLastError(ERROR_SUCCESS);
1632 ERR("Can't allocate console\n");
1633 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1634 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1635 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1641 /***********************************************************************
1642 * ReadConsoleA (KERNEL32.@)
1644 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1645 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1647 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1651 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1652 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1654 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1655 HeapFree(GetProcessHeap(), 0, ptr);
1660 /***********************************************************************
1661 * ReadConsoleW (KERNEL32.@)
1663 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1664 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1667 LPWSTR xbuf = lpBuffer;
1669 BOOL is_bare = FALSE;
1672 TRACE("(%p,%p,%d,%p,%p)\n",
1673 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1675 if (!GetConsoleMode(hConsoleInput, &mode))
1677 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1682 if (mode & ENABLE_LINE_INPUT)
1684 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1686 HeapFree(GetProcessHeap(), 0, S_EditString);
1687 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1691 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1692 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1693 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1694 S_EditStrPos += charsread;
1699 DWORD timeout = INFINITE;
1701 /* FIXME: should we read at least 1 char? The SDK does not say */
1702 /* wait for at least one available input record (it doesn't mean we'll have
1703 * chars stored in xbuf...)
1705 * Although SDK doc keeps silence about 1 char, SDK examples assume
1706 * that we should wait for at least one character (not key). --KS
1711 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1712 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1713 ir.Event.KeyEvent.uChar.UnicodeChar)
1715 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1718 } while (charsread < nNumberOfCharsToRead);
1719 /* nothing has been read */
1720 if (timeout == INFINITE) return FALSE;
1723 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1729 /***********************************************************************
1730 * ReadConsoleInputW (KERNEL32.@)
1732 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1733 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1736 DWORD timeout = INFINITE;
1740 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1744 /* loop until we get at least one event */
1745 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1749 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1754 /******************************************************************************
1755 * WriteConsoleOutputCharacterW [KERNEL32.@]
1757 * Copy character to consecutive cells in the console screen buffer.
1760 * hConsoleOutput [I] Handle to screen buffer
1761 * str [I] Pointer to buffer with chars to write
1762 * length [I] Number of cells to write to
1763 * coord [I] Coords of first cell
1764 * lpNumCharsWritten [O] Pointer to number of cells written
1771 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1772 COORD coord, LPDWORD lpNumCharsWritten )
1776 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1777 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1779 if ((length > 0 && !str) || !lpNumCharsWritten)
1781 SetLastError(ERROR_INVALID_ACCESS);
1785 *lpNumCharsWritten = 0;
1787 SERVER_START_REQ( write_console_output )
1789 req->handle = console_handle_unmap(hConsoleOutput);
1792 req->mode = CHAR_INFO_MODE_TEXT;
1794 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1795 if ((ret = !wine_server_call_err( req )))
1796 *lpNumCharsWritten = reply->written;
1803 /******************************************************************************
1804 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1807 * title [I] Address of new title
1813 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1817 TRACE("(%s)\n", debugstr_w(title));
1818 SERVER_START_REQ( set_console_input_info )
1821 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1822 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1823 ret = !wine_server_call_err( req );
1830 /***********************************************************************
1831 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1833 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1835 FIXME("(%p): stub\n", nrofbuttons);
1840 /******************************************************************************
1841 * SetConsoleInputExeNameW [KERNEL32.@]
1843 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1845 TRACE("(%s)\n", debugstr_w(name));
1847 if (!name || !name[0])
1849 SetLastError(ERROR_INVALID_PARAMETER);
1853 RtlEnterCriticalSection(&CONSOLE_CritSect);
1854 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1855 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1860 /******************************************************************************
1861 * SetConsoleInputExeNameA [KERNEL32.@]
1863 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1869 if (!name || !name[0])
1871 SetLastError(ERROR_INVALID_PARAMETER);
1875 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1876 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1878 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1879 ret = SetConsoleInputExeNameW(nameW);
1880 HeapFree(GetProcessHeap(), 0, nameW);
1885 /******************************************************************
1886 * CONSOLE_DefaultHandler
1888 * Final control event handler
1890 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1892 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1894 /* should never go here */
1898 /******************************************************************************
1899 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1902 * func [I] Address of handler function
1903 * add [I] Handler to add or remove
1910 struct ConsoleHandler
1912 PHANDLER_ROUTINE handler;
1913 struct ConsoleHandler* next;
1916 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1917 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1919 /*****************************************************************************/
1921 /******************************************************************
1922 * SetConsoleCtrlHandler (KERNEL32.@)
1924 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1928 TRACE("(%p,%i)\n", func, add);
1932 RtlEnterCriticalSection(&CONSOLE_CritSect);
1934 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1936 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1937 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1941 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1943 if (!ch) return FALSE;
1945 RtlEnterCriticalSection(&CONSOLE_CritSect);
1946 ch->next = CONSOLE_Handlers;
1947 CONSOLE_Handlers = ch;
1948 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1952 struct ConsoleHandler** ch;
1953 RtlEnterCriticalSection(&CONSOLE_CritSect);
1954 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1956 if ((*ch)->handler == func) break;
1960 struct ConsoleHandler* rch = *ch;
1963 if (rch == &CONSOLE_DefaultConsoleHandler)
1965 ERR("Who's trying to remove default handler???\n");
1966 SetLastError(ERROR_INVALID_PARAMETER);
1972 HeapFree(GetProcessHeap(), 0, rch);
1977 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1978 SetLastError(ERROR_INVALID_PARAMETER);
1981 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1986 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1988 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1989 return EXCEPTION_EXECUTE_HANDLER;
1992 /******************************************************************
1993 * CONSOLE_SendEventThread
1995 * Internal helper to pass an event to the list on installed handlers
1997 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1999 DWORD_PTR event = (DWORD_PTR)pmt;
2000 struct ConsoleHandler* ch;
2002 if (event == CTRL_C_EVENT)
2004 BOOL caught_by_dbg = TRUE;
2005 /* First, try to pass the ctrl-C event to the debugger (if any)
2006 * If it continues, there's nothing more to do
2007 * Otherwise, we need to send the ctrl-C event to the handlers
2011 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
2013 __EXCEPT(CONSOLE_CtrlEventHandler)
2015 caught_by_dbg = FALSE;
2018 if (caught_by_dbg) return 0;
2019 /* the debugger didn't continue... so, pass to ctrl handlers */
2021 RtlEnterCriticalSection(&CONSOLE_CritSect);
2022 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
2024 if (ch->handler(event)) break;
2026 RtlLeaveCriticalSection(&CONSOLE_CritSect);
2030 /******************************************************************
2031 * CONSOLE_HandleCtrlC
2033 * Check whether the shall manipulate CtrlC events
2035 int CONSOLE_HandleCtrlC(unsigned sig)
2037 /* FIXME: better test whether a console is attached to this process ??? */
2038 extern unsigned CONSOLE_GetNumHistoryEntries(void);
2039 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
2041 /* check if we have to ignore ctrl-C events */
2042 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
2044 /* Create a separate thread to signal all the events.
2045 * This is needed because:
2046 * - this function can be called in an Unix signal handler (hence on an
2047 * different stack than the thread that's running). This breaks the
2048 * Win32 exception mechanisms (where the thread's stack is checked).
2049 * - since the current thread, while processing the signal, can hold the
2050 * console critical section, we need another execution environment where
2051 * we can wait on this critical section
2053 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2058 /******************************************************************************
2059 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2062 * dwCtrlEvent [I] Type of event
2063 * dwProcessGroupID [I] Process group ID to send event to
2067 * Failure: False (and *should* [but doesn't] set LastError)
2069 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2070 DWORD dwProcessGroupID)
2074 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2076 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2078 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2082 SERVER_START_REQ( send_console_signal )
2084 req->signal = dwCtrlEvent;
2085 req->group_id = dwProcessGroupID;
2086 ret = !wine_server_call_err( req );
2090 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2091 * have been handled by all processes in the given group?
2092 * As of today, we don't wait...
2098 /******************************************************************************
2099 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2102 * dwDesiredAccess [I] Access flag
2103 * dwShareMode [I] Buffer share mode
2104 * sa [I] Security attributes
2105 * dwFlags [I] Type of buffer to create
2106 * lpScreenBufferData [I] Reserved
2109 * Should call SetLastError
2112 * Success: Handle to new console screen buffer
2113 * Failure: INVALID_HANDLE_VALUE
2115 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2116 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2117 LPVOID lpScreenBufferData)
2119 HANDLE ret = INVALID_HANDLE_VALUE;
2121 TRACE("(%d,%d,%p,%d,%p)\n",
2122 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2124 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2126 SetLastError(ERROR_INVALID_PARAMETER);
2127 return INVALID_HANDLE_VALUE;
2130 SERVER_START_REQ(create_console_output)
2133 req->access = dwDesiredAccess;
2134 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2135 req->share = dwShareMode;
2137 if (!wine_server_call_err( req ))
2138 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2146 /***********************************************************************
2147 * GetConsoleScreenBufferInfo (KERNEL32.@)
2149 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2153 SERVER_START_REQ(get_console_output_info)
2155 req->handle = console_handle_unmap(hConsoleOutput);
2156 if ((ret = !wine_server_call_err( req )))
2158 csbi->dwSize.X = reply->width;
2159 csbi->dwSize.Y = reply->height;
2160 csbi->dwCursorPosition.X = reply->cursor_x;
2161 csbi->dwCursorPosition.Y = reply->cursor_y;
2162 csbi->wAttributes = reply->attr;
2163 csbi->srWindow.Left = reply->win_left;
2164 csbi->srWindow.Right = reply->win_right;
2165 csbi->srWindow.Top = reply->win_top;
2166 csbi->srWindow.Bottom = reply->win_bottom;
2167 csbi->dwMaximumWindowSize.X = reply->max_width;
2168 csbi->dwMaximumWindowSize.Y = reply->max_height;
2173 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2174 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2175 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2177 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2178 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2184 /******************************************************************************
2185 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2191 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2195 TRACE("(%p)\n", hConsoleOutput);
2197 SERVER_START_REQ( set_console_input_info )
2200 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2201 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2202 ret = !wine_server_call_err( req );
2209 /***********************************************************************
2210 * GetConsoleMode (KERNEL32.@)
2212 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2216 SERVER_START_REQ( get_console_mode )
2218 req->handle = console_handle_unmap(hcon);
2219 if ((ret = !wine_server_call_err( req )))
2221 if (mode) *mode = reply->mode;
2229 /******************************************************************************
2230 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2233 * hcon [I] Handle to console input or screen buffer
2234 * mode [I] Input or output mode to set
2241 * ENABLE_PROCESSED_INPUT 0x01
2242 * ENABLE_LINE_INPUT 0x02
2243 * ENABLE_ECHO_INPUT 0x04
2244 * ENABLE_WINDOW_INPUT 0x08
2245 * ENABLE_MOUSE_INPUT 0x10
2247 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2251 SERVER_START_REQ(set_console_mode)
2253 req->handle = console_handle_unmap(hcon);
2255 ret = !wine_server_call_err( req );
2258 /* FIXME: when resetting a console input to editline mode, I think we should
2259 * empty the S_EditString buffer
2262 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2268 /******************************************************************
2269 * CONSOLE_WriteChars
2271 * WriteConsoleOutput helper: hides server call semantics
2272 * writes a string at a given pos with standard attribute
2274 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2280 SERVER_START_REQ( write_console_output )
2282 req->handle = console_handle_unmap(hCon);
2285 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2287 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2288 if (!wine_server_call_err( req )) written = reply->written;
2292 if (written > 0) pos->X += written;
2296 /******************************************************************
2299 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2302 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2308 csbi->dwCursorPosition.X = 0;
2309 csbi->dwCursorPosition.Y++;
2311 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2314 src.Bottom = csbi->dwSize.Y - 1;
2316 src.Right = csbi->dwSize.X - 1;
2321 ci.Attributes = csbi->wAttributes;
2322 ci.Char.UnicodeChar = ' ';
2324 csbi->dwCursorPosition.Y--;
2325 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2330 /******************************************************************
2333 * WriteConsoleOutput helper: writes a block of non special characters
2334 * Block can spread on several lines, and wrapping, if needed, is
2338 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2339 DWORD mode, LPCWSTR ptr, int len)
2341 int blk; /* number of chars to write on current line */
2342 int done; /* number of chars already written */
2344 if (len <= 0) return 1;
2346 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2348 for (done = 0; done < len; done += blk)
2350 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2352 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2354 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2360 int pos = csbi->dwCursorPosition.X;
2361 /* FIXME: we could reduce the number of loops
2362 * but, in most cases we wouldn't gain lots of time (it would only
2363 * happen if we're asked to overwrite more than twice the part of the line,
2366 for (done = 0; done < len; done += blk)
2368 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2370 csbi->dwCursorPosition.X = pos;
2371 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2379 /***********************************************************************
2380 * WriteConsoleW (KERNEL32.@)
2382 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2383 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2387 const WCHAR* psz = lpBuffer;
2388 CONSOLE_SCREEN_BUFFER_INFO csbi;
2389 int k, first = 0, fd;
2391 TRACE("%p %s %d %p %p\n",
2392 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2393 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2395 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2397 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2404 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2407 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2408 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2411 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2412 ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2413 ptr, len, lpNumberOfCharsWritten, NULL);
2414 if (ret && lpNumberOfCharsWritten)
2416 if (*lpNumberOfCharsWritten == len)
2417 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2419 FIXME("Conversion not supported yet\n");
2421 HeapFree(GetProcessHeap(), 0, ptr);
2425 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2428 if (!nNumberOfCharsToWrite) return TRUE;
2430 if (mode & ENABLE_PROCESSED_OUTPUT)
2434 for (i = 0; i < nNumberOfCharsToWrite; i++)
2438 case '\b': case '\t': case '\n': case '\a': case '\r':
2439 /* don't handle here the i-th char... done below */
2440 if ((k = i - first) > 0)
2442 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2452 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2456 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2458 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2459 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2464 next_line(hConsoleOutput, &csbi);
2470 csbi.dwCursorPosition.X = 0;
2478 /* write the remaining block (if any) if processed output is enabled, or the
2479 * entire buffer otherwise
2481 if ((k = nNumberOfCharsToWrite - first) > 0)
2483 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2489 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2490 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2495 /***********************************************************************
2496 * WriteConsoleA (KERNEL32.@)
2498 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2499 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2505 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2507 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2508 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2509 if (!xstring) return 0;
2511 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2513 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2515 HeapFree(GetProcessHeap(), 0, xstring);
2520 /******************************************************************************
2521 * SetConsoleCursorPosition [KERNEL32.@]
2522 * Sets the cursor position in console
2525 * hConsoleOutput [I] Handle of console screen buffer
2526 * dwCursorPosition [I] New cursor position coordinates
2532 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2535 CONSOLE_SCREEN_BUFFER_INFO csbi;
2539 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2541 SERVER_START_REQ(set_console_output_info)
2543 req->handle = console_handle_unmap(hcon);
2544 req->cursor_x = pos.X;
2545 req->cursor_y = pos.Y;
2546 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2547 ret = !wine_server_call_err( req );
2551 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2554 /* if cursor is no longer visible, scroll the visible window... */
2555 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2556 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2557 if (pos.X < csbi.srWindow.Left)
2559 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2562 else if (pos.X > csbi.srWindow.Right)
2564 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2567 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2569 if (pos.Y < csbi.srWindow.Top)
2571 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2574 else if (pos.Y > csbi.srWindow.Bottom)
2576 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2579 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2581 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2586 /******************************************************************************
2587 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2590 * hcon [I] Handle to console screen buffer
2591 * cinfo [O] Address of cursor information
2597 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2601 SERVER_START_REQ(get_console_output_info)
2603 req->handle = console_handle_unmap(hCon);
2604 ret = !wine_server_call_err( req );
2607 cinfo->dwSize = reply->cursor_size;
2608 cinfo->bVisible = reply->cursor_visible;
2613 if (!ret) return FALSE;
2617 SetLastError(ERROR_INVALID_ACCESS);
2620 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2626 /******************************************************************************
2627 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2630 * hcon [I] Handle to console screen buffer
2631 * cinfo [I] Address of cursor information
2636 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2640 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2641 SERVER_START_REQ(set_console_output_info)
2643 req->handle = console_handle_unmap(hCon);
2644 req->cursor_size = cinfo->dwSize;
2645 req->cursor_visible = cinfo->bVisible;
2646 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2647 ret = !wine_server_call_err( req );
2654 /******************************************************************************
2655 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2658 * hcon [I] Handle to console screen buffer
2659 * bAbsolute [I] Coordinate type flag
2660 * window [I] Address of new window rectangle
2665 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2667 SMALL_RECT p = *window;
2670 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2674 CONSOLE_SCREEN_BUFFER_INFO csbi;
2676 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2678 p.Left += csbi.srWindow.Left;
2679 p.Top += csbi.srWindow.Top;
2680 p.Right += csbi.srWindow.Right;
2681 p.Bottom += csbi.srWindow.Bottom;
2683 SERVER_START_REQ(set_console_output_info)
2685 req->handle = console_handle_unmap(hCon);
2686 req->win_left = p.Left;
2687 req->win_top = p.Top;
2688 req->win_right = p.Right;
2689 req->win_bottom = p.Bottom;
2690 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2691 ret = !wine_server_call_err( req );
2699 /******************************************************************************
2700 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2702 * Sets the foreground and background color attributes of characters
2703 * written to the screen buffer.
2709 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2713 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2714 SERVER_START_REQ(set_console_output_info)
2716 req->handle = console_handle_unmap(hConsoleOutput);
2718 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2719 ret = !wine_server_call_err( req );
2726 /******************************************************************************
2727 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2730 * hConsoleOutput [I] Handle to console screen buffer
2731 * dwSize [I] New size in character rows and cols
2737 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2741 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2742 SERVER_START_REQ(set_console_output_info)
2744 req->handle = console_handle_unmap(hConsoleOutput);
2745 req->width = dwSize.X;
2746 req->height = dwSize.Y;
2747 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2748 ret = !wine_server_call_err( req );
2755 /******************************************************************************
2756 * ScrollConsoleScreenBufferA [KERNEL32.@]
2759 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2760 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2765 ciw.Attributes = lpFill->Attributes;
2766 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2768 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2769 dwDestOrigin, &ciw);
2772 /******************************************************************
2773 * CONSOLE_FillLineUniform
2775 * Helper function for ScrollConsoleScreenBufferW
2776 * Fills a part of a line with a constant character info
2778 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2780 SERVER_START_REQ( fill_console_output )
2782 req->handle = console_handle_unmap(hConsoleOutput);
2783 req->mode = CHAR_INFO_MODE_TEXTATTR;
2788 req->data.ch = lpFill->Char.UnicodeChar;
2789 req->data.attr = lpFill->Attributes;
2790 wine_server_call_err( req );
2795 /******************************************************************************
2796 * ScrollConsoleScreenBufferW [KERNEL32.@]
2800 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2801 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2809 CONSOLE_SCREEN_BUFFER_INFO csbi;
2814 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2815 lpScrollRect->Left, lpScrollRect->Top,
2816 lpScrollRect->Right, lpScrollRect->Bottom,
2817 lpClipRect->Left, lpClipRect->Top,
2818 lpClipRect->Right, lpClipRect->Bottom,
2819 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2821 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2822 lpScrollRect->Left, lpScrollRect->Top,
2823 lpScrollRect->Right, lpScrollRect->Bottom,
2824 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2826 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2829 src.X = lpScrollRect->Left;
2830 src.Y = lpScrollRect->Top;
2832 /* step 1: get dst rect */
2833 dst.Left = dwDestOrigin.X;
2834 dst.Top = dwDestOrigin.Y;
2835 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2836 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2838 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2841 clip.Left = max(0, lpClipRect->Left);
2842 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2843 clip.Top = max(0, lpClipRect->Top);
2844 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2849 clip.Right = csbi.dwSize.X - 1;
2851 clip.Bottom = csbi.dwSize.Y - 1;
2853 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2855 /* step 2b: clip dst rect */
2856 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2857 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2858 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2859 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2861 /* step 3: transfer the bits */
2862 SERVER_START_REQ(move_console_output)
2864 req->handle = console_handle_unmap(hConsoleOutput);
2867 req->x_dst = dst.Left;
2868 req->y_dst = dst.Top;
2869 req->w = dst.Right - dst.Left + 1;
2870 req->h = dst.Bottom - dst.Top + 1;
2871 ret = !wine_server_call_err( req );
2875 if (!ret) return FALSE;
2877 /* step 4: clean out the exposed part */
2879 /* have to write cell [i,j] if it is not in dst rect (because it has already
2880 * been written to by the scroll) and is in clip (we shall not write
2883 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2885 inside = dst.Top <= j && j <= dst.Bottom;
2887 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2889 if (inside && dst.Left <= i && i <= dst.Right)
2893 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2899 if (start == -1) start = i;
2903 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2909 /******************************************************************
2910 * AttachConsole (KERNEL32.@)
2912 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2914 FIXME("stub %x\n",dwProcessId);
2918 /******************************************************************
2919 * GetConsoleDisplayMode (KERNEL32.@)
2921 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2923 TRACE("semi-stub: %p\n", lpModeFlags);
2924 /* It is safe to successfully report windowed mode */
2929 /******************************************************************
2930 * SetConsoleDisplayMode (KERNEL32.@)
2932 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2933 COORD *lpNewScreenBufferDimensions)
2935 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2936 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2939 /* We cannot switch to fullscreen */
2946 /* ====================================================================
2948 * Console manipulation functions
2950 * ====================================================================*/
2952 /* some missing functions...
2953 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2954 * should get the right API and implement them
2955 * GetConsoleCommandHistory[AW] (dword dword dword)
2956 * GetConsoleCommandHistoryLength[AW]
2957 * SetConsoleCommandHistoryMode
2958 * SetConsoleNumberOfCommands[AW]
2960 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2964 SERVER_START_REQ( get_console_input_history )
2968 if (buf && buf_len > 1)
2970 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2972 if (!wine_server_call_err( req ))
2974 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2975 len = reply->total / sizeof(WCHAR) + 1;
2982 /******************************************************************
2983 * CONSOLE_AppendHistory
2987 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2989 size_t len = strlenW(ptr);
2992 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2993 if (!len) return FALSE;
2995 SERVER_START_REQ( append_console_input_history )
2998 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2999 ret = !wine_server_call_err( req );
3005 /******************************************************************
3006 * CONSOLE_GetNumHistoryEntries
3010 unsigned CONSOLE_GetNumHistoryEntries(void)
3013 SERVER_START_REQ(get_console_input_info)
3016 if (!wine_server_call_err( req )) ret = reply->history_index;
3022 /******************************************************************
3023 * CONSOLE_GetEditionMode
3027 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
3029 unsigned ret = FALSE;
3030 SERVER_START_REQ(get_console_input_info)
3032 req->handle = console_handle_unmap(hConIn);
3033 if ((ret = !wine_server_call_err( req )))
3034 *mode = reply->edition_mode;
3040 /******************************************************************
3045 * 0 if an error occurred, non-zero for success
3048 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3049 DWORD TargetBufferLength, LPWSTR lpExename)
3051 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3052 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3056 /******************************************************************
3057 * GetConsoleProcessList (KERNEL32.@)
3059 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3061 FIXME("(%p,%d): stub\n", processlist, processcount);
3063 if (!processlist || processcount < 1)
3065 SetLastError(ERROR_INVALID_PARAMETER);
3072 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3074 memset(&S_termios, 0, sizeof(S_termios));
3075 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3079 /* FIXME: to be done even if program is a GUI ? */
3080 /* This is wine specific: we have no parent (we're started from unix)
3081 * so, create a simple console with bare handles
3083 wine_server_send_fd(0);
3084 SERVER_START_REQ( alloc_console )
3086 req->access = GENERIC_READ | GENERIC_WRITE;
3087 req->attributes = OBJ_INHERIT;
3088 req->pid = 0xffffffff;
3090 wine_server_call( req );
3091 conin = wine_server_ptr_handle( reply->handle_in );
3092 /* reply->event shouldn't be created by server */
3096 if (!params->hStdInput)
3097 params->hStdInput = conin;
3099 if (!params->hStdOutput)
3101 wine_server_send_fd(1);
3102 SERVER_START_REQ( create_console_output )
3104 req->handle_in = wine_server_obj_handle(conin);
3105 req->access = GENERIC_WRITE|GENERIC_READ;
3106 req->attributes = OBJ_INHERIT;
3107 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3109 wine_server_call(req);
3110 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3114 if (!params->hStdError)
3116 wine_server_send_fd(2);
3117 SERVER_START_REQ( create_console_output )
3119 req->handle_in = wine_server_obj_handle(conin);
3120 req->access = GENERIC_WRITE|GENERIC_READ;
3121 req->attributes = OBJ_INHERIT;
3122 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3124 wine_server_call(req);
3125 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3131 /* convert value from server:
3132 * + 0 => INVALID_HANDLE_VALUE
3133 * + console handle needs to be mapped
3135 if (!params->hStdInput)
3136 params->hStdInput = INVALID_HANDLE_VALUE;
3137 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3139 params->hStdInput = console_handle_map(params->hStdInput);
3140 save_console_mode(params->hStdInput);
3143 if (!params->hStdOutput)
3144 params->hStdOutput = INVALID_HANDLE_VALUE;
3145 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3146 params->hStdOutput = console_handle_map(params->hStdOutput);
3148 if (!params->hStdError)
3149 params->hStdError = INVALID_HANDLE_VALUE;
3150 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3151 params->hStdError = console_handle_map(params->hStdError);
3156 BOOL CONSOLE_Exit(void)
3158 /* the console is in raw mode, put it back in cooked mode */
3159 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));