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 BOOL get_console_mode(HANDLE conin, DWORD* mode, BOOL* bare)
138 SERVER_START_REQ( get_console_mode )
140 req->handle = console_handle_unmap(conin);
141 if ((ret = !wine_server_call_err( req )))
143 if (mode) *mode = reply->mode;
144 if (bare) *bare = reply->is_bare;
151 static struct termios S_termios; /* saved termios for bare consoles */
152 static BOOL S_termios_raw /* = FALSE */;
154 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
155 * - a bare console is created for all CUI programs started from command line (without
156 * wineconsole) (let's call those PS)
157 * - of course, every child of a PS which requires console inheritance will get it
158 * - the console termios attributes are saved at the start of program which is attached to be
160 * - if any program attached to a bare console requests input from console, the console is
161 * turned into raw mode
162 * - when the program which created the bare console (the program started from command line)
163 * exits, it will restore the console termios attributes it saved at startup (this
164 * will put back the console into cooked mode if it had been put in raw mode)
165 * - if any other program attached to this bare console is still alive, the Unix shell will put
166 * it in the background, hence forbidding access to the console. Therefore, reading console
167 * input will not be available when the bare console creator has died.
168 * FIXME: This is a limitation of current implementation
171 /* returns the fd for a bare console (-1 otherwise) */
172 static int get_console_bare_fd(HANDLE hin)
177 if (get_console_mode(hin, NULL, &is_bare) && is_bare &&
178 wine_server_handle_to_fd(hin, 0, &fd, NULL) == STATUS_SUCCESS)
183 static BOOL save_console_mode(HANDLE hin)
188 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
189 ret = tcgetattr(fd, &S_termios) >= 0;
194 static BOOL put_console_into_raw_mode(HANDLE hin)
198 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
200 RtlEnterCriticalSection(&CONSOLE_CritSect);
203 struct termios term = S_termios;
205 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
206 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
207 term.c_cflag &= ~(CSIZE | PARENB);
209 /* FIXME: we should actually disable output processing here
210 * and let kernel32/console.c do the job (with support of enable/disable of
213 /* term.c_oflag &= ~(OPOST); */
215 term.c_cc[VTIME] = 0;
216 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
218 RtlLeaveCriticalSection(&CONSOLE_CritSect);
221 return S_termios_raw;
224 /* put back the console in cooked mode iff we're the process which created the bare console
225 * we don't test if thie process has set the console in raw mode as it could be one of its
228 static BOOL restore_console_mode(HANDLE hin)
233 if (!S_termios_raw ||
234 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
236 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
237 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
242 /******************************************************************************
243 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
246 * Success: hwnd of the console window.
249 HWND WINAPI GetConsoleWindow(VOID)
253 SERVER_START_REQ(get_console_input_info)
256 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
264 /******************************************************************************
265 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
270 UINT WINAPI GetConsoleCP(VOID)
273 UINT codepage = GetOEMCP(); /* default value */
275 SERVER_START_REQ(get_console_input_info)
278 ret = !wine_server_call_err(req);
279 if (ret && reply->input_cp)
280 codepage = reply->input_cp;
288 /******************************************************************************
289 * SetConsoleCP [KERNEL32.@]
291 BOOL WINAPI SetConsoleCP(UINT cp)
295 if (!IsValidCodePage(cp))
297 SetLastError(ERROR_INVALID_PARAMETER);
301 SERVER_START_REQ(set_console_input_info)
304 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
306 ret = !wine_server_call_err(req);
314 /***********************************************************************
315 * GetConsoleOutputCP (KERNEL32.@)
317 UINT WINAPI GetConsoleOutputCP(VOID)
320 UINT codepage = GetOEMCP(); /* default value */
322 SERVER_START_REQ(get_console_input_info)
325 ret = !wine_server_call_err(req);
326 if (ret && reply->output_cp)
327 codepage = reply->output_cp;
335 /******************************************************************************
336 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
339 * cp [I] code page to set
345 BOOL WINAPI SetConsoleOutputCP(UINT cp)
349 if (!IsValidCodePage(cp))
351 SetLastError(ERROR_INVALID_PARAMETER);
355 SERVER_START_REQ(set_console_input_info)
358 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
360 ret = !wine_server_call_err(req);
368 /***********************************************************************
371 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
373 static const char beep = '\a';
374 /* dwFreq and dwDur are ignored by Win95 */
375 if (isatty(2)) write( 2, &beep, 1 );
380 /******************************************************************
381 * OpenConsoleW (KERNEL32.@)
384 * Open a handle to the current process console.
385 * Returns INVALID_HANDLE_VALUE on failure.
387 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
389 HANDLE output = INVALID_HANDLE_VALUE;
392 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
396 if (strcmpiW(coninW, name) == 0)
397 output = (HANDLE) FALSE;
398 else if (strcmpiW(conoutW, name) == 0)
399 output = (HANDLE) TRUE;
402 if (output == INVALID_HANDLE_VALUE)
404 SetLastError(ERROR_INVALID_PARAMETER);
405 return INVALID_HANDLE_VALUE;
407 else if (creation != OPEN_EXISTING)
409 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
410 SetLastError(ERROR_SHARING_VIOLATION);
412 SetLastError(ERROR_INVALID_PARAMETER);
413 return INVALID_HANDLE_VALUE;
416 SERVER_START_REQ( open_console )
418 req->from = wine_server_obj_handle( output );
419 req->access = access;
420 req->attributes = inherit ? OBJ_INHERIT : 0;
421 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
422 wine_server_call_err( req );
423 ret = wine_server_ptr_handle( reply->handle );
427 ret = console_handle_map(ret);
432 /******************************************************************
433 * VerifyConsoleIoHandle (KERNEL32.@)
437 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
441 if (!is_console_handle(handle)) return FALSE;
442 SERVER_START_REQ(get_console_mode)
444 req->handle = console_handle_unmap(handle);
445 ret = !wine_server_call( req );
451 /******************************************************************
452 * DuplicateConsoleHandle (KERNEL32.@)
456 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
461 if (!is_console_handle(handle) ||
462 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
463 GetCurrentProcess(), &ret, access, inherit, options))
464 return INVALID_HANDLE_VALUE;
465 return console_handle_map(ret);
468 /******************************************************************
469 * CloseConsoleHandle (KERNEL32.@)
473 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
475 if (!is_console_handle(handle))
477 SetLastError(ERROR_INVALID_PARAMETER);
480 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
483 /******************************************************************
484 * GetConsoleInputWaitHandle (KERNEL32.@)
488 HANDLE WINAPI GetConsoleInputWaitHandle(void)
490 if (!console_wait_event)
492 SERVER_START_REQ(get_console_wait_event)
494 if (!wine_server_call_err( req ))
495 console_wait_event = wine_server_ptr_handle( reply->handle );
499 return console_wait_event;
503 /******************************************************************************
504 * WriteConsoleInputA [KERNEL32.@]
506 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
507 DWORD count, LPDWORD written )
512 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
513 memcpy( recW, buffer, count*sizeof(*recW) );
514 input_records_AtoW( recW, count );
515 ret = WriteConsoleInputW( handle, recW, count, written );
516 HeapFree( GetProcessHeap(), 0, recW );
521 /******************************************************************************
522 * WriteConsoleInputW [KERNEL32.@]
524 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
525 DWORD count, LPDWORD written )
529 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
531 if (written) *written = 0;
532 SERVER_START_REQ( write_console_input )
534 req->handle = console_handle_unmap(handle);
535 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
536 if ((ret = !wine_server_call_err( req )) && written)
537 *written = reply->written;
545 /***********************************************************************
546 * WriteConsoleOutputA (KERNEL32.@)
548 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
549 COORD size, COORD coord, LPSMALL_RECT region )
553 COORD new_size, new_coord;
556 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
557 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
559 if (new_size.X <= 0 || new_size.Y <= 0)
561 region->Bottom = region->Top + new_size.Y - 1;
562 region->Right = region->Left + new_size.X - 1;
566 /* only copy the useful rectangle */
567 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
569 for (y = 0; y < new_size.Y; y++)
571 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
572 new_size.X * sizeof(CHAR_INFO) );
573 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
575 new_coord.X = new_coord.Y = 0;
576 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
577 HeapFree( GetProcessHeap(), 0, ciw );
582 /***********************************************************************
583 * WriteConsoleOutputW (KERNEL32.@)
585 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
586 COORD size, COORD coord, LPSMALL_RECT region )
588 int width, height, y;
591 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
592 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
593 region->Left, region->Top, region->Right, region->Bottom);
595 width = min( region->Right - region->Left + 1, size.X - coord.X );
596 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
598 if (width > 0 && height > 0)
600 for (y = 0; y < height; y++)
602 SERVER_START_REQ( write_console_output )
604 req->handle = console_handle_unmap(hConsoleOutput);
605 req->x = region->Left;
606 req->y = region->Top + y;
607 req->mode = CHAR_INFO_MODE_TEXTATTR;
609 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
610 width * sizeof(CHAR_INFO));
611 if ((ret = !wine_server_call_err( req )))
613 width = min( width, reply->width - region->Left );
614 height = min( height, reply->height - region->Top );
621 region->Bottom = region->Top + height - 1;
622 region->Right = region->Left + width - 1;
627 /******************************************************************************
628 * WriteConsoleOutputCharacterA [KERNEL32.@]
630 * See WriteConsoleOutputCharacterW.
632 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
633 COORD coord, LPDWORD lpNumCharsWritten )
639 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
640 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
642 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
644 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
646 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
647 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
649 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
650 HeapFree( GetProcessHeap(), 0, strW );
655 /******************************************************************************
656 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
657 * the console screen buffer
660 * hConsoleOutput [I] Handle to screen buffer
661 * attr [I] Pointer to buffer with write attributes
662 * length [I] Number of cells to write to
663 * coord [I] Coords of first cell
664 * lpNumAttrsWritten [O] Pointer to number of cells written
671 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
672 COORD coord, LPDWORD lpNumAttrsWritten )
676 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
678 SERVER_START_REQ( write_console_output )
680 req->handle = console_handle_unmap(hConsoleOutput);
683 req->mode = CHAR_INFO_MODE_ATTR;
685 wine_server_add_data( req, attr, length * sizeof(WORD) );
686 if ((ret = !wine_server_call_err( req )))
688 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
696 /******************************************************************************
697 * FillConsoleOutputCharacterA [KERNEL32.@]
699 * See FillConsoleOutputCharacterW.
701 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
702 COORD coord, LPDWORD lpNumCharsWritten )
706 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
707 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
711 /******************************************************************************
712 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
715 * hConsoleOutput [I] Handle to screen buffer
716 * ch [I] Character to write
717 * length [I] Number of cells to write to
718 * coord [I] Coords of first cell
719 * lpNumCharsWritten [O] Pointer to number of cells written
725 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
726 COORD coord, LPDWORD lpNumCharsWritten)
730 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
731 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
733 SERVER_START_REQ( fill_console_output )
735 req->handle = console_handle_unmap(hConsoleOutput);
738 req->mode = CHAR_INFO_MODE_TEXT;
742 if ((ret = !wine_server_call_err( req )))
744 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
752 /******************************************************************************
753 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
756 * hConsoleOutput [I] Handle to screen buffer
757 * attr [I] Color attribute to write
758 * length [I] Number of cells to write to
759 * coord [I] Coords of first cell
760 * lpNumAttrsWritten [O] Pointer to number of cells written
766 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
767 COORD coord, LPDWORD lpNumAttrsWritten )
771 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
772 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
774 SERVER_START_REQ( fill_console_output )
776 req->handle = console_handle_unmap(hConsoleOutput);
779 req->mode = CHAR_INFO_MODE_ATTR;
781 req->data.attr = attr;
783 if ((ret = !wine_server_call_err( req )))
785 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
793 /******************************************************************************
794 * ReadConsoleOutputCharacterA [KERNEL32.@]
797 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
798 COORD coord, LPDWORD read_count)
802 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
804 if (read_count) *read_count = 0;
805 if (!wptr) return FALSE;
807 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
809 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
810 if (read_count) *read_count = read;
812 HeapFree( GetProcessHeap(), 0, wptr );
817 /******************************************************************************
818 * ReadConsoleOutputCharacterW [KERNEL32.@]
821 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
822 COORD coord, LPDWORD read_count )
826 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
828 SERVER_START_REQ( read_console_output )
830 req->handle = console_handle_unmap(hConsoleOutput);
833 req->mode = CHAR_INFO_MODE_TEXT;
835 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
836 if ((ret = !wine_server_call_err( req )))
838 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
846 /******************************************************************************
847 * ReadConsoleOutputAttribute [KERNEL32.@]
849 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
850 COORD coord, LPDWORD read_count)
854 TRACE("(%p,%p,%d,%dx%d,%p)\n",
855 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
857 SERVER_START_REQ( read_console_output )
859 req->handle = console_handle_unmap(hConsoleOutput);
862 req->mode = CHAR_INFO_MODE_ATTR;
864 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
865 if ((ret = !wine_server_call_err( req )))
867 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
875 /******************************************************************************
876 * ReadConsoleOutputA [KERNEL32.@]
879 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
880 COORD coord, LPSMALL_RECT region )
885 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
886 if (ret && region->Right >= region->Left)
888 for (y = 0; y <= region->Bottom - region->Top; y++)
890 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
891 region->Right - region->Left + 1 );
898 /******************************************************************************
899 * ReadConsoleOutputW [KERNEL32.@]
901 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
902 * think we need to be *that* compatible. -- AJ
904 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
905 COORD coord, LPSMALL_RECT region )
907 int width, height, y;
910 width = min( region->Right - region->Left + 1, size.X - coord.X );
911 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
913 if (width > 0 && height > 0)
915 for (y = 0; y < height; y++)
917 SERVER_START_REQ( read_console_output )
919 req->handle = console_handle_unmap(hConsoleOutput);
920 req->x = region->Left;
921 req->y = region->Top + y;
922 req->mode = CHAR_INFO_MODE_TEXTATTR;
924 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
925 width * sizeof(CHAR_INFO) );
926 if ((ret = !wine_server_call_err( req )))
928 width = min( width, reply->width - region->Left );
929 height = min( height, reply->height - region->Top );
936 region->Bottom = region->Top + height - 1;
937 region->Right = region->Left + width - 1;
942 /******************************************************************************
943 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
946 * handle [I] Handle to console input buffer
947 * buffer [O] Address of buffer for read data
948 * count [I] Number of records to read
949 * pRead [O] Address of number of records read
955 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
959 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
960 input_records_WtoA( buffer, read );
961 if (pRead) *pRead = read;
966 /***********************************************************************
967 * PeekConsoleInputA (KERNEL32.@)
969 * Gets 'count' first events (or less) from input queue.
971 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
975 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
976 input_records_WtoA( buffer, read );
977 if (pRead) *pRead = read;
982 /***********************************************************************
983 * PeekConsoleInputW (KERNEL32.@)
985 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
988 SERVER_START_REQ( read_console_input )
990 req->handle = console_handle_unmap(handle);
992 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
993 if ((ret = !wine_server_call_err( req )))
995 if (read) *read = count ? reply->read : 0;
1003 /***********************************************************************
1004 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1006 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1009 SERVER_START_REQ( read_console_input )
1011 req->handle = console_handle_unmap(handle);
1013 if ((ret = !wine_server_call_err( req )))
1015 if (nrofevents) *nrofevents = reply->read;
1023 /******************************************************************************
1024 * read_console_input
1026 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1029 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1031 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1032 static const int vkkeyscan_table[256] =
1034 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,
1035 0,32,305,478,307,308,309,311,222,313,304,312,443,188,189,190,191,48,
1036 49,50,51,52,53,54,55,56,57,442,186,444,187,446,447,306,321,322,323,
1037 324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,
1038 341,342,343,344,345,346,219,220,221,310,445,192,65,66,67,68,69,70,71,
1039 72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,475,476,477,
1040 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,
1041 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,
1042 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,
1043 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
1046 static const int mapvkey_0[256] =
1048 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,
1049 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,
1050 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,
1051 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,
1052 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,
1053 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,
1054 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,
1055 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,
1056 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
1059 static inline void init_complex_char(INPUT_RECORD* ir, BOOL down, WORD vk, WORD kc, DWORD cks)
1061 ir->EventType = KEY_EVENT;
1062 ir->Event.KeyEvent.bKeyDown = down;
1063 ir->Event.KeyEvent.wRepeatCount = 1;
1064 ir->Event.KeyEvent.wVirtualScanCode = vk;
1065 ir->Event.KeyEvent.wVirtualKeyCode = kc;
1066 ir->Event.KeyEvent.dwControlKeyState = cks;
1067 ir->Event.KeyEvent.uChar.UnicodeChar = 0;
1070 /******************************************************************
1071 * handle_simple_char
1075 static BOOL handle_simple_char(HANDLE conin, unsigned real_inchar)
1080 unsigned numEvent = 0;
1081 DWORD cks = 0, written;
1084 switch (real_inchar)
1086 case 9: inchar = real_inchar;
1087 real_inchar = 27; /* so that we don't think key is ctrl- something */
1090 case 10: inchar = '\r';
1091 real_inchar = 27; /* Fixme: so that we don't think key is ctrl- something */
1093 case 127: inchar = '\b';
1096 inchar = real_inchar;
1099 if ((inchar & ~0xFF) != 0) FIXME("What a char (%u)\n", inchar);
1100 vk = vkkeyscan_table[inchar];
1102 init_complex_char(&ir[numEvent++], 1, 0x2a, 0x10, SHIFT_PRESSED);
1103 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1104 init_complex_char(&ir[numEvent++], 1, 0x1d, 0x11, LEFT_CTRL_PRESSED);
1106 init_complex_char(&ir[numEvent++], 1, 0x38, 0x12, LEFT_ALT_PRESSED);
1108 ir[numEvent].EventType = KEY_EVENT;
1109 ir[numEvent].Event.KeyEvent.bKeyDown = 1;
1110 ir[numEvent].Event.KeyEvent.wRepeatCount = 1;
1111 ir[numEvent].Event.KeyEvent.dwControlKeyState = cks;
1113 ir[numEvent].Event.KeyEvent.dwControlKeyState |= SHIFT_PRESSED;
1114 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1115 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_CTRL_PRESSED;
1117 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_ALT_PRESSED;
1118 ir[numEvent].Event.KeyEvent.wVirtualKeyCode = vk;
1119 ir[numEvent].Event.KeyEvent.wVirtualScanCode = mapvkey_0[vk & 0x00ff]; /* VirtualKeyCodes to ScanCode */
1122 MultiByteToWideChar(CP_UNIXCP, 0, &ch, 1, &ir[numEvent].Event.KeyEvent.uChar.UnicodeChar, 1);
1123 ir[numEvent + 1] = ir[numEvent];
1124 ir[numEvent + 1].Event.KeyEvent.bKeyDown = 0;
1129 init_complex_char(&ir[numEvent++], 0, 0x38, 0x12, LEFT_ALT_PRESSED);
1130 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1131 init_complex_char(&ir[numEvent++], 0, 0x1d, 0x11, 0);
1133 init_complex_char(&ir[numEvent++], 0, 0x2a, 0x10, 0);
1135 return WriteConsoleInputW(conin, ir, numEvent, &written);
1138 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, DWORD timeout)
1141 enum read_console_input_return ret;
1144 /* get the real handle to the console object */
1145 handle = wine_server_ptr_handle(console_handle_unmap(handle));
1147 memset(&ov, 0, sizeof(ov));
1148 ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1150 if (ReadFile(handle, &ch, 1, NULL, &ov) ||
1151 (GetLastError() == ERROR_IO_PENDING &&
1152 WaitForSingleObject(ov.hEvent, timeout) == WAIT_OBJECT_0 &&
1153 GetOverlappedResult(handle, &ov, NULL, FALSE)))
1155 ret = handle_simple_char(handle, ch) ? rci_gotone : rci_error;
1159 WARN("Failed read %x\n", GetLastError());
1162 CloseHandle(ov.hEvent);
1167 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1170 enum read_console_input_return ret;
1172 if (!get_console_mode(handle, NULL, &bare)) return rci_error;
1176 put_console_into_raw_mode(handle);
1177 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1179 ret = bare_console_fetch_input(handle, timeout);
1180 if (ret != rci_gotone) return ret;
1185 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1189 SERVER_START_REQ( read_console_input )
1191 req->handle = console_handle_unmap(handle);
1193 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1194 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1195 else ret = rci_gotone;
1203 /***********************************************************************
1204 * FlushConsoleInputBuffer (KERNEL32.@)
1206 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1208 enum read_console_input_return last;
1211 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1213 return last == rci_timeout;
1217 /***********************************************************************
1218 * SetConsoleTitleA (KERNEL32.@)
1220 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1225 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1226 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1227 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1228 ret = SetConsoleTitleW(titleW);
1229 HeapFree(GetProcessHeap(), 0, titleW);
1234 /***********************************************************************
1235 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1237 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1239 FIXME( "stub %p\n", layoutName);
1243 /***********************************************************************
1244 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1246 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1248 FIXME( "stub %p\n", layoutName);
1252 static WCHAR input_exe[MAX_PATH + 1];
1254 /***********************************************************************
1255 * GetConsoleInputExeNameW (KERNEL32.@)
1257 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1259 TRACE("%u %p\n", buflen, buffer);
1261 RtlEnterCriticalSection(&CONSOLE_CritSect);
1262 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1263 else SetLastError(ERROR_BUFFER_OVERFLOW);
1264 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1269 /***********************************************************************
1270 * GetConsoleInputExeNameA (KERNEL32.@)
1272 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1274 TRACE("%u %p\n", buflen, buffer);
1276 RtlEnterCriticalSection(&CONSOLE_CritSect);
1277 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1278 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1279 else SetLastError(ERROR_BUFFER_OVERFLOW);
1280 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1285 /***********************************************************************
1286 * GetConsoleTitleA (KERNEL32.@)
1288 * See GetConsoleTitleW.
1290 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1292 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1296 ret = GetConsoleTitleW( ptr, size );
1299 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1300 ret = strlen(title);
1302 HeapFree(GetProcessHeap(), 0, ptr);
1307 /******************************************************************************
1308 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1311 * title [O] Address of buffer for title
1312 * size [I] Size of buffer
1315 * Success: Length of string copied
1318 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1322 SERVER_START_REQ( get_console_input_info )
1325 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1326 if (!wine_server_call_err( req ))
1328 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1337 /***********************************************************************
1338 * GetLargestConsoleWindowSize (KERNEL32.@)
1341 * This should return a COORD, but calling convention for returning
1342 * structures is different between Windows and gcc on i386.
1347 #undef GetLargestConsoleWindowSize
1348 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1356 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1359 #endif /* defined(__i386__) */
1362 /***********************************************************************
1363 * GetLargestConsoleWindowSize (KERNEL32.@)
1366 * This should return a COORD, but calling convention for returning
1367 * structures is different between Windows and gcc on i386.
1372 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1377 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1380 #endif /* defined(__i386__) */
1382 static WCHAR* S_EditString /* = NULL */;
1383 static unsigned S_EditStrPos /* = 0 */;
1385 /***********************************************************************
1386 * FreeConsole (KERNEL32.@)
1388 BOOL WINAPI FreeConsole(VOID)
1392 /* invalidate local copy of input event handle */
1393 console_wait_event = 0;
1395 SERVER_START_REQ(free_console)
1397 ret = !wine_server_call_err( req );
1403 /******************************************************************
1404 * start_console_renderer
1406 * helper for AllocConsole
1407 * starts the renderer process
1409 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1414 PROCESS_INFORMATION pi;
1416 /* FIXME: use dynamic allocation for most of the buffers below */
1417 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1418 if ((ret > -1) && (ret < sizeof(buffer)) &&
1419 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1420 NULL, NULL, si, &pi))
1426 wh[1] = pi.hProcess;
1427 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1429 CloseHandle(pi.hThread);
1430 CloseHandle(pi.hProcess);
1432 if (ret != WAIT_OBJECT_0) return FALSE;
1434 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1435 pi.dwProcessId, pi.dwThreadId);
1442 static BOOL start_console_renderer(STARTUPINFOA* si)
1446 OBJECT_ATTRIBUTES attr;
1449 attr.Length = sizeof(attr);
1450 attr.RootDirectory = 0;
1451 attr.Attributes = OBJ_INHERIT;
1452 attr.ObjectName = NULL;
1453 attr.SecurityDescriptor = NULL;
1454 attr.SecurityQualityOfService = NULL;
1456 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1457 if (!hEvent) return FALSE;
1459 /* first try environment variable */
1460 if ((p = getenv("WINECONSOLE")) != NULL)
1462 ret = start_console_renderer_helper(p, si, hEvent);
1464 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1465 "trying default access\n", p);
1468 /* then try the regular PATH */
1470 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1472 CloseHandle(hEvent);
1476 /***********************************************************************
1477 * AllocConsole (KERNEL32.@)
1479 * creates an xterm with a pty to our program
1481 BOOL WINAPI AllocConsole(void)
1483 HANDLE handle_in = INVALID_HANDLE_VALUE;
1484 HANDLE handle_out = INVALID_HANDLE_VALUE;
1485 HANDLE handle_err = INVALID_HANDLE_VALUE;
1486 STARTUPINFOA siCurrent;
1487 STARTUPINFOA siConsole;
1492 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1493 FALSE, OPEN_EXISTING );
1495 if (VerifyConsoleIoHandle(handle_in))
1497 /* we already have a console opened on this process, don't create a new one */
1498 CloseHandle(handle_in);
1502 /* invalidate local copy of input event handle */
1503 console_wait_event = 0;
1505 GetStartupInfoA(&siCurrent);
1507 memset(&siConsole, 0, sizeof(siConsole));
1508 siConsole.cb = sizeof(siConsole);
1509 /* setup a view arguments for wineconsole (it'll use them as default values) */
1510 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1512 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1513 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1514 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1516 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1518 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1519 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1521 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1523 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1524 siConsole.wShowWindow = siCurrent.wShowWindow;
1526 /* FIXME (should pass the unicode form) */
1527 if (siCurrent.lpTitle)
1528 siConsole.lpTitle = siCurrent.lpTitle;
1529 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1531 buffer[sizeof(buffer) - 1] = '\0';
1532 siConsole.lpTitle = buffer;
1535 if (!start_console_renderer(&siConsole))
1538 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1539 /* all std I/O handles are inheritable by default */
1540 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1541 TRUE, OPEN_EXISTING );
1542 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1544 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1545 TRUE, OPEN_EXISTING );
1546 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1548 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1549 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1552 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1553 handle_in = siCurrent.hStdInput;
1554 handle_out = siCurrent.hStdOutput;
1555 handle_err = siCurrent.hStdError;
1558 /* NT resets the STD_*_HANDLEs on console alloc */
1559 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1560 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1561 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1563 SetLastError(ERROR_SUCCESS);
1568 ERR("Can't allocate console\n");
1569 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1570 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1571 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1577 /***********************************************************************
1578 * ReadConsoleA (KERNEL32.@)
1580 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1581 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1583 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1587 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1588 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1590 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1591 HeapFree(GetProcessHeap(), 0, ptr);
1596 /***********************************************************************
1597 * ReadConsoleW (KERNEL32.@)
1599 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1600 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1603 LPWSTR xbuf = lpBuffer;
1607 TRACE("(%p,%p,%d,%p,%p)\n",
1608 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1610 if (!get_console_mode(hConsoleInput, &mode, &is_bare))
1613 if (mode & ENABLE_LINE_INPUT)
1615 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1617 HeapFree(GetProcessHeap(), 0, S_EditString);
1618 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1622 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1623 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1624 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1625 S_EditStrPos += charsread;
1630 DWORD timeout = INFINITE;
1632 /* FIXME: should we read at least 1 char? The SDK does not say */
1633 /* wait for at least one available input record (it doesn't mean we'll have
1634 * chars stored in xbuf...)
1636 * Although SDK doc keeps silence about 1 char, SDK examples assume
1637 * that we should wait for at least one character (not key). --KS
1642 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1643 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1644 ir.Event.KeyEvent.uChar.UnicodeChar)
1646 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1649 } while (charsread < nNumberOfCharsToRead);
1650 /* nothing has been read */
1651 if (timeout == INFINITE) return FALSE;
1654 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1660 /***********************************************************************
1661 * ReadConsoleInputW (KERNEL32.@)
1663 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1664 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1667 DWORD timeout = INFINITE;
1671 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1675 /* loop until we get at least one event */
1676 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1680 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1685 /******************************************************************************
1686 * WriteConsoleOutputCharacterW [KERNEL32.@]
1688 * Copy character to consecutive cells in the console screen buffer.
1691 * hConsoleOutput [I] Handle to screen buffer
1692 * str [I] Pointer to buffer with chars to write
1693 * length [I] Number of cells to write to
1694 * coord [I] Coords of first cell
1695 * lpNumCharsWritten [O] Pointer to number of cells written
1702 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1703 COORD coord, LPDWORD lpNumCharsWritten )
1707 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1708 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1710 SERVER_START_REQ( write_console_output )
1712 req->handle = console_handle_unmap(hConsoleOutput);
1715 req->mode = CHAR_INFO_MODE_TEXT;
1717 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1718 if ((ret = !wine_server_call_err( req )))
1720 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1728 /******************************************************************************
1729 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1732 * title [I] Address of new title
1738 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1742 TRACE("(%s)\n", debugstr_w(title));
1743 SERVER_START_REQ( set_console_input_info )
1746 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1747 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1748 ret = !wine_server_call_err( req );
1755 /***********************************************************************
1756 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1758 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1760 FIXME("(%p): stub\n", nrofbuttons);
1765 /******************************************************************************
1766 * SetConsoleInputExeNameW [KERNEL32.@]
1768 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1770 TRACE("(%s)\n", debugstr_w(name));
1772 if (!name || !name[0])
1774 SetLastError(ERROR_INVALID_PARAMETER);
1778 RtlEnterCriticalSection(&CONSOLE_CritSect);
1779 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1780 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1785 /******************************************************************************
1786 * SetConsoleInputExeNameA [KERNEL32.@]
1788 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1794 if (!name || !name[0])
1796 SetLastError(ERROR_INVALID_PARAMETER);
1800 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1801 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1803 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1804 ret = SetConsoleInputExeNameW(nameW);
1805 HeapFree(GetProcessHeap(), 0, nameW);
1810 /******************************************************************
1811 * CONSOLE_DefaultHandler
1813 * Final control event handler
1815 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1817 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1819 /* should never go here */
1823 /******************************************************************************
1824 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1827 * func [I] Address of handler function
1828 * add [I] Handler to add or remove
1835 struct ConsoleHandler
1837 PHANDLER_ROUTINE handler;
1838 struct ConsoleHandler* next;
1841 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1842 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1844 /*****************************************************************************/
1846 /******************************************************************
1847 * SetConsoleCtrlHandler (KERNEL32.@)
1849 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1853 TRACE("(%p,%i)\n", func, add);
1857 RtlEnterCriticalSection(&CONSOLE_CritSect);
1859 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1861 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1862 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1866 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1868 if (!ch) return FALSE;
1870 RtlEnterCriticalSection(&CONSOLE_CritSect);
1871 ch->next = CONSOLE_Handlers;
1872 CONSOLE_Handlers = ch;
1873 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1877 struct ConsoleHandler** ch;
1878 RtlEnterCriticalSection(&CONSOLE_CritSect);
1879 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1881 if ((*ch)->handler == func) break;
1885 struct ConsoleHandler* rch = *ch;
1888 if (rch == &CONSOLE_DefaultConsoleHandler)
1890 ERR("Who's trying to remove default handler???\n");
1891 SetLastError(ERROR_INVALID_PARAMETER);
1897 HeapFree(GetProcessHeap(), 0, rch);
1902 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1903 SetLastError(ERROR_INVALID_PARAMETER);
1906 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1911 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1913 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1914 return EXCEPTION_EXECUTE_HANDLER;
1917 /******************************************************************
1918 * CONSOLE_SendEventThread
1920 * Internal helper to pass an event to the list on installed handlers
1922 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1924 DWORD_PTR event = (DWORD_PTR)pmt;
1925 struct ConsoleHandler* ch;
1927 if (event == CTRL_C_EVENT)
1929 BOOL caught_by_dbg = TRUE;
1930 /* First, try to pass the ctrl-C event to the debugger (if any)
1931 * If it continues, there's nothing more to do
1932 * Otherwise, we need to send the ctrl-C event to the handlers
1936 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1938 __EXCEPT(CONSOLE_CtrlEventHandler)
1940 caught_by_dbg = FALSE;
1943 if (caught_by_dbg) return 0;
1944 /* the debugger didn't continue... so, pass to ctrl handlers */
1946 RtlEnterCriticalSection(&CONSOLE_CritSect);
1947 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1949 if (ch->handler(event)) break;
1951 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1955 /******************************************************************
1956 * CONSOLE_HandleCtrlC
1958 * Check whether the shall manipulate CtrlC events
1960 int CONSOLE_HandleCtrlC(unsigned sig)
1962 /* FIXME: better test whether a console is attached to this process ??? */
1963 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1964 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1966 /* check if we have to ignore ctrl-C events */
1967 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1969 /* Create a separate thread to signal all the events.
1970 * This is needed because:
1971 * - this function can be called in an Unix signal handler (hence on an
1972 * different stack than the thread that's running). This breaks the
1973 * Win32 exception mechanisms (where the thread's stack is checked).
1974 * - since the current thread, while processing the signal, can hold the
1975 * console critical section, we need another execution environment where
1976 * we can wait on this critical section
1978 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1983 /******************************************************************************
1984 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1987 * dwCtrlEvent [I] Type of event
1988 * dwProcessGroupID [I] Process group ID to send event to
1992 * Failure: False (and *should* [but doesn't] set LastError)
1994 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1995 DWORD dwProcessGroupID)
1999 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2001 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2003 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2007 SERVER_START_REQ( send_console_signal )
2009 req->signal = dwCtrlEvent;
2010 req->group_id = dwProcessGroupID;
2011 ret = !wine_server_call_err( req );
2015 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2016 * have been handled by all processes in the given group?
2017 * As of today, we don't wait...
2023 /******************************************************************************
2024 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2027 * dwDesiredAccess [I] Access flag
2028 * dwShareMode [I] Buffer share mode
2029 * sa [I] Security attributes
2030 * dwFlags [I] Type of buffer to create
2031 * lpScreenBufferData [I] Reserved
2034 * Should call SetLastError
2037 * Success: Handle to new console screen buffer
2038 * Failure: INVALID_HANDLE_VALUE
2040 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2041 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2042 LPVOID lpScreenBufferData)
2044 HANDLE ret = INVALID_HANDLE_VALUE;
2046 TRACE("(%d,%d,%p,%d,%p)\n",
2047 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2049 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2051 SetLastError(ERROR_INVALID_PARAMETER);
2052 return INVALID_HANDLE_VALUE;
2055 SERVER_START_REQ(create_console_output)
2058 req->access = dwDesiredAccess;
2059 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2060 req->share = dwShareMode;
2062 if (!wine_server_call_err( req ))
2063 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2071 /***********************************************************************
2072 * GetConsoleScreenBufferInfo (KERNEL32.@)
2074 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2078 SERVER_START_REQ(get_console_output_info)
2080 req->handle = console_handle_unmap(hConsoleOutput);
2081 if ((ret = !wine_server_call_err( req )))
2083 csbi->dwSize.X = reply->width;
2084 csbi->dwSize.Y = reply->height;
2085 csbi->dwCursorPosition.X = reply->cursor_x;
2086 csbi->dwCursorPosition.Y = reply->cursor_y;
2087 csbi->wAttributes = reply->attr;
2088 csbi->srWindow.Left = reply->win_left;
2089 csbi->srWindow.Right = reply->win_right;
2090 csbi->srWindow.Top = reply->win_top;
2091 csbi->srWindow.Bottom = reply->win_bottom;
2092 csbi->dwMaximumWindowSize.X = reply->max_width;
2093 csbi->dwMaximumWindowSize.Y = reply->max_height;
2098 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2099 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2100 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2102 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2103 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2109 /******************************************************************************
2110 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2116 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2120 TRACE("(%p)\n", hConsoleOutput);
2122 SERVER_START_REQ( set_console_input_info )
2125 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2126 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2127 ret = !wine_server_call_err( req );
2134 /***********************************************************************
2135 * GetConsoleMode (KERNEL32.@)
2137 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2139 return get_console_mode(hcon, mode, NULL);
2143 /******************************************************************************
2144 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2147 * hcon [I] Handle to console input or screen buffer
2148 * mode [I] Input or output mode to set
2155 * ENABLE_PROCESSED_INPUT 0x01
2156 * ENABLE_LINE_INPUT 0x02
2157 * ENABLE_ECHO_INPUT 0x04
2158 * ENABLE_WINDOW_INPUT 0x08
2159 * ENABLE_MOUSE_INPUT 0x10
2161 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2165 SERVER_START_REQ(set_console_mode)
2167 req->handle = console_handle_unmap(hcon);
2169 ret = !wine_server_call_err( req );
2172 /* FIXME: when resetting a console input to editline mode, I think we should
2173 * empty the S_EditString buffer
2176 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2182 /******************************************************************
2183 * CONSOLE_WriteChars
2185 * WriteConsoleOutput helper: hides server call semantics
2186 * writes a string at a given pos with standard attribute
2188 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2194 SERVER_START_REQ( write_console_output )
2196 req->handle = console_handle_unmap(hCon);
2199 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2201 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2202 if (!wine_server_call_err( req )) written = reply->written;
2206 if (written > 0) pos->X += written;
2210 /******************************************************************
2213 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2216 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2222 csbi->dwCursorPosition.X = 0;
2223 csbi->dwCursorPosition.Y++;
2225 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2228 src.Bottom = csbi->dwSize.Y - 1;
2230 src.Right = csbi->dwSize.X - 1;
2235 ci.Attributes = csbi->wAttributes;
2236 ci.Char.UnicodeChar = ' ';
2238 csbi->dwCursorPosition.Y--;
2239 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2244 /******************************************************************
2247 * WriteConsoleOutput helper: writes a block of non special characters
2248 * Block can spread on several lines, and wrapping, if needed, is
2252 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2253 DWORD mode, LPCWSTR ptr, int len)
2255 int blk; /* number of chars to write on current line */
2256 int done; /* number of chars already written */
2258 if (len <= 0) return 1;
2260 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2262 for (done = 0; done < len; done += blk)
2264 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2266 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2268 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2274 int pos = csbi->dwCursorPosition.X;
2275 /* FIXME: we could reduce the number of loops
2276 * but, in most cases we wouldn't gain lots of time (it would only
2277 * happen if we're asked to overwrite more than twice the part of the line,
2280 for (done = 0; done < len; done += blk)
2282 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2284 csbi->dwCursorPosition.X = pos;
2285 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2293 /***********************************************************************
2294 * WriteConsoleW (KERNEL32.@)
2296 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2297 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2301 const WCHAR* psz = lpBuffer;
2302 CONSOLE_SCREEN_BUFFER_INFO csbi;
2306 TRACE("%p %s %d %p %p\n",
2307 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2308 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2310 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2312 if (!get_console_mode(hConsoleOutput, &mode, &bare)) return FALSE;
2320 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2323 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2324 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2327 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2328 ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2329 ptr, len, lpNumberOfCharsWritten, NULL);
2330 if (ret && lpNumberOfCharsWritten)
2332 if (*lpNumberOfCharsWritten == len)
2333 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2335 FIXME("Conversion not supported yet\n");
2337 HeapFree(GetProcessHeap(), 0, ptr);
2341 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2344 if (!nNumberOfCharsToWrite) return TRUE;
2346 if (mode & ENABLE_PROCESSED_OUTPUT)
2350 for (i = 0; i < nNumberOfCharsToWrite; i++)
2354 case '\b': case '\t': case '\n': case '\a': case '\r':
2355 /* don't handle here the i-th char... done below */
2356 if ((k = i - first) > 0)
2358 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2368 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2372 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2374 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2375 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2380 next_line(hConsoleOutput, &csbi);
2386 csbi.dwCursorPosition.X = 0;
2394 /* write the remaining block (if any) if processed output is enabled, or the
2395 * entire buffer otherwise
2397 if ((k = nNumberOfCharsToWrite - first) > 0)
2399 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2405 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2406 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2411 /***********************************************************************
2412 * WriteConsoleA (KERNEL32.@)
2414 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2415 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2421 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2423 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2424 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2425 if (!xstring) return 0;
2427 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2429 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2431 HeapFree(GetProcessHeap(), 0, xstring);
2436 /******************************************************************************
2437 * SetConsoleCursorPosition [KERNEL32.@]
2438 * Sets the cursor position in console
2441 * hConsoleOutput [I] Handle of console screen buffer
2442 * dwCursorPosition [I] New cursor position coordinates
2448 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2451 CONSOLE_SCREEN_BUFFER_INFO csbi;
2455 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2457 SERVER_START_REQ(set_console_output_info)
2459 req->handle = console_handle_unmap(hcon);
2460 req->cursor_x = pos.X;
2461 req->cursor_y = pos.Y;
2462 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2463 ret = !wine_server_call_err( req );
2467 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2470 /* if cursor is no longer visible, scroll the visible window... */
2471 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2472 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2473 if (pos.X < csbi.srWindow.Left)
2475 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2478 else if (pos.X > csbi.srWindow.Right)
2480 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2483 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2485 if (pos.Y < csbi.srWindow.Top)
2487 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2490 else if (pos.Y > csbi.srWindow.Bottom)
2492 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2495 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2497 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2502 /******************************************************************************
2503 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2506 * hcon [I] Handle to console screen buffer
2507 * cinfo [O] Address of cursor information
2513 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2517 SERVER_START_REQ(get_console_output_info)
2519 req->handle = console_handle_unmap(hCon);
2520 ret = !wine_server_call_err( req );
2523 cinfo->dwSize = reply->cursor_size;
2524 cinfo->bVisible = reply->cursor_visible;
2529 if (!ret) return FALSE;
2533 SetLastError(ERROR_INVALID_ACCESS);
2536 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2542 /******************************************************************************
2543 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2546 * hcon [I] Handle to console screen buffer
2547 * cinfo [I] Address of cursor information
2552 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2556 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2557 SERVER_START_REQ(set_console_output_info)
2559 req->handle = console_handle_unmap(hCon);
2560 req->cursor_size = cinfo->dwSize;
2561 req->cursor_visible = cinfo->bVisible;
2562 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2563 ret = !wine_server_call_err( req );
2570 /******************************************************************************
2571 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2574 * hcon [I] Handle to console screen buffer
2575 * bAbsolute [I] Coordinate type flag
2576 * window [I] Address of new window rectangle
2581 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2583 SMALL_RECT p = *window;
2586 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2590 CONSOLE_SCREEN_BUFFER_INFO csbi;
2592 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2594 p.Left += csbi.srWindow.Left;
2595 p.Top += csbi.srWindow.Top;
2596 p.Right += csbi.srWindow.Right;
2597 p.Bottom += csbi.srWindow.Bottom;
2599 SERVER_START_REQ(set_console_output_info)
2601 req->handle = console_handle_unmap(hCon);
2602 req->win_left = p.Left;
2603 req->win_top = p.Top;
2604 req->win_right = p.Right;
2605 req->win_bottom = p.Bottom;
2606 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2607 ret = !wine_server_call_err( req );
2615 /******************************************************************************
2616 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2618 * Sets the foreground and background color attributes of characters
2619 * written to the screen buffer.
2625 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2629 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2630 SERVER_START_REQ(set_console_output_info)
2632 req->handle = console_handle_unmap(hConsoleOutput);
2634 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2635 ret = !wine_server_call_err( req );
2642 /******************************************************************************
2643 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2646 * hConsoleOutput [I] Handle to console screen buffer
2647 * dwSize [I] New size in character rows and cols
2653 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2657 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2658 SERVER_START_REQ(set_console_output_info)
2660 req->handle = console_handle_unmap(hConsoleOutput);
2661 req->width = dwSize.X;
2662 req->height = dwSize.Y;
2663 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2664 ret = !wine_server_call_err( req );
2671 /******************************************************************************
2672 * ScrollConsoleScreenBufferA [KERNEL32.@]
2675 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2676 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2681 ciw.Attributes = lpFill->Attributes;
2682 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2684 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2685 dwDestOrigin, &ciw);
2688 /******************************************************************
2689 * CONSOLE_FillLineUniform
2691 * Helper function for ScrollConsoleScreenBufferW
2692 * Fills a part of a line with a constant character info
2694 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2696 SERVER_START_REQ( fill_console_output )
2698 req->handle = console_handle_unmap(hConsoleOutput);
2699 req->mode = CHAR_INFO_MODE_TEXTATTR;
2704 req->data.ch = lpFill->Char.UnicodeChar;
2705 req->data.attr = lpFill->Attributes;
2706 wine_server_call_err( req );
2711 /******************************************************************************
2712 * ScrollConsoleScreenBufferW [KERNEL32.@]
2716 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2717 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2725 CONSOLE_SCREEN_BUFFER_INFO csbi;
2730 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2731 lpScrollRect->Left, lpScrollRect->Top,
2732 lpScrollRect->Right, lpScrollRect->Bottom,
2733 lpClipRect->Left, lpClipRect->Top,
2734 lpClipRect->Right, lpClipRect->Bottom,
2735 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2737 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2738 lpScrollRect->Left, lpScrollRect->Top,
2739 lpScrollRect->Right, lpScrollRect->Bottom,
2740 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2742 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2745 src.X = lpScrollRect->Left;
2746 src.Y = lpScrollRect->Top;
2748 /* step 1: get dst rect */
2749 dst.Left = dwDestOrigin.X;
2750 dst.Top = dwDestOrigin.Y;
2751 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2752 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2754 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2757 clip.Left = max(0, lpClipRect->Left);
2758 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2759 clip.Top = max(0, lpClipRect->Top);
2760 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2765 clip.Right = csbi.dwSize.X - 1;
2767 clip.Bottom = csbi.dwSize.Y - 1;
2769 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2771 /* step 2b: clip dst rect */
2772 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2773 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2774 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2775 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2777 /* step 3: transfer the bits */
2778 SERVER_START_REQ(move_console_output)
2780 req->handle = console_handle_unmap(hConsoleOutput);
2783 req->x_dst = dst.Left;
2784 req->y_dst = dst.Top;
2785 req->w = dst.Right - dst.Left + 1;
2786 req->h = dst.Bottom - dst.Top + 1;
2787 ret = !wine_server_call_err( req );
2791 if (!ret) return FALSE;
2793 /* step 4: clean out the exposed part */
2795 /* have to write cell [i,j] if it is not in dst rect (because it has already
2796 * been written to by the scroll) and is in clip (we shall not write
2799 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2801 inside = dst.Top <= j && j <= dst.Bottom;
2803 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2805 if (inside && dst.Left <= i && i <= dst.Right)
2809 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2815 if (start == -1) start = i;
2819 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2825 /******************************************************************
2826 * AttachConsole (KERNEL32.@)
2828 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2830 FIXME("stub %x\n",dwProcessId);
2834 /******************************************************************
2835 * GetConsoleDisplayMode (KERNEL32.@)
2837 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2839 TRACE("semi-stub: %p\n", lpModeFlags);
2840 /* It is safe to successfully report windowed mode */
2845 /******************************************************************
2846 * SetConsoleDisplayMode (KERNEL32.@)
2848 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2849 COORD *lpNewScreenBufferDimensions)
2851 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2852 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2855 /* We cannot switch to fullscreen */
2862 /* ====================================================================
2864 * Console manipulation functions
2866 * ====================================================================*/
2868 /* some missing functions...
2869 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2870 * should get the right API and implement them
2871 * GetConsoleCommandHistory[AW] (dword dword dword)
2872 * GetConsoleCommandHistoryLength[AW]
2873 * SetConsoleCommandHistoryMode
2874 * SetConsoleNumberOfCommands[AW]
2876 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2880 SERVER_START_REQ( get_console_input_history )
2884 if (buf && buf_len > 1)
2886 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2888 if (!wine_server_call_err( req ))
2890 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2891 len = reply->total / sizeof(WCHAR) + 1;
2898 /******************************************************************
2899 * CONSOLE_AppendHistory
2903 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2905 size_t len = strlenW(ptr);
2908 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2909 if (!len) return FALSE;
2911 SERVER_START_REQ( append_console_input_history )
2914 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2915 ret = !wine_server_call_err( req );
2921 /******************************************************************
2922 * CONSOLE_GetNumHistoryEntries
2926 unsigned CONSOLE_GetNumHistoryEntries(void)
2929 SERVER_START_REQ(get_console_input_info)
2932 if (!wine_server_call_err( req )) ret = reply->history_index;
2938 /******************************************************************
2939 * CONSOLE_GetEditionMode
2943 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2945 unsigned ret = FALSE;
2946 SERVER_START_REQ(get_console_input_info)
2948 req->handle = console_handle_unmap(hConIn);
2949 if ((ret = !wine_server_call_err( req )))
2950 *mode = reply->edition_mode;
2956 /******************************************************************
2961 * 0 if an error occurred, non-zero for success
2964 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
2965 DWORD TargetBufferLength, LPWSTR lpExename)
2967 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
2968 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2972 /******************************************************************
2973 * GetConsoleProcessList (KERNEL32.@)
2975 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
2977 FIXME("(%p,%d): stub\n", processlist, processcount);
2979 if (!processlist || processcount < 1)
2981 SetLastError(ERROR_INVALID_PARAMETER);
2988 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
2990 memset(&S_termios, 0, sizeof(S_termios));
2991 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
2995 /* FIXME: to be done even if program is a GUI ? */
2996 /* This is wine specific: we have no parent (we're started from unix)
2997 * so, create a simple console with bare handles
2999 wine_server_send_fd(0);
3000 SERVER_START_REQ( alloc_console )
3002 req->access = GENERIC_READ | GENERIC_WRITE;
3003 req->attributes = OBJ_INHERIT;
3004 req->pid = 0xffffffff;
3006 wine_server_call( req );
3007 conin = wine_server_ptr_handle( reply->handle_in );
3008 /* reply->event shouldn't be created by server */
3012 if (!params->hStdInput)
3013 params->hStdInput = conin;
3015 if (!params->hStdOutput)
3017 wine_server_send_fd(1);
3018 SERVER_START_REQ( create_console_output )
3020 req->handle_in = wine_server_obj_handle(conin);
3021 req->access = GENERIC_WRITE|GENERIC_READ;
3022 req->attributes = OBJ_INHERIT;
3023 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3025 wine_server_call(req);
3026 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3030 if (!params->hStdError)
3032 wine_server_send_fd(2);
3033 SERVER_START_REQ( create_console_output )
3035 req->handle_in = wine_server_obj_handle(conin);
3036 req->access = GENERIC_WRITE|GENERIC_READ;
3037 req->attributes = OBJ_INHERIT;
3038 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3040 wine_server_call(req);
3041 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3047 /* convert value from server:
3048 * + 0 => INVALID_HANDLE_VALUE
3049 * + console handle needs to be mapped
3051 if (!params->hStdInput)
3052 params->hStdInput = INVALID_HANDLE_VALUE;
3053 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3055 params->hStdInput = console_handle_map(params->hStdInput);
3056 save_console_mode(params->hStdInput);
3059 if (!params->hStdOutput)
3060 params->hStdOutput = INVALID_HANDLE_VALUE;
3061 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3062 params->hStdOutput = console_handle_map(params->hStdOutput);
3064 if (!params->hStdError)
3065 params->hStdError = INVALID_HANDLE_VALUE;
3066 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3067 params->hStdError = console_handle_map(params->hStdError);
3072 BOOL CONSOLE_Exit(void)
3074 /* the console is in raw mode, put it back in cooked mode */
3075 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));