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"
46 #define WIN32_NO_STATUS
52 #include "wine/server.h"
53 #include "wine/exception.h"
54 #include "wine/unicode.h"
55 #include "wine/debug.h"
57 #include "console_private.h"
58 #include "kernel_private.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(console);
62 static CRITICAL_SECTION CONSOLE_CritSect;
63 static CRITICAL_SECTION_DEBUG critsect_debug =
65 0, 0, &CONSOLE_CritSect,
66 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
67 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
69 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
71 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
72 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
74 /* FIXME: this is not thread safe */
75 static HANDLE console_wait_event;
77 /* map input records to ASCII */
78 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
83 for (i = 0; i < count; i++)
85 if (buffer[i].EventType != KEY_EVENT) continue;
86 WideCharToMultiByte( GetConsoleCP(), 0,
87 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
88 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
92 /* map input records to Unicode */
93 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
98 for (i = 0; i < count; i++)
100 if (buffer[i].EventType != KEY_EVENT) continue;
101 MultiByteToWideChar( GetConsoleCP(), 0,
102 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
103 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
107 /* map char infos to ASCII */
108 static void char_info_WtoA( CHAR_INFO *buffer, int count )
114 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
115 &ch, 1, NULL, NULL );
116 buffer->Char.AsciiChar = ch;
121 /* map char infos to Unicode */
122 static void char_info_AtoW( CHAR_INFO *buffer, int count )
128 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
129 buffer->Char.UnicodeChar = ch;
134 static struct termios S_termios; /* saved termios for bare consoles */
135 static BOOL S_termios_raw /* = FALSE */;
137 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
138 * - a bare console is created for all CUI programs started from command line (without
139 * wineconsole) (let's call those PS)
140 * - of course, every child of a PS which requires console inheritance will get it
141 * - the console termios attributes are saved at the start of program which is attached to be
143 * - if any program attached to a bare console requests input from console, the console is
144 * turned into raw mode
145 * - when the program which created the bare console (the program started from command line)
146 * exits, it will restore the console termios attributes it saved at startup (this
147 * will put back the console into cooked mode if it had been put in raw mode)
148 * - if any other program attached to this bare console is still alive, the Unix shell will put
149 * it in the background, hence forbidding access to the console. Therefore, reading console
150 * input will not be available when the bare console creator has died.
151 * FIXME: This is a limitation of current implementation
154 /* returns the fd for a bare console (-1 otherwise) */
155 static int get_console_bare_fd(HANDLE hin)
159 if (wine_server_handle_to_fd(wine_server_ptr_handle(console_handle_unmap(hin)),
160 0, &fd, NULL) == STATUS_SUCCESS)
165 static BOOL save_console_mode(HANDLE hin)
170 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
171 ret = tcgetattr(fd, &S_termios) >= 0;
176 static BOOL put_console_into_raw_mode(int fd)
178 RtlEnterCriticalSection(&CONSOLE_CritSect);
181 struct termios term = S_termios;
183 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
184 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
185 term.c_cflag &= ~(CSIZE | PARENB);
187 /* FIXME: we should actually disable output processing here
188 * and let kernel32/console.c do the job (with support of enable/disable of
191 /* term.c_oflag &= ~(OPOST); */
193 term.c_cc[VTIME] = 0;
194 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
196 RtlLeaveCriticalSection(&CONSOLE_CritSect);
198 return S_termios_raw;
201 /* put back the console in cooked mode iff we're the process which created the bare console
202 * we don't test if thie process has set the console in raw mode as it could be one of its
205 static BOOL restore_console_mode(HANDLE hin)
210 if (!S_termios_raw ||
211 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
213 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
214 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
219 /******************************************************************************
220 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
223 * Success: hwnd of the console window.
226 HWND WINAPI GetConsoleWindow(VOID)
230 SERVER_START_REQ(get_console_input_info)
233 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
241 /******************************************************************************
242 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
247 UINT WINAPI GetConsoleCP(VOID)
250 UINT codepage = GetOEMCP(); /* default value */
252 SERVER_START_REQ(get_console_input_info)
255 ret = !wine_server_call_err(req);
256 if (ret && reply->input_cp)
257 codepage = reply->input_cp;
265 /******************************************************************************
266 * SetConsoleCP [KERNEL32.@]
268 BOOL WINAPI SetConsoleCP(UINT cp)
272 if (!IsValidCodePage(cp))
274 SetLastError(ERROR_INVALID_PARAMETER);
278 SERVER_START_REQ(set_console_input_info)
281 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
283 ret = !wine_server_call_err(req);
291 /***********************************************************************
292 * GetConsoleOutputCP (KERNEL32.@)
294 UINT WINAPI GetConsoleOutputCP(VOID)
297 UINT codepage = GetOEMCP(); /* default value */
299 SERVER_START_REQ(get_console_input_info)
302 ret = !wine_server_call_err(req);
303 if (ret && reply->output_cp)
304 codepage = reply->output_cp;
312 /******************************************************************************
313 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
316 * cp [I] code page to set
322 BOOL WINAPI SetConsoleOutputCP(UINT cp)
326 if (!IsValidCodePage(cp))
328 SetLastError(ERROR_INVALID_PARAMETER);
332 SERVER_START_REQ(set_console_input_info)
335 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
337 ret = !wine_server_call_err(req);
345 /***********************************************************************
348 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
350 static const char beep = '\a';
351 /* dwFreq and dwDur are ignored by Win95 */
352 if (isatty(2)) write( 2, &beep, 1 );
357 /******************************************************************
358 * OpenConsoleW (KERNEL32.@)
361 * Open a handle to the current process console.
362 * Returns INVALID_HANDLE_VALUE on failure.
364 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
366 HANDLE output = INVALID_HANDLE_VALUE;
369 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
373 if (strcmpiW(coninW, name) == 0)
374 output = (HANDLE) FALSE;
375 else if (strcmpiW(conoutW, name) == 0)
376 output = (HANDLE) TRUE;
379 if (output == INVALID_HANDLE_VALUE)
381 SetLastError(ERROR_INVALID_PARAMETER);
382 return INVALID_HANDLE_VALUE;
384 else if (creation != OPEN_EXISTING)
386 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
387 SetLastError(ERROR_SHARING_VIOLATION);
389 SetLastError(ERROR_INVALID_PARAMETER);
390 return INVALID_HANDLE_VALUE;
393 SERVER_START_REQ( open_console )
395 req->from = wine_server_obj_handle( output );
396 req->access = access;
397 req->attributes = inherit ? OBJ_INHERIT : 0;
398 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
399 wine_server_call_err( req );
400 ret = wine_server_ptr_handle( reply->handle );
404 ret = console_handle_map(ret);
409 /******************************************************************
410 * VerifyConsoleIoHandle (KERNEL32.@)
414 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
418 if (!is_console_handle(handle)) return FALSE;
419 SERVER_START_REQ(get_console_mode)
421 req->handle = console_handle_unmap(handle);
422 ret = !wine_server_call( req );
428 /******************************************************************
429 * DuplicateConsoleHandle (KERNEL32.@)
433 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
438 if (!is_console_handle(handle) ||
439 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
440 GetCurrentProcess(), &ret, access, inherit, options))
441 return INVALID_HANDLE_VALUE;
442 return console_handle_map(ret);
445 /******************************************************************
446 * CloseConsoleHandle (KERNEL32.@)
450 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
452 if (!is_console_handle(handle))
454 SetLastError(ERROR_INVALID_PARAMETER);
457 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
460 /******************************************************************
461 * GetConsoleInputWaitHandle (KERNEL32.@)
465 HANDLE WINAPI GetConsoleInputWaitHandle(void)
467 if (!console_wait_event)
469 SERVER_START_REQ(get_console_wait_event)
471 if (!wine_server_call_err( req ))
472 console_wait_event = wine_server_ptr_handle( reply->handle );
476 return console_wait_event;
480 /******************************************************************************
481 * WriteConsoleInputA [KERNEL32.@]
483 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
484 DWORD count, LPDWORD written )
489 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
490 memcpy( recW, buffer, count*sizeof(*recW) );
491 input_records_AtoW( recW, count );
492 ret = WriteConsoleInputW( handle, recW, count, written );
493 HeapFree( GetProcessHeap(), 0, recW );
498 /******************************************************************************
499 * WriteConsoleInputW [KERNEL32.@]
501 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
502 DWORD count, LPDWORD written )
506 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
508 if (written) *written = 0;
509 SERVER_START_REQ( write_console_input )
511 req->handle = console_handle_unmap(handle);
512 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
513 if ((ret = !wine_server_call_err( req )) && written)
514 *written = reply->written;
522 /***********************************************************************
523 * WriteConsoleOutputA (KERNEL32.@)
525 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
526 COORD size, COORD coord, LPSMALL_RECT region )
530 COORD new_size, new_coord;
533 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
534 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
536 if (new_size.X <= 0 || new_size.Y <= 0)
538 region->Bottom = region->Top + new_size.Y - 1;
539 region->Right = region->Left + new_size.X - 1;
543 /* only copy the useful rectangle */
544 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
546 for (y = 0; y < new_size.Y; y++)
548 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
549 new_size.X * sizeof(CHAR_INFO) );
550 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
552 new_coord.X = new_coord.Y = 0;
553 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
554 HeapFree( GetProcessHeap(), 0, ciw );
559 /***********************************************************************
560 * WriteConsoleOutputW (KERNEL32.@)
562 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
563 COORD size, COORD coord, LPSMALL_RECT region )
565 int width, height, y;
568 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
569 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
570 region->Left, region->Top, region->Right, region->Bottom);
572 width = min( region->Right - region->Left + 1, size.X - coord.X );
573 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
575 if (width > 0 && height > 0)
577 for (y = 0; y < height; y++)
579 SERVER_START_REQ( write_console_output )
581 req->handle = console_handle_unmap(hConsoleOutput);
582 req->x = region->Left;
583 req->y = region->Top + y;
584 req->mode = CHAR_INFO_MODE_TEXTATTR;
586 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
587 width * sizeof(CHAR_INFO));
588 if ((ret = !wine_server_call_err( req )))
590 width = min( width, reply->width - region->Left );
591 height = min( height, reply->height - region->Top );
598 region->Bottom = region->Top + height - 1;
599 region->Right = region->Left + width - 1;
604 /******************************************************************************
605 * WriteConsoleOutputCharacterA [KERNEL32.@]
607 * See WriteConsoleOutputCharacterW.
609 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
610 COORD coord, LPDWORD lpNumCharsWritten )
616 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
617 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
619 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
621 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
623 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
624 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
626 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
627 HeapFree( GetProcessHeap(), 0, strW );
632 /******************************************************************************
633 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
634 * the console screen buffer
637 * hConsoleOutput [I] Handle to screen buffer
638 * attr [I] Pointer to buffer with write attributes
639 * length [I] Number of cells to write to
640 * coord [I] Coords of first cell
641 * lpNumAttrsWritten [O] Pointer to number of cells written
648 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
649 COORD coord, LPDWORD lpNumAttrsWritten )
653 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
655 SERVER_START_REQ( write_console_output )
657 req->handle = console_handle_unmap(hConsoleOutput);
660 req->mode = CHAR_INFO_MODE_ATTR;
662 wine_server_add_data( req, attr, length * sizeof(WORD) );
663 if ((ret = !wine_server_call_err( req )))
665 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
673 /******************************************************************************
674 * FillConsoleOutputCharacterA [KERNEL32.@]
676 * See FillConsoleOutputCharacterW.
678 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
679 COORD coord, LPDWORD lpNumCharsWritten )
683 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
684 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
688 /******************************************************************************
689 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
692 * hConsoleOutput [I] Handle to screen buffer
693 * ch [I] Character to write
694 * length [I] Number of cells to write to
695 * coord [I] Coords of first cell
696 * lpNumCharsWritten [O] Pointer to number of cells written
702 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
703 COORD coord, LPDWORD lpNumCharsWritten)
707 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
708 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
710 SERVER_START_REQ( fill_console_output )
712 req->handle = console_handle_unmap(hConsoleOutput);
715 req->mode = CHAR_INFO_MODE_TEXT;
719 if ((ret = !wine_server_call_err( req )))
721 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
729 /******************************************************************************
730 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
733 * hConsoleOutput [I] Handle to screen buffer
734 * attr [I] Color attribute to write
735 * length [I] Number of cells to write to
736 * coord [I] Coords of first cell
737 * lpNumAttrsWritten [O] Pointer to number of cells written
743 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
744 COORD coord, LPDWORD lpNumAttrsWritten )
748 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
749 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
751 SERVER_START_REQ( fill_console_output )
753 req->handle = console_handle_unmap(hConsoleOutput);
756 req->mode = CHAR_INFO_MODE_ATTR;
758 req->data.attr = attr;
760 if ((ret = !wine_server_call_err( req )))
762 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
770 /******************************************************************************
771 * ReadConsoleOutputCharacterA [KERNEL32.@]
774 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
775 COORD coord, LPDWORD read_count)
779 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
781 if (read_count) *read_count = 0;
782 if (!wptr) return FALSE;
784 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
786 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
787 if (read_count) *read_count = read;
789 HeapFree( GetProcessHeap(), 0, wptr );
794 /******************************************************************************
795 * ReadConsoleOutputCharacterW [KERNEL32.@]
798 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
799 COORD coord, LPDWORD read_count )
803 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
805 SERVER_START_REQ( read_console_output )
807 req->handle = console_handle_unmap(hConsoleOutput);
810 req->mode = CHAR_INFO_MODE_TEXT;
812 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
813 if ((ret = !wine_server_call_err( req )))
815 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
823 /******************************************************************************
824 * ReadConsoleOutputAttribute [KERNEL32.@]
826 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
827 COORD coord, LPDWORD read_count)
831 TRACE("(%p,%p,%d,%dx%d,%p)\n",
832 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
834 SERVER_START_REQ( read_console_output )
836 req->handle = console_handle_unmap(hConsoleOutput);
839 req->mode = CHAR_INFO_MODE_ATTR;
841 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
842 if ((ret = !wine_server_call_err( req )))
844 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
852 /******************************************************************************
853 * ReadConsoleOutputA [KERNEL32.@]
856 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
857 COORD coord, LPSMALL_RECT region )
862 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
863 if (ret && region->Right >= region->Left)
865 for (y = 0; y <= region->Bottom - region->Top; y++)
867 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
868 region->Right - region->Left + 1 );
875 /******************************************************************************
876 * ReadConsoleOutputW [KERNEL32.@]
878 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
879 * think we need to be *that* compatible. -- AJ
881 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
882 COORD coord, LPSMALL_RECT region )
884 int width, height, y;
887 width = min( region->Right - region->Left + 1, size.X - coord.X );
888 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
890 if (width > 0 && height > 0)
892 for (y = 0; y < height; y++)
894 SERVER_START_REQ( read_console_output )
896 req->handle = console_handle_unmap(hConsoleOutput);
897 req->x = region->Left;
898 req->y = region->Top + y;
899 req->mode = CHAR_INFO_MODE_TEXTATTR;
901 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
902 width * sizeof(CHAR_INFO) );
903 if ((ret = !wine_server_call_err( req )))
905 width = min( width, reply->width - region->Left );
906 height = min( height, reply->height - region->Top );
913 region->Bottom = region->Top + height - 1;
914 region->Right = region->Left + width - 1;
919 /******************************************************************************
920 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
923 * handle [I] Handle to console input buffer
924 * buffer [O] Address of buffer for read data
925 * count [I] Number of records to read
926 * pRead [O] Address of number of records read
932 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
936 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
937 input_records_WtoA( buffer, read );
938 if (pRead) *pRead = read;
943 /***********************************************************************
944 * PeekConsoleInputA (KERNEL32.@)
946 * Gets 'count' first events (or less) from input queue.
948 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
952 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
953 input_records_WtoA( buffer, read );
954 if (pRead) *pRead = read;
959 /***********************************************************************
960 * PeekConsoleInputW (KERNEL32.@)
962 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
965 SERVER_START_REQ( read_console_input )
967 req->handle = console_handle_unmap(handle);
969 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
970 if ((ret = !wine_server_call_err( req )))
972 if (read) *read = count ? reply->read : 0;
980 /***********************************************************************
981 * GetNumberOfConsoleInputEvents (KERNEL32.@)
983 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
986 SERVER_START_REQ( read_console_input )
988 req->handle = console_handle_unmap(handle);
990 if ((ret = !wine_server_call_err( req )))
992 if (nrofevents) *nrofevents = reply->read;
1000 /******************************************************************************
1001 * read_console_input
1003 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1006 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1008 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1009 static const int vkkeyscan_table[256] =
1011 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,
1012 0,32,305,478,307,308,309,311,222,313,304,312,443,188,189,190,191,48,
1013 49,50,51,52,53,54,55,56,57,442,186,444,187,446,447,306,321,322,323,
1014 324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,
1015 341,342,343,344,345,346,219,220,221,310,445,192,65,66,67,68,69,70,71,
1016 72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,475,476,477,
1017 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,
1018 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,
1019 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,
1020 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
1023 static const int mapvkey_0[256] =
1025 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,
1026 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,
1027 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,
1028 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,
1029 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,
1030 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,
1031 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,
1032 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,
1033 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
1036 static inline void init_complex_char(INPUT_RECORD* ir, BOOL down, WORD vk, WORD kc, DWORD cks)
1038 ir->EventType = KEY_EVENT;
1039 ir->Event.KeyEvent.bKeyDown = down;
1040 ir->Event.KeyEvent.wRepeatCount = 1;
1041 ir->Event.KeyEvent.wVirtualScanCode = vk;
1042 ir->Event.KeyEvent.wVirtualKeyCode = kc;
1043 ir->Event.KeyEvent.dwControlKeyState = cks;
1044 ir->Event.KeyEvent.uChar.UnicodeChar = 0;
1047 /******************************************************************
1048 * handle_simple_char
1052 static BOOL handle_simple_char(HANDLE conin, unsigned real_inchar)
1057 unsigned numEvent = 0;
1058 DWORD cks = 0, written;
1061 switch (real_inchar)
1063 case 9: inchar = real_inchar;
1064 real_inchar = 27; /* so that we don't think key is ctrl- something */
1067 case 10: inchar = '\r';
1068 real_inchar = 27; /* Fixme: so that we don't think key is ctrl- something */
1070 case 127: inchar = '\b';
1073 inchar = real_inchar;
1076 if ((inchar & ~0xFF) != 0) FIXME("What a char (%u)\n", inchar);
1077 vk = vkkeyscan_table[inchar];
1079 init_complex_char(&ir[numEvent++], 1, 0x2a, 0x10, SHIFT_PRESSED);
1080 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1081 init_complex_char(&ir[numEvent++], 1, 0x1d, 0x11, LEFT_CTRL_PRESSED);
1083 init_complex_char(&ir[numEvent++], 1, 0x38, 0x12, LEFT_ALT_PRESSED);
1085 ir[numEvent].EventType = KEY_EVENT;
1086 ir[numEvent].Event.KeyEvent.bKeyDown = 1;
1087 ir[numEvent].Event.KeyEvent.wRepeatCount = 1;
1088 ir[numEvent].Event.KeyEvent.dwControlKeyState = cks;
1090 ir[numEvent].Event.KeyEvent.dwControlKeyState |= SHIFT_PRESSED;
1091 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1092 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_CTRL_PRESSED;
1094 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_ALT_PRESSED;
1095 ir[numEvent].Event.KeyEvent.wVirtualKeyCode = vk;
1096 ir[numEvent].Event.KeyEvent.wVirtualScanCode = mapvkey_0[vk & 0x00ff]; /* VirtualKeyCodes to ScanCode */
1099 MultiByteToWideChar(CP_UNIXCP, 0, &ch, 1, &ir[numEvent].Event.KeyEvent.uChar.UnicodeChar, 1);
1100 ir[numEvent + 1] = ir[numEvent];
1101 ir[numEvent + 1].Event.KeyEvent.bKeyDown = 0;
1106 init_complex_char(&ir[numEvent++], 0, 0x38, 0x12, LEFT_ALT_PRESSED);
1107 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1108 init_complex_char(&ir[numEvent++], 0, 0x1d, 0x11, 0);
1110 init_complex_char(&ir[numEvent++], 0, 0x2a, 0x10, 0);
1112 return WriteConsoleInputW(conin, ir, numEvent, &written);
1115 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, DWORD timeout)
1118 enum read_console_input_return ret;
1121 /* get the real handle to the console object */
1122 handle = wine_server_ptr_handle(console_handle_unmap(handle));
1124 memset(&ov, 0, sizeof(ov));
1125 ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1127 if (ReadFile(handle, &ch, 1, NULL, &ov) ||
1128 (GetLastError() == ERROR_IO_PENDING &&
1129 WaitForSingleObject(ov.hEvent, timeout) == WAIT_OBJECT_0 &&
1130 GetOverlappedResult(handle, &ov, NULL, FALSE)))
1132 ret = handle_simple_char(handle, ch) ? rci_gotone : rci_error;
1136 WARN("Failed read %x\n", GetLastError());
1139 CloseHandle(ov.hEvent);
1144 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1147 enum read_console_input_return ret;
1149 if ((fd = get_console_bare_fd(handle)) != -1)
1151 put_console_into_raw_mode(fd);
1153 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1155 ret = bare_console_fetch_input(handle, timeout);
1156 if (ret != rci_gotone) return ret;
1161 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1163 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1167 SERVER_START_REQ( read_console_input )
1169 req->handle = console_handle_unmap(handle);
1171 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1172 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1173 else ret = rci_gotone;
1181 /***********************************************************************
1182 * FlushConsoleInputBuffer (KERNEL32.@)
1184 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1186 enum read_console_input_return last;
1189 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1191 return last == rci_timeout;
1195 /***********************************************************************
1196 * SetConsoleTitleA (KERNEL32.@)
1198 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1203 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1204 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1205 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1206 ret = SetConsoleTitleW(titleW);
1207 HeapFree(GetProcessHeap(), 0, titleW);
1212 /***********************************************************************
1213 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1215 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1217 FIXME( "stub %p\n", layoutName);
1221 /***********************************************************************
1222 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1224 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1226 FIXME( "stub %p\n", layoutName);
1230 static WCHAR input_exe[MAX_PATH + 1];
1232 /***********************************************************************
1233 * GetConsoleInputExeNameW (KERNEL32.@)
1235 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1237 TRACE("%u %p\n", buflen, buffer);
1239 RtlEnterCriticalSection(&CONSOLE_CritSect);
1240 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1241 else SetLastError(ERROR_BUFFER_OVERFLOW);
1242 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1247 /***********************************************************************
1248 * GetConsoleInputExeNameA (KERNEL32.@)
1250 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1252 TRACE("%u %p\n", buflen, buffer);
1254 RtlEnterCriticalSection(&CONSOLE_CritSect);
1255 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1256 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1257 else SetLastError(ERROR_BUFFER_OVERFLOW);
1258 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1263 /***********************************************************************
1264 * GetConsoleTitleA (KERNEL32.@)
1266 * See GetConsoleTitleW.
1268 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1270 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1274 ret = GetConsoleTitleW( ptr, size );
1277 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1278 ret = strlen(title);
1280 HeapFree(GetProcessHeap(), 0, ptr);
1285 /******************************************************************************
1286 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1289 * title [O] Address of buffer for title
1290 * size [I] Size of buffer
1293 * Success: Length of string copied
1296 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1300 SERVER_START_REQ( get_console_input_info )
1303 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1304 if (!wine_server_call_err( req ))
1306 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1315 /***********************************************************************
1316 * GetLargestConsoleWindowSize (KERNEL32.@)
1319 * This should return a COORD, but calling convention for returning
1320 * structures is different between Windows and gcc on i386.
1325 #undef GetLargestConsoleWindowSize
1326 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1334 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1337 #endif /* defined(__i386__) */
1340 /***********************************************************************
1341 * GetLargestConsoleWindowSize (KERNEL32.@)
1344 * This should return a COORD, but calling convention for returning
1345 * structures is different between Windows and gcc on i386.
1350 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1355 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1358 #endif /* defined(__i386__) */
1360 static WCHAR* S_EditString /* = NULL */;
1361 static unsigned S_EditStrPos /* = 0 */;
1363 /***********************************************************************
1364 * FreeConsole (KERNEL32.@)
1366 BOOL WINAPI FreeConsole(VOID)
1370 /* invalidate local copy of input event handle */
1371 console_wait_event = 0;
1373 SERVER_START_REQ(free_console)
1375 ret = !wine_server_call_err( req );
1381 /******************************************************************
1382 * start_console_renderer
1384 * helper for AllocConsole
1385 * starts the renderer process
1387 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1392 PROCESS_INFORMATION pi;
1394 /* FIXME: use dynamic allocation for most of the buffers below */
1395 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1396 if ((ret > -1) && (ret < sizeof(buffer)) &&
1397 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1398 NULL, NULL, si, &pi))
1404 wh[1] = pi.hProcess;
1405 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1407 CloseHandle(pi.hThread);
1408 CloseHandle(pi.hProcess);
1410 if (ret != WAIT_OBJECT_0) return FALSE;
1412 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1413 pi.dwProcessId, pi.dwThreadId);
1420 static BOOL start_console_renderer(STARTUPINFOA* si)
1424 OBJECT_ATTRIBUTES attr;
1427 attr.Length = sizeof(attr);
1428 attr.RootDirectory = 0;
1429 attr.Attributes = OBJ_INHERIT;
1430 attr.ObjectName = NULL;
1431 attr.SecurityDescriptor = NULL;
1432 attr.SecurityQualityOfService = NULL;
1434 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1435 if (!hEvent) return FALSE;
1437 /* first try environment variable */
1438 if ((p = getenv("WINECONSOLE")) != NULL)
1440 ret = start_console_renderer_helper(p, si, hEvent);
1442 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1443 "trying default access\n", p);
1446 /* then try the regular PATH */
1448 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1450 CloseHandle(hEvent);
1454 /***********************************************************************
1455 * AllocConsole (KERNEL32.@)
1457 * creates an xterm with a pty to our program
1459 BOOL WINAPI AllocConsole(void)
1461 HANDLE handle_in = INVALID_HANDLE_VALUE;
1462 HANDLE handle_out = INVALID_HANDLE_VALUE;
1463 HANDLE handle_err = INVALID_HANDLE_VALUE;
1464 STARTUPINFOA siCurrent;
1465 STARTUPINFOA siConsole;
1470 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1471 FALSE, OPEN_EXISTING );
1473 if (VerifyConsoleIoHandle(handle_in))
1475 /* we already have a console opened on this process, don't create a new one */
1476 CloseHandle(handle_in);
1480 /* invalidate local copy of input event handle */
1481 console_wait_event = 0;
1483 GetStartupInfoA(&siCurrent);
1485 memset(&siConsole, 0, sizeof(siConsole));
1486 siConsole.cb = sizeof(siConsole);
1487 /* setup a view arguments for wineconsole (it'll use them as default values) */
1488 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1490 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1491 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1492 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1494 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1496 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1497 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1499 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1501 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1502 siConsole.wShowWindow = siCurrent.wShowWindow;
1504 /* FIXME (should pass the unicode form) */
1505 if (siCurrent.lpTitle)
1506 siConsole.lpTitle = siCurrent.lpTitle;
1507 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1509 buffer[sizeof(buffer) - 1] = '\0';
1510 siConsole.lpTitle = buffer;
1513 if (!start_console_renderer(&siConsole))
1516 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1517 /* all std I/O handles are inheritable by default */
1518 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1519 TRUE, OPEN_EXISTING );
1520 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1522 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1523 TRUE, OPEN_EXISTING );
1524 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1526 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1527 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1530 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1531 handle_in = siCurrent.hStdInput;
1532 handle_out = siCurrent.hStdOutput;
1533 handle_err = siCurrent.hStdError;
1536 /* NT resets the STD_*_HANDLEs on console alloc */
1537 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1538 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1539 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1541 SetLastError(ERROR_SUCCESS);
1546 ERR("Can't allocate console\n");
1547 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1548 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1549 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1555 /***********************************************************************
1556 * ReadConsoleA (KERNEL32.@)
1558 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1559 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1561 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1565 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1566 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1568 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1569 HeapFree(GetProcessHeap(), 0, ptr);
1574 /***********************************************************************
1575 * ReadConsoleW (KERNEL32.@)
1577 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1578 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1581 LPWSTR xbuf = lpBuffer;
1583 BOOL is_bare = FALSE;
1586 TRACE("(%p,%p,%d,%p,%p)\n",
1587 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1589 if (!GetConsoleMode(hConsoleInput, &mode))
1591 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1596 if (mode & ENABLE_LINE_INPUT)
1598 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1600 HeapFree(GetProcessHeap(), 0, S_EditString);
1601 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1605 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1606 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1607 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1608 S_EditStrPos += charsread;
1613 DWORD timeout = INFINITE;
1615 /* FIXME: should we read at least 1 char? The SDK does not say */
1616 /* wait for at least one available input record (it doesn't mean we'll have
1617 * chars stored in xbuf...)
1619 * Although SDK doc keeps silence about 1 char, SDK examples assume
1620 * that we should wait for at least one character (not key). --KS
1625 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1626 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1627 ir.Event.KeyEvent.uChar.UnicodeChar)
1629 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1632 } while (charsread < nNumberOfCharsToRead);
1633 /* nothing has been read */
1634 if (timeout == INFINITE) return FALSE;
1637 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1643 /***********************************************************************
1644 * ReadConsoleInputW (KERNEL32.@)
1646 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1647 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1650 DWORD timeout = INFINITE;
1654 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1658 /* loop until we get at least one event */
1659 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1663 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1668 /******************************************************************************
1669 * WriteConsoleOutputCharacterW [KERNEL32.@]
1671 * Copy character to consecutive cells in the console screen buffer.
1674 * hConsoleOutput [I] Handle to screen buffer
1675 * str [I] Pointer to buffer with chars to write
1676 * length [I] Number of cells to write to
1677 * coord [I] Coords of first cell
1678 * lpNumCharsWritten [O] Pointer to number of cells written
1685 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1686 COORD coord, LPDWORD lpNumCharsWritten )
1690 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1691 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1693 SERVER_START_REQ( write_console_output )
1695 req->handle = console_handle_unmap(hConsoleOutput);
1698 req->mode = CHAR_INFO_MODE_TEXT;
1700 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1701 if ((ret = !wine_server_call_err( req )))
1703 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1711 /******************************************************************************
1712 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1715 * title [I] Address of new title
1721 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1725 TRACE("(%s)\n", debugstr_w(title));
1726 SERVER_START_REQ( set_console_input_info )
1729 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1730 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1731 ret = !wine_server_call_err( req );
1738 /***********************************************************************
1739 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1741 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1743 FIXME("(%p): stub\n", nrofbuttons);
1748 /******************************************************************************
1749 * SetConsoleInputExeNameW [KERNEL32.@]
1751 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1753 TRACE("(%s)\n", debugstr_w(name));
1755 if (!name || !name[0])
1757 SetLastError(ERROR_INVALID_PARAMETER);
1761 RtlEnterCriticalSection(&CONSOLE_CritSect);
1762 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1763 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1768 /******************************************************************************
1769 * SetConsoleInputExeNameA [KERNEL32.@]
1771 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1777 if (!name || !name[0])
1779 SetLastError(ERROR_INVALID_PARAMETER);
1783 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1784 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1786 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1787 ret = SetConsoleInputExeNameW(nameW);
1788 HeapFree(GetProcessHeap(), 0, nameW);
1793 /******************************************************************
1794 * CONSOLE_DefaultHandler
1796 * Final control event handler
1798 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1800 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1802 /* should never go here */
1806 /******************************************************************************
1807 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1810 * func [I] Address of handler function
1811 * add [I] Handler to add or remove
1818 struct ConsoleHandler
1820 PHANDLER_ROUTINE handler;
1821 struct ConsoleHandler* next;
1824 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1825 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1827 /*****************************************************************************/
1829 /******************************************************************
1830 * SetConsoleCtrlHandler (KERNEL32.@)
1832 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1836 TRACE("(%p,%i)\n", func, add);
1840 RtlEnterCriticalSection(&CONSOLE_CritSect);
1842 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1844 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1845 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1849 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1851 if (!ch) return FALSE;
1853 RtlEnterCriticalSection(&CONSOLE_CritSect);
1854 ch->next = CONSOLE_Handlers;
1855 CONSOLE_Handlers = ch;
1856 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1860 struct ConsoleHandler** ch;
1861 RtlEnterCriticalSection(&CONSOLE_CritSect);
1862 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1864 if ((*ch)->handler == func) break;
1868 struct ConsoleHandler* rch = *ch;
1871 if (rch == &CONSOLE_DefaultConsoleHandler)
1873 ERR("Who's trying to remove default handler???\n");
1874 SetLastError(ERROR_INVALID_PARAMETER);
1880 HeapFree(GetProcessHeap(), 0, rch);
1885 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1886 SetLastError(ERROR_INVALID_PARAMETER);
1889 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1894 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1896 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1897 return EXCEPTION_EXECUTE_HANDLER;
1900 /******************************************************************
1901 * CONSOLE_SendEventThread
1903 * Internal helper to pass an event to the list on installed handlers
1905 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1907 DWORD_PTR event = (DWORD_PTR)pmt;
1908 struct ConsoleHandler* ch;
1910 if (event == CTRL_C_EVENT)
1912 BOOL caught_by_dbg = TRUE;
1913 /* First, try to pass the ctrl-C event to the debugger (if any)
1914 * If it continues, there's nothing more to do
1915 * Otherwise, we need to send the ctrl-C event to the handlers
1919 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1921 __EXCEPT(CONSOLE_CtrlEventHandler)
1923 caught_by_dbg = FALSE;
1926 if (caught_by_dbg) return 0;
1927 /* the debugger didn't continue... so, pass to ctrl handlers */
1929 RtlEnterCriticalSection(&CONSOLE_CritSect);
1930 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1932 if (ch->handler(event)) break;
1934 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1938 /******************************************************************
1939 * CONSOLE_HandleCtrlC
1941 * Check whether the shall manipulate CtrlC events
1943 int CONSOLE_HandleCtrlC(unsigned sig)
1945 /* FIXME: better test whether a console is attached to this process ??? */
1946 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1947 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1949 /* check if we have to ignore ctrl-C events */
1950 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1952 /* Create a separate thread to signal all the events.
1953 * This is needed because:
1954 * - this function can be called in an Unix signal handler (hence on an
1955 * different stack than the thread that's running). This breaks the
1956 * Win32 exception mechanisms (where the thread's stack is checked).
1957 * - since the current thread, while processing the signal, can hold the
1958 * console critical section, we need another execution environment where
1959 * we can wait on this critical section
1961 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1966 /******************************************************************************
1967 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1970 * dwCtrlEvent [I] Type of event
1971 * dwProcessGroupID [I] Process group ID to send event to
1975 * Failure: False (and *should* [but doesn't] set LastError)
1977 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1978 DWORD dwProcessGroupID)
1982 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
1984 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1986 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
1990 SERVER_START_REQ( send_console_signal )
1992 req->signal = dwCtrlEvent;
1993 req->group_id = dwProcessGroupID;
1994 ret = !wine_server_call_err( req );
1998 /* FIXME: Shall this function be synchronous, i.e., only return when all events
1999 * have been handled by all processes in the given group?
2000 * As of today, we don't wait...
2006 /******************************************************************************
2007 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2010 * dwDesiredAccess [I] Access flag
2011 * dwShareMode [I] Buffer share mode
2012 * sa [I] Security attributes
2013 * dwFlags [I] Type of buffer to create
2014 * lpScreenBufferData [I] Reserved
2017 * Should call SetLastError
2020 * Success: Handle to new console screen buffer
2021 * Failure: INVALID_HANDLE_VALUE
2023 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2024 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2025 LPVOID lpScreenBufferData)
2027 HANDLE ret = INVALID_HANDLE_VALUE;
2029 TRACE("(%d,%d,%p,%d,%p)\n",
2030 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2032 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2034 SetLastError(ERROR_INVALID_PARAMETER);
2035 return INVALID_HANDLE_VALUE;
2038 SERVER_START_REQ(create_console_output)
2041 req->access = dwDesiredAccess;
2042 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2043 req->share = dwShareMode;
2045 if (!wine_server_call_err( req ))
2046 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2054 /***********************************************************************
2055 * GetConsoleScreenBufferInfo (KERNEL32.@)
2057 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2061 SERVER_START_REQ(get_console_output_info)
2063 req->handle = console_handle_unmap(hConsoleOutput);
2064 if ((ret = !wine_server_call_err( req )))
2066 csbi->dwSize.X = reply->width;
2067 csbi->dwSize.Y = reply->height;
2068 csbi->dwCursorPosition.X = reply->cursor_x;
2069 csbi->dwCursorPosition.Y = reply->cursor_y;
2070 csbi->wAttributes = reply->attr;
2071 csbi->srWindow.Left = reply->win_left;
2072 csbi->srWindow.Right = reply->win_right;
2073 csbi->srWindow.Top = reply->win_top;
2074 csbi->srWindow.Bottom = reply->win_bottom;
2075 csbi->dwMaximumWindowSize.X = reply->max_width;
2076 csbi->dwMaximumWindowSize.Y = reply->max_height;
2081 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2082 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2083 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2085 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2086 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2092 /******************************************************************************
2093 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2099 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2103 TRACE("(%p)\n", hConsoleOutput);
2105 SERVER_START_REQ( set_console_input_info )
2108 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2109 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2110 ret = !wine_server_call_err( req );
2117 /***********************************************************************
2118 * GetConsoleMode (KERNEL32.@)
2120 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2124 SERVER_START_REQ( get_console_mode )
2126 req->handle = console_handle_unmap(hcon);
2127 if ((ret = !wine_server_call_err( req )))
2129 if (mode) *mode = reply->mode;
2137 /******************************************************************************
2138 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2141 * hcon [I] Handle to console input or screen buffer
2142 * mode [I] Input or output mode to set
2149 * ENABLE_PROCESSED_INPUT 0x01
2150 * ENABLE_LINE_INPUT 0x02
2151 * ENABLE_ECHO_INPUT 0x04
2152 * ENABLE_WINDOW_INPUT 0x08
2153 * ENABLE_MOUSE_INPUT 0x10
2155 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2159 SERVER_START_REQ(set_console_mode)
2161 req->handle = console_handle_unmap(hcon);
2163 ret = !wine_server_call_err( req );
2166 /* FIXME: when resetting a console input to editline mode, I think we should
2167 * empty the S_EditString buffer
2170 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2176 /******************************************************************
2177 * CONSOLE_WriteChars
2179 * WriteConsoleOutput helper: hides server call semantics
2180 * writes a string at a given pos with standard attribute
2182 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2188 SERVER_START_REQ( write_console_output )
2190 req->handle = console_handle_unmap(hCon);
2193 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2195 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2196 if (!wine_server_call_err( req )) written = reply->written;
2200 if (written > 0) pos->X += written;
2204 /******************************************************************
2207 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2210 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2216 csbi->dwCursorPosition.X = 0;
2217 csbi->dwCursorPosition.Y++;
2219 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2222 src.Bottom = csbi->dwSize.Y - 1;
2224 src.Right = csbi->dwSize.X - 1;
2229 ci.Attributes = csbi->wAttributes;
2230 ci.Char.UnicodeChar = ' ';
2232 csbi->dwCursorPosition.Y--;
2233 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2238 /******************************************************************
2241 * WriteConsoleOutput helper: writes a block of non special characters
2242 * Block can spread on several lines, and wrapping, if needed, is
2246 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2247 DWORD mode, LPCWSTR ptr, int len)
2249 int blk; /* number of chars to write on current line */
2250 int done; /* number of chars already written */
2252 if (len <= 0) return 1;
2254 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2256 for (done = 0; done < len; done += blk)
2258 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2260 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2262 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2268 int pos = csbi->dwCursorPosition.X;
2269 /* FIXME: we could reduce the number of loops
2270 * but, in most cases we wouldn't gain lots of time (it would only
2271 * happen if we're asked to overwrite more than twice the part of the line,
2274 for (done = 0; done < len; done += blk)
2276 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2278 csbi->dwCursorPosition.X = pos;
2279 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2287 /***********************************************************************
2288 * WriteConsoleW (KERNEL32.@)
2290 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2291 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2295 const WCHAR* psz = lpBuffer;
2296 CONSOLE_SCREEN_BUFFER_INFO csbi;
2297 int k, first = 0, fd;
2299 TRACE("%p %s %d %p %p\n",
2300 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2301 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2303 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2305 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2312 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2315 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2316 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2319 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2320 ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2321 ptr, len, lpNumberOfCharsWritten, NULL);
2322 if (ret && lpNumberOfCharsWritten)
2324 if (*lpNumberOfCharsWritten == len)
2325 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2327 FIXME("Conversion not supported yet\n");
2329 HeapFree(GetProcessHeap(), 0, ptr);
2333 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2336 if (!nNumberOfCharsToWrite) return TRUE;
2338 if (mode & ENABLE_PROCESSED_OUTPUT)
2342 for (i = 0; i < nNumberOfCharsToWrite; i++)
2346 case '\b': case '\t': case '\n': case '\a': case '\r':
2347 /* don't handle here the i-th char... done below */
2348 if ((k = i - first) > 0)
2350 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2360 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2364 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2366 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2367 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2372 next_line(hConsoleOutput, &csbi);
2378 csbi.dwCursorPosition.X = 0;
2386 /* write the remaining block (if any) if processed output is enabled, or the
2387 * entire buffer otherwise
2389 if ((k = nNumberOfCharsToWrite - first) > 0)
2391 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2397 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2398 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2403 /***********************************************************************
2404 * WriteConsoleA (KERNEL32.@)
2406 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2407 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2413 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2415 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2416 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2417 if (!xstring) return 0;
2419 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2421 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2423 HeapFree(GetProcessHeap(), 0, xstring);
2428 /******************************************************************************
2429 * SetConsoleCursorPosition [KERNEL32.@]
2430 * Sets the cursor position in console
2433 * hConsoleOutput [I] Handle of console screen buffer
2434 * dwCursorPosition [I] New cursor position coordinates
2440 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2443 CONSOLE_SCREEN_BUFFER_INFO csbi;
2447 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2449 SERVER_START_REQ(set_console_output_info)
2451 req->handle = console_handle_unmap(hcon);
2452 req->cursor_x = pos.X;
2453 req->cursor_y = pos.Y;
2454 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2455 ret = !wine_server_call_err( req );
2459 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2462 /* if cursor is no longer visible, scroll the visible window... */
2463 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2464 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2465 if (pos.X < csbi.srWindow.Left)
2467 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2470 else if (pos.X > csbi.srWindow.Right)
2472 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2475 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2477 if (pos.Y < csbi.srWindow.Top)
2479 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2482 else if (pos.Y > csbi.srWindow.Bottom)
2484 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2487 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2489 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2494 /******************************************************************************
2495 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2498 * hcon [I] Handle to console screen buffer
2499 * cinfo [O] Address of cursor information
2505 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2509 SERVER_START_REQ(get_console_output_info)
2511 req->handle = console_handle_unmap(hCon);
2512 ret = !wine_server_call_err( req );
2515 cinfo->dwSize = reply->cursor_size;
2516 cinfo->bVisible = reply->cursor_visible;
2521 if (!ret) return FALSE;
2525 SetLastError(ERROR_INVALID_ACCESS);
2528 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2534 /******************************************************************************
2535 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2538 * hcon [I] Handle to console screen buffer
2539 * cinfo [I] Address of cursor information
2544 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2548 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2549 SERVER_START_REQ(set_console_output_info)
2551 req->handle = console_handle_unmap(hCon);
2552 req->cursor_size = cinfo->dwSize;
2553 req->cursor_visible = cinfo->bVisible;
2554 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2555 ret = !wine_server_call_err( req );
2562 /******************************************************************************
2563 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2566 * hcon [I] Handle to console screen buffer
2567 * bAbsolute [I] Coordinate type flag
2568 * window [I] Address of new window rectangle
2573 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2575 SMALL_RECT p = *window;
2578 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2582 CONSOLE_SCREEN_BUFFER_INFO csbi;
2584 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2586 p.Left += csbi.srWindow.Left;
2587 p.Top += csbi.srWindow.Top;
2588 p.Right += csbi.srWindow.Right;
2589 p.Bottom += csbi.srWindow.Bottom;
2591 SERVER_START_REQ(set_console_output_info)
2593 req->handle = console_handle_unmap(hCon);
2594 req->win_left = p.Left;
2595 req->win_top = p.Top;
2596 req->win_right = p.Right;
2597 req->win_bottom = p.Bottom;
2598 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2599 ret = !wine_server_call_err( req );
2607 /******************************************************************************
2608 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2610 * Sets the foreground and background color attributes of characters
2611 * written to the screen buffer.
2617 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2621 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2622 SERVER_START_REQ(set_console_output_info)
2624 req->handle = console_handle_unmap(hConsoleOutput);
2626 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2627 ret = !wine_server_call_err( req );
2634 /******************************************************************************
2635 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2638 * hConsoleOutput [I] Handle to console screen buffer
2639 * dwSize [I] New size in character rows and cols
2645 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2649 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2650 SERVER_START_REQ(set_console_output_info)
2652 req->handle = console_handle_unmap(hConsoleOutput);
2653 req->width = dwSize.X;
2654 req->height = dwSize.Y;
2655 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2656 ret = !wine_server_call_err( req );
2663 /******************************************************************************
2664 * ScrollConsoleScreenBufferA [KERNEL32.@]
2667 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2668 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2673 ciw.Attributes = lpFill->Attributes;
2674 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2676 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2677 dwDestOrigin, &ciw);
2680 /******************************************************************
2681 * CONSOLE_FillLineUniform
2683 * Helper function for ScrollConsoleScreenBufferW
2684 * Fills a part of a line with a constant character info
2686 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2688 SERVER_START_REQ( fill_console_output )
2690 req->handle = console_handle_unmap(hConsoleOutput);
2691 req->mode = CHAR_INFO_MODE_TEXTATTR;
2696 req->data.ch = lpFill->Char.UnicodeChar;
2697 req->data.attr = lpFill->Attributes;
2698 wine_server_call_err( req );
2703 /******************************************************************************
2704 * ScrollConsoleScreenBufferW [KERNEL32.@]
2708 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2709 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2717 CONSOLE_SCREEN_BUFFER_INFO csbi;
2722 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2723 lpScrollRect->Left, lpScrollRect->Top,
2724 lpScrollRect->Right, lpScrollRect->Bottom,
2725 lpClipRect->Left, lpClipRect->Top,
2726 lpClipRect->Right, lpClipRect->Bottom,
2727 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2729 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2730 lpScrollRect->Left, lpScrollRect->Top,
2731 lpScrollRect->Right, lpScrollRect->Bottom,
2732 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2734 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2737 src.X = lpScrollRect->Left;
2738 src.Y = lpScrollRect->Top;
2740 /* step 1: get dst rect */
2741 dst.Left = dwDestOrigin.X;
2742 dst.Top = dwDestOrigin.Y;
2743 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2744 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2746 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2749 clip.Left = max(0, lpClipRect->Left);
2750 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2751 clip.Top = max(0, lpClipRect->Top);
2752 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2757 clip.Right = csbi.dwSize.X - 1;
2759 clip.Bottom = csbi.dwSize.Y - 1;
2761 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2763 /* step 2b: clip dst rect */
2764 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2765 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2766 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2767 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2769 /* step 3: transfer the bits */
2770 SERVER_START_REQ(move_console_output)
2772 req->handle = console_handle_unmap(hConsoleOutput);
2775 req->x_dst = dst.Left;
2776 req->y_dst = dst.Top;
2777 req->w = dst.Right - dst.Left + 1;
2778 req->h = dst.Bottom - dst.Top + 1;
2779 ret = !wine_server_call_err( req );
2783 if (!ret) return FALSE;
2785 /* step 4: clean out the exposed part */
2787 /* have to write cell [i,j] if it is not in dst rect (because it has already
2788 * been written to by the scroll) and is in clip (we shall not write
2791 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2793 inside = dst.Top <= j && j <= dst.Bottom;
2795 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2797 if (inside && dst.Left <= i && i <= dst.Right)
2801 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2807 if (start == -1) start = i;
2811 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2817 /******************************************************************
2818 * AttachConsole (KERNEL32.@)
2820 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2822 FIXME("stub %x\n",dwProcessId);
2826 /******************************************************************
2827 * GetConsoleDisplayMode (KERNEL32.@)
2829 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2831 TRACE("semi-stub: %p\n", lpModeFlags);
2832 /* It is safe to successfully report windowed mode */
2837 /******************************************************************
2838 * SetConsoleDisplayMode (KERNEL32.@)
2840 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2841 COORD *lpNewScreenBufferDimensions)
2843 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2844 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2847 /* We cannot switch to fullscreen */
2854 /* ====================================================================
2856 * Console manipulation functions
2858 * ====================================================================*/
2860 /* some missing functions...
2861 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2862 * should get the right API and implement them
2863 * GetConsoleCommandHistory[AW] (dword dword dword)
2864 * GetConsoleCommandHistoryLength[AW]
2865 * SetConsoleCommandHistoryMode
2866 * SetConsoleNumberOfCommands[AW]
2868 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2872 SERVER_START_REQ( get_console_input_history )
2876 if (buf && buf_len > 1)
2878 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2880 if (!wine_server_call_err( req ))
2882 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2883 len = reply->total / sizeof(WCHAR) + 1;
2890 /******************************************************************
2891 * CONSOLE_AppendHistory
2895 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2897 size_t len = strlenW(ptr);
2900 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2901 if (!len) return FALSE;
2903 SERVER_START_REQ( append_console_input_history )
2906 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2907 ret = !wine_server_call_err( req );
2913 /******************************************************************
2914 * CONSOLE_GetNumHistoryEntries
2918 unsigned CONSOLE_GetNumHistoryEntries(void)
2921 SERVER_START_REQ(get_console_input_info)
2924 if (!wine_server_call_err( req )) ret = reply->history_index;
2930 /******************************************************************
2931 * CONSOLE_GetEditionMode
2935 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2937 unsigned ret = FALSE;
2938 SERVER_START_REQ(get_console_input_info)
2940 req->handle = console_handle_unmap(hConIn);
2941 if ((ret = !wine_server_call_err( req )))
2942 *mode = reply->edition_mode;
2948 /******************************************************************
2953 * 0 if an error occurred, non-zero for success
2956 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
2957 DWORD TargetBufferLength, LPWSTR lpExename)
2959 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
2960 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2964 /******************************************************************
2965 * GetConsoleProcessList (KERNEL32.@)
2967 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
2969 FIXME("(%p,%d): stub\n", processlist, processcount);
2971 if (!processlist || processcount < 1)
2973 SetLastError(ERROR_INVALID_PARAMETER);
2980 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
2982 memset(&S_termios, 0, sizeof(S_termios));
2983 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
2987 /* FIXME: to be done even if program is a GUI ? */
2988 /* This is wine specific: we have no parent (we're started from unix)
2989 * so, create a simple console with bare handles
2991 wine_server_send_fd(0);
2992 SERVER_START_REQ( alloc_console )
2994 req->access = GENERIC_READ | GENERIC_WRITE;
2995 req->attributes = OBJ_INHERIT;
2996 req->pid = 0xffffffff;
2998 wine_server_call( req );
2999 conin = wine_server_ptr_handle( reply->handle_in );
3000 /* reply->event shouldn't be created by server */
3004 if (!params->hStdInput)
3005 params->hStdInput = conin;
3007 if (!params->hStdOutput)
3009 wine_server_send_fd(1);
3010 SERVER_START_REQ( create_console_output )
3012 req->handle_in = wine_server_obj_handle(conin);
3013 req->access = GENERIC_WRITE|GENERIC_READ;
3014 req->attributes = OBJ_INHERIT;
3015 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3017 wine_server_call(req);
3018 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3022 if (!params->hStdError)
3024 wine_server_send_fd(2);
3025 SERVER_START_REQ( create_console_output )
3027 req->handle_in = wine_server_obj_handle(conin);
3028 req->access = GENERIC_WRITE|GENERIC_READ;
3029 req->attributes = OBJ_INHERIT;
3030 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3032 wine_server_call(req);
3033 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3039 /* convert value from server:
3040 * + 0 => INVALID_HANDLE_VALUE
3041 * + console handle needs to be mapped
3043 if (!params->hStdInput)
3044 params->hStdInput = INVALID_HANDLE_VALUE;
3045 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3047 params->hStdInput = console_handle_map(params->hStdInput);
3048 save_console_mode(params->hStdInput);
3051 if (!params->hStdOutput)
3052 params->hStdOutput = INVALID_HANDLE_VALUE;
3053 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3054 params->hStdOutput = console_handle_map(params->hStdOutput);
3056 if (!params->hStdError)
3057 params->hStdError = INVALID_HANDLE_VALUE;
3058 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3059 params->hStdError = console_handle_map(params->hStdError);
3064 BOOL CONSOLE_Exit(void)
3066 /* the console is in raw mode, put it back in cooked mode */
3067 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));