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,2010 Eric Pouech
9 * Copyright 2001 Alexandre Julliard
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 /* Reference applications:
27 * - IDA (interactive disassembler) full version 3.75. Works.
28 * - LYNX/W32. Works mostly, some keys crash it.
32 #include "wine/port.h"
44 #ifdef HAVE_SYS_POLL_H
45 # include <sys/poll.h>
48 #define NONAMELESSUNION
50 #define WIN32_NO_STATUS
56 #include "wine/server.h"
57 #include "wine/exception.h"
58 #include "wine/unicode.h"
59 #include "wine/debug.h"
61 #include "console_private.h"
62 #include "kernel_private.h"
64 WINE_DEFAULT_DEBUG_CHANNEL(console);
66 static CRITICAL_SECTION CONSOLE_CritSect;
67 static CRITICAL_SECTION_DEBUG critsect_debug =
69 0, 0, &CONSOLE_CritSect,
70 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
71 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
73 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
75 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
76 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
78 /* FIXME: this is not thread safe */
79 static HANDLE console_wait_event;
81 /* map input records to ASCII */
82 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
87 for (i = 0; i < count; i++)
89 if (buffer[i].EventType != KEY_EVENT) continue;
90 WideCharToMultiByte( GetConsoleCP(), 0,
91 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
92 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
96 /* map input records to Unicode */
97 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
102 for (i = 0; i < count; i++)
104 if (buffer[i].EventType != KEY_EVENT) continue;
105 MultiByteToWideChar( GetConsoleCP(), 0,
106 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
107 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
111 /* map char infos to ASCII */
112 static void char_info_WtoA( CHAR_INFO *buffer, int count )
118 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
119 &ch, 1, NULL, NULL );
120 buffer->Char.AsciiChar = ch;
125 /* map char infos to Unicode */
126 static void char_info_AtoW( CHAR_INFO *buffer, int count )
132 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
133 buffer->Char.UnicodeChar = ch;
138 static struct termios S_termios; /* saved termios for bare consoles */
139 static BOOL S_termios_raw /* = FALSE */;
141 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
142 * - a bare console is created for all CUI programs started from command line (without
143 * wineconsole) (let's call those PS)
144 * - of course, every child of a PS which requires console inheritance will get it
145 * - the console termios attributes are saved at the start of program which is attached to be
147 * - if any program attached to a bare console requests input from console, the console is
148 * turned into raw mode
149 * - when the program which created the bare console (the program started from command line)
150 * exits, it will restore the console termios attributes it saved at startup (this
151 * will put back the console into cooked mode if it had been put in raw mode)
152 * - if any other program attached to this bare console is still alive, the Unix shell will put
153 * it in the background, hence forbidding access to the console. Therefore, reading console
154 * input will not be available when the bare console creator has died.
155 * FIXME: This is a limitation of current implementation
158 /* returns the fd for a bare console (-1 otherwise) */
159 static int get_console_bare_fd(HANDLE hin)
163 if (wine_server_handle_to_fd(wine_server_ptr_handle(console_handle_unmap(hin)),
164 0, &fd, NULL) == STATUS_SUCCESS)
169 static BOOL save_console_mode(HANDLE hin)
174 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
175 ret = tcgetattr(fd, &S_termios) >= 0;
180 static BOOL put_console_into_raw_mode(int fd)
182 RtlEnterCriticalSection(&CONSOLE_CritSect);
185 struct termios term = S_termios;
187 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
188 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
189 term.c_cflag &= ~(CSIZE | PARENB);
191 /* FIXME: we should actually disable output processing here
192 * and let kernel32/console.c do the job (with support of enable/disable of
195 /* term.c_oflag &= ~(OPOST); */
197 term.c_cc[VTIME] = 0;
198 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
200 RtlLeaveCriticalSection(&CONSOLE_CritSect);
202 return S_termios_raw;
205 /* put back the console in cooked mode iff we're the process which created the bare console
206 * we don't test if this process has set the console in raw mode as it could be one of its
207 * children who did it
209 static BOOL restore_console_mode(HANDLE hin)
214 if (!S_termios_raw ||
215 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
217 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
218 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
224 /******************************************************************************
225 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
228 * Success: hwnd of the console window.
231 HWND WINAPI GetConsoleWindow(VOID)
235 SERVER_START_REQ(get_console_input_info)
238 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
246 /******************************************************************************
247 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
252 UINT WINAPI GetConsoleCP(VOID)
255 UINT codepage = GetOEMCP(); /* default value */
257 SERVER_START_REQ(get_console_input_info)
260 ret = !wine_server_call_err(req);
261 if (ret && reply->input_cp)
262 codepage = reply->input_cp;
270 /******************************************************************************
271 * SetConsoleCP [KERNEL32.@]
273 BOOL WINAPI SetConsoleCP(UINT cp)
277 if (!IsValidCodePage(cp))
279 SetLastError(ERROR_INVALID_PARAMETER);
283 SERVER_START_REQ(set_console_input_info)
286 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
288 ret = !wine_server_call_err(req);
296 /***********************************************************************
297 * GetConsoleOutputCP (KERNEL32.@)
299 UINT WINAPI GetConsoleOutputCP(VOID)
302 UINT codepage = GetOEMCP(); /* default value */
304 SERVER_START_REQ(get_console_input_info)
307 ret = !wine_server_call_err(req);
308 if (ret && reply->output_cp)
309 codepage = reply->output_cp;
317 /******************************************************************************
318 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
321 * cp [I] code page to set
327 BOOL WINAPI SetConsoleOutputCP(UINT cp)
331 if (!IsValidCodePage(cp))
333 SetLastError(ERROR_INVALID_PARAMETER);
337 SERVER_START_REQ(set_console_input_info)
340 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
342 ret = !wine_server_call_err(req);
350 /***********************************************************************
353 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
355 static const char beep = '\a';
356 /* dwFreq and dwDur are ignored by Win95 */
357 if (isatty(2)) write( 2, &beep, 1 );
362 /******************************************************************
363 * OpenConsoleW (KERNEL32.@)
366 * Open a handle to the current process console.
367 * Returns INVALID_HANDLE_VALUE on failure.
369 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
371 HANDLE output = INVALID_HANDLE_VALUE;
374 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
378 if (strcmpiW(coninW, name) == 0)
379 output = (HANDLE) FALSE;
380 else if (strcmpiW(conoutW, name) == 0)
381 output = (HANDLE) TRUE;
384 if (output == INVALID_HANDLE_VALUE)
386 SetLastError(ERROR_INVALID_PARAMETER);
387 return INVALID_HANDLE_VALUE;
389 else if (creation != OPEN_EXISTING)
391 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
392 SetLastError(ERROR_SHARING_VIOLATION);
394 SetLastError(ERROR_INVALID_PARAMETER);
395 return INVALID_HANDLE_VALUE;
398 SERVER_START_REQ( open_console )
400 req->from = wine_server_obj_handle( output );
401 req->access = access;
402 req->attributes = inherit ? OBJ_INHERIT : 0;
403 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
404 wine_server_call_err( req );
405 ret = wine_server_ptr_handle( reply->handle );
409 ret = console_handle_map(ret);
414 /******************************************************************
415 * VerifyConsoleIoHandle (KERNEL32.@)
419 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
423 if (!is_console_handle(handle)) return FALSE;
424 SERVER_START_REQ(get_console_mode)
426 req->handle = console_handle_unmap(handle);
427 ret = !wine_server_call( req );
433 /******************************************************************
434 * DuplicateConsoleHandle (KERNEL32.@)
438 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
443 if (!is_console_handle(handle) ||
444 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
445 GetCurrentProcess(), &ret, access, inherit, options))
446 return INVALID_HANDLE_VALUE;
447 return console_handle_map(ret);
450 /******************************************************************
451 * CloseConsoleHandle (KERNEL32.@)
455 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
457 if (!is_console_handle(handle))
459 SetLastError(ERROR_INVALID_PARAMETER);
462 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
465 /******************************************************************
466 * GetConsoleInputWaitHandle (KERNEL32.@)
470 HANDLE WINAPI GetConsoleInputWaitHandle(void)
472 if (!console_wait_event)
474 SERVER_START_REQ(get_console_wait_event)
476 if (!wine_server_call_err( req ))
477 console_wait_event = wine_server_ptr_handle( reply->handle );
481 return console_wait_event;
485 /******************************************************************************
486 * WriteConsoleInputA [KERNEL32.@]
488 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
489 DWORD count, LPDWORD written )
491 INPUT_RECORD *recW = NULL;
498 SetLastError( ERROR_INVALID_ACCESS );
502 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) )))
504 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
508 memcpy( recW, buffer, count * sizeof(*recW) );
509 input_records_AtoW( recW, count );
512 ret = WriteConsoleInputW( handle, recW, count, written );
513 HeapFree( GetProcessHeap(), 0, recW );
518 /******************************************************************************
519 * WriteConsoleInputW [KERNEL32.@]
521 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
522 DWORD count, LPDWORD written )
524 DWORD events_written = 0;
527 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
529 if (count > 0 && !buffer)
531 SetLastError(ERROR_INVALID_ACCESS);
535 SERVER_START_REQ( write_console_input )
537 req->handle = console_handle_unmap(handle);
538 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
539 if ((ret = !wine_server_call_err( req )))
540 events_written = reply->written;
544 if (written) *written = events_written;
547 SetLastError(ERROR_INVALID_ACCESS);
554 /***********************************************************************
555 * WriteConsoleOutputA (KERNEL32.@)
557 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
558 COORD size, COORD coord, LPSMALL_RECT region )
562 COORD new_size, new_coord;
565 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
566 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
568 if (new_size.X <= 0 || new_size.Y <= 0)
570 region->Bottom = region->Top + new_size.Y - 1;
571 region->Right = region->Left + new_size.X - 1;
575 /* only copy the useful rectangle */
576 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
578 for (y = 0; y < new_size.Y; y++)
580 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
581 new_size.X * sizeof(CHAR_INFO) );
582 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
584 new_coord.X = new_coord.Y = 0;
585 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
586 HeapFree( GetProcessHeap(), 0, ciw );
591 /***********************************************************************
592 * WriteConsoleOutputW (KERNEL32.@)
594 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
595 COORD size, COORD coord, LPSMALL_RECT region )
597 int width, height, y;
600 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
601 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
602 region->Left, region->Top, region->Right, region->Bottom);
604 width = min( region->Right - region->Left + 1, size.X - coord.X );
605 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
607 if (width > 0 && height > 0)
609 for (y = 0; y < height; y++)
611 SERVER_START_REQ( write_console_output )
613 req->handle = console_handle_unmap(hConsoleOutput);
614 req->x = region->Left;
615 req->y = region->Top + y;
616 req->mode = CHAR_INFO_MODE_TEXTATTR;
618 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
619 width * sizeof(CHAR_INFO));
620 if ((ret = !wine_server_call_err( req )))
622 width = min( width, reply->width - region->Left );
623 height = min( height, reply->height - region->Top );
630 region->Bottom = region->Top + height - 1;
631 region->Right = region->Left + width - 1;
636 /******************************************************************************
637 * WriteConsoleOutputCharacterA [KERNEL32.@]
639 * See WriteConsoleOutputCharacterW.
641 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
642 COORD coord, LPDWORD lpNumCharsWritten )
648 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
649 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
655 SetLastError( ERROR_INVALID_ACCESS );
659 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
661 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
663 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
667 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
670 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
671 HeapFree( GetProcessHeap(), 0, strW );
676 /******************************************************************************
677 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
678 * the console screen buffer
681 * hConsoleOutput [I] Handle to screen buffer
682 * attr [I] Pointer to buffer with write attributes
683 * length [I] Number of cells to write to
684 * coord [I] Coords of first cell
685 * lpNumAttrsWritten [O] Pointer to number of cells written
692 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
693 COORD coord, LPDWORD lpNumAttrsWritten )
697 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
699 if ((length > 0 && !attr) || !lpNumAttrsWritten)
701 SetLastError(ERROR_INVALID_ACCESS);
705 *lpNumAttrsWritten = 0;
707 SERVER_START_REQ( write_console_output )
709 req->handle = console_handle_unmap(hConsoleOutput);
712 req->mode = CHAR_INFO_MODE_ATTR;
714 wine_server_add_data( req, attr, length * sizeof(WORD) );
715 if ((ret = !wine_server_call_err( req )))
716 *lpNumAttrsWritten = reply->written;
723 /******************************************************************************
724 * FillConsoleOutputCharacterA [KERNEL32.@]
726 * See FillConsoleOutputCharacterW.
728 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
729 COORD coord, LPDWORD lpNumCharsWritten )
733 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
734 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
738 /******************************************************************************
739 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
742 * hConsoleOutput [I] Handle to screen buffer
743 * ch [I] Character to write
744 * length [I] Number of cells to write to
745 * coord [I] Coords of first cell
746 * lpNumCharsWritten [O] Pointer to number of cells written
752 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
753 COORD coord, LPDWORD lpNumCharsWritten)
757 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
758 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
760 if (!lpNumCharsWritten)
762 SetLastError(ERROR_INVALID_ACCESS);
766 *lpNumCharsWritten = 0;
768 SERVER_START_REQ( fill_console_output )
770 req->handle = console_handle_unmap(hConsoleOutput);
773 req->mode = CHAR_INFO_MODE_TEXT;
777 if ((ret = !wine_server_call_err( req )))
778 *lpNumCharsWritten = reply->written;
785 /******************************************************************************
786 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
789 * hConsoleOutput [I] Handle to screen buffer
790 * attr [I] Color attribute to write
791 * length [I] Number of cells to write to
792 * coord [I] Coords of first cell
793 * lpNumAttrsWritten [O] Pointer to number of cells written
799 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
800 COORD coord, LPDWORD lpNumAttrsWritten )
804 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
805 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
807 if (!lpNumAttrsWritten)
809 SetLastError(ERROR_INVALID_ACCESS);
813 *lpNumAttrsWritten = 0;
815 SERVER_START_REQ( fill_console_output )
817 req->handle = console_handle_unmap(hConsoleOutput);
820 req->mode = CHAR_INFO_MODE_ATTR;
822 req->data.attr = attr;
824 if ((ret = !wine_server_call_err( req )))
825 *lpNumAttrsWritten = reply->written;
832 /******************************************************************************
833 * ReadConsoleOutputCharacterA [KERNEL32.@]
836 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
837 COORD coord, LPDWORD read_count)
845 SetLastError(ERROR_INVALID_ACCESS);
851 if (!(wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR))))
853 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
857 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
859 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
862 HeapFree( GetProcessHeap(), 0, wptr );
867 /******************************************************************************
868 * ReadConsoleOutputCharacterW [KERNEL32.@]
871 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
872 COORD coord, LPDWORD read_count )
876 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
880 SetLastError(ERROR_INVALID_ACCESS);
886 SERVER_START_REQ( read_console_output )
888 req->handle = console_handle_unmap(hConsoleOutput);
891 req->mode = CHAR_INFO_MODE_TEXT;
893 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
894 if ((ret = !wine_server_call_err( req )))
895 *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
902 /******************************************************************************
903 * ReadConsoleOutputAttribute [KERNEL32.@]
905 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
906 COORD coord, LPDWORD read_count)
910 TRACE("(%p,%p,%d,%dx%d,%p)\n",
911 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
915 SetLastError(ERROR_INVALID_ACCESS);
921 SERVER_START_REQ( read_console_output )
923 req->handle = console_handle_unmap(hConsoleOutput);
926 req->mode = CHAR_INFO_MODE_ATTR;
928 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
929 if ((ret = !wine_server_call_err( req )))
930 *read_count = wine_server_reply_size(reply) / sizeof(WORD);
937 /******************************************************************************
938 * ReadConsoleOutputA [KERNEL32.@]
941 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
942 COORD coord, LPSMALL_RECT region )
947 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
948 if (ret && region->Right >= region->Left)
950 for (y = 0; y <= region->Bottom - region->Top; y++)
952 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
953 region->Right - region->Left + 1 );
960 /******************************************************************************
961 * ReadConsoleOutputW [KERNEL32.@]
963 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
964 * think we need to be *that* compatible. -- AJ
966 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
967 COORD coord, LPSMALL_RECT region )
969 int width, height, y;
972 width = min( region->Right - region->Left + 1, size.X - coord.X );
973 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
975 if (width > 0 && height > 0)
977 for (y = 0; y < height; y++)
979 SERVER_START_REQ( read_console_output )
981 req->handle = console_handle_unmap(hConsoleOutput);
982 req->x = region->Left;
983 req->y = region->Top + y;
984 req->mode = CHAR_INFO_MODE_TEXTATTR;
986 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
987 width * sizeof(CHAR_INFO) );
988 if ((ret = !wine_server_call_err( req )))
990 width = min( width, reply->width - region->Left );
991 height = min( height, reply->height - region->Top );
998 region->Bottom = region->Top + height - 1;
999 region->Right = region->Left + width - 1;
1004 /******************************************************************************
1005 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
1008 * handle [I] Handle to console input buffer
1009 * buffer [O] Address of buffer for read data
1010 * count [I] Number of records to read
1011 * pRead [O] Address of number of records read
1017 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1021 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
1022 input_records_WtoA( buffer, read );
1023 if (pRead) *pRead = read;
1028 /***********************************************************************
1029 * PeekConsoleInputA (KERNEL32.@)
1031 * Gets 'count' first events (or less) from input queue.
1033 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1037 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
1038 input_records_WtoA( buffer, read );
1039 if (pRead) *pRead = read;
1044 /***********************************************************************
1045 * PeekConsoleInputW (KERNEL32.@)
1047 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
1050 SERVER_START_REQ( read_console_input )
1052 req->handle = console_handle_unmap(handle);
1054 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1055 if ((ret = !wine_server_call_err( req )))
1057 if (read) *read = count ? reply->read : 0;
1065 /***********************************************************************
1066 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1068 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1071 SERVER_START_REQ( read_console_input )
1073 req->handle = console_handle_unmap(handle);
1075 if ((ret = !wine_server_call_err( req )))
1078 *nrofevents = reply->read;
1081 SetLastError(ERROR_INVALID_ACCESS);
1091 /******************************************************************************
1092 * read_console_input
1094 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1097 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1099 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1101 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1103 enum read_console_input_return ret;
1107 size_t idx = 0, idxw;
1111 struct pollfd pollfd;
1112 BOOL locked = FALSE, next_char;
1116 if (idx == sizeof(input))
1118 FIXME("buffer too small (%s)\n", wine_dbgstr_an(input, idx));
1123 pollfd.events = POLLIN;
1127 switch (poll(&pollfd, 1, timeout))
1132 RtlEnterCriticalSection(&CONSOLE_CritSect);
1135 i = read(fd, &input[idx], 1);
1143 /* actually another thread likely beat us to reading the char
1144 * return rci_gotone, while not perfect, it should work in most of the cases (as the new event
1145 * should be now in the queue, fed from the other thread)
1152 numEvent = TERM_FillInputRecord(input, idx, ir);
1156 /* we need more char(s) to tell if it matches a key-db entry. wait 1/2s for next char */
1161 /* we haven't found the string into key-db, push full input string into server */
1162 idxw = MultiByteToWideChar(CP_UNIXCP, 0, input, idx, inputw, sizeof(inputw) / sizeof(inputw[0]));
1164 /* we cannot translate yet... likely we need more chars (wait max 1/2s for next char) */
1171 for (i = 0; i < idxw; i++)
1173 numEvent = TERM_FillSimpleChar(inputw[i], ir);
1174 WriteConsoleInputW(handle, ir, numEvent, &written);
1179 /* we got a transformation from key-db... push this into server */
1180 ret = WriteConsoleInputW(handle, ir, numEvent, &written) ? rci_gotone : rci_error;
1184 case 0: ret = rci_timeout; break;
1185 default: ret = rci_error; break;
1187 } while (next_char);
1188 if (locked) RtlLeaveCriticalSection(&CONSOLE_CritSect);
1193 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1196 enum read_console_input_return ret;
1198 if ((fd = get_console_bare_fd(handle)) != -1)
1200 put_console_into_raw_mode(fd);
1201 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1203 ret = bare_console_fetch_input(handle, fd, timeout);
1205 else ret = rci_gotone;
1207 if (ret != rci_gotone) return ret;
1211 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1213 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1217 SERVER_START_REQ( read_console_input )
1219 req->handle = console_handle_unmap(handle);
1221 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1222 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1223 else ret = rci_gotone;
1231 /***********************************************************************
1232 * FlushConsoleInputBuffer (KERNEL32.@)
1234 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1236 enum read_console_input_return last;
1239 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1241 return last == rci_timeout;
1245 /***********************************************************************
1246 * SetConsoleTitleA (KERNEL32.@)
1248 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1253 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1254 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1255 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1256 ret = SetConsoleTitleW(titleW);
1257 HeapFree(GetProcessHeap(), 0, titleW);
1262 /***********************************************************************
1263 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1265 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1267 FIXME( "stub %p\n", layoutName);
1271 /***********************************************************************
1272 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1274 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1276 FIXME( "stub %p\n", layoutName);
1280 static WCHAR input_exe[MAX_PATH + 1];
1282 /***********************************************************************
1283 * GetConsoleInputExeNameW (KERNEL32.@)
1285 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1287 TRACE("%u %p\n", buflen, buffer);
1289 RtlEnterCriticalSection(&CONSOLE_CritSect);
1290 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1291 else SetLastError(ERROR_BUFFER_OVERFLOW);
1292 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1297 /***********************************************************************
1298 * GetConsoleInputExeNameA (KERNEL32.@)
1300 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1302 TRACE("%u %p\n", buflen, buffer);
1304 RtlEnterCriticalSection(&CONSOLE_CritSect);
1305 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1306 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1307 else SetLastError(ERROR_BUFFER_OVERFLOW);
1308 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1313 /***********************************************************************
1314 * GetConsoleTitleA (KERNEL32.@)
1316 * See GetConsoleTitleW.
1318 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1320 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1324 ret = GetConsoleTitleW( ptr, size );
1327 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1328 ret = strlen(title);
1330 HeapFree(GetProcessHeap(), 0, ptr);
1335 /******************************************************************************
1336 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1339 * title [O] Address of buffer for title
1340 * size [I] Size of buffer
1343 * Success: Length of string copied
1346 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1350 SERVER_START_REQ( get_console_input_info )
1353 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1354 if (!wine_server_call_err( req ))
1356 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1365 /***********************************************************************
1366 * GetLargestConsoleWindowSize (KERNEL32.@)
1369 * This should return a COORD, but calling convention for returning
1370 * structures is different between Windows and gcc on i386.
1375 #undef GetLargestConsoleWindowSize
1376 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1384 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1387 #endif /* defined(__i386__) */
1390 /***********************************************************************
1391 * GetLargestConsoleWindowSize (KERNEL32.@)
1394 * This should return a COORD, but calling convention for returning
1395 * structures is different between Windows and gcc on i386.
1400 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1405 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1408 #endif /* defined(__i386__) */
1410 static WCHAR* S_EditString /* = NULL */;
1411 static unsigned S_EditStrPos /* = 0 */;
1413 /***********************************************************************
1414 * FreeConsole (KERNEL32.@)
1416 BOOL WINAPI FreeConsole(VOID)
1420 /* invalidate local copy of input event handle */
1421 console_wait_event = 0;
1423 SERVER_START_REQ(free_console)
1425 ret = !wine_server_call_err( req );
1431 /******************************************************************
1432 * start_console_renderer
1434 * helper for AllocConsole
1435 * starts the renderer process
1437 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1442 PROCESS_INFORMATION pi;
1444 /* FIXME: use dynamic allocation for most of the buffers below */
1445 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1446 if ((ret > -1) && (ret < sizeof(buffer)) &&
1447 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1448 NULL, NULL, si, &pi))
1454 wh[1] = pi.hProcess;
1455 res = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1457 CloseHandle(pi.hThread);
1458 CloseHandle(pi.hProcess);
1460 if (res != WAIT_OBJECT_0) return FALSE;
1462 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1463 pi.dwProcessId, pi.dwThreadId);
1470 static BOOL start_console_renderer(STARTUPINFOA* si)
1474 OBJECT_ATTRIBUTES attr;
1477 attr.Length = sizeof(attr);
1478 attr.RootDirectory = 0;
1479 attr.Attributes = OBJ_INHERIT;
1480 attr.ObjectName = NULL;
1481 attr.SecurityDescriptor = NULL;
1482 attr.SecurityQualityOfService = NULL;
1484 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1485 if (!hEvent) return FALSE;
1487 /* first try environment variable */
1488 if ((p = getenv("WINECONSOLE")) != NULL)
1490 ret = start_console_renderer_helper(p, si, hEvent);
1492 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1493 "trying default access\n", p);
1496 /* then try the regular PATH */
1498 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1500 CloseHandle(hEvent);
1504 /***********************************************************************
1505 * AllocConsole (KERNEL32.@)
1507 * creates an xterm with a pty to our program
1509 BOOL WINAPI AllocConsole(void)
1511 HANDLE handle_in = INVALID_HANDLE_VALUE;
1512 HANDLE handle_out = INVALID_HANDLE_VALUE;
1513 HANDLE handle_err = INVALID_HANDLE_VALUE;
1514 STARTUPINFOA siCurrent;
1515 STARTUPINFOA siConsole;
1520 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1521 FALSE, OPEN_EXISTING );
1523 if (VerifyConsoleIoHandle(handle_in))
1525 /* we already have a console opened on this process, don't create a new one */
1526 CloseHandle(handle_in);
1530 /* invalidate local copy of input event handle */
1531 console_wait_event = 0;
1533 GetStartupInfoA(&siCurrent);
1535 memset(&siConsole, 0, sizeof(siConsole));
1536 siConsole.cb = sizeof(siConsole);
1537 /* setup a view arguments for wineconsole (it'll use them as default values) */
1538 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1540 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1541 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1542 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1544 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1546 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1547 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1549 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1551 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1552 siConsole.wShowWindow = siCurrent.wShowWindow;
1554 /* FIXME (should pass the unicode form) */
1555 if (siCurrent.lpTitle)
1556 siConsole.lpTitle = siCurrent.lpTitle;
1557 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1559 buffer[sizeof(buffer) - 1] = '\0';
1560 siConsole.lpTitle = buffer;
1563 if (!start_console_renderer(&siConsole))
1566 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1567 /* all std I/O handles are inheritable by default */
1568 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1569 TRUE, OPEN_EXISTING );
1570 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1572 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1573 TRUE, OPEN_EXISTING );
1574 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1576 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1577 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1580 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1581 handle_in = siCurrent.hStdInput;
1582 handle_out = siCurrent.hStdOutput;
1583 handle_err = siCurrent.hStdError;
1586 /* NT resets the STD_*_HANDLEs on console alloc */
1587 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1588 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1589 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1591 SetLastError(ERROR_SUCCESS);
1596 ERR("Can't allocate console\n");
1597 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1598 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1599 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1605 /***********************************************************************
1606 * ReadConsoleA (KERNEL32.@)
1608 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1609 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1611 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1615 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1616 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1618 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1619 HeapFree(GetProcessHeap(), 0, ptr);
1624 /***********************************************************************
1625 * ReadConsoleW (KERNEL32.@)
1627 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1628 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1631 LPWSTR xbuf = lpBuffer;
1633 BOOL is_bare = FALSE;
1636 TRACE("(%p,%p,%d,%p,%p)\n",
1637 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1639 if (!GetConsoleMode(hConsoleInput, &mode))
1641 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1646 if (mode & ENABLE_LINE_INPUT)
1648 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1650 HeapFree(GetProcessHeap(), 0, S_EditString);
1651 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1655 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1656 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1657 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1658 S_EditStrPos += charsread;
1663 DWORD timeout = INFINITE;
1665 /* FIXME: should we read at least 1 char? The SDK does not say */
1666 /* wait for at least one available input record (it doesn't mean we'll have
1667 * chars stored in xbuf...)
1669 * Although SDK doc keeps silence about 1 char, SDK examples assume
1670 * that we should wait for at least one character (not key). --KS
1675 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1676 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1677 ir.Event.KeyEvent.uChar.UnicodeChar)
1679 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1682 } while (charsread < nNumberOfCharsToRead);
1683 /* nothing has been read */
1684 if (timeout == INFINITE) return FALSE;
1687 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1693 /***********************************************************************
1694 * ReadConsoleInputW (KERNEL32.@)
1696 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1697 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1700 DWORD timeout = INFINITE;
1704 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1708 /* loop until we get at least one event */
1709 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1713 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1718 /******************************************************************************
1719 * WriteConsoleOutputCharacterW [KERNEL32.@]
1721 * Copy character to consecutive cells in the console screen buffer.
1724 * hConsoleOutput [I] Handle to screen buffer
1725 * str [I] Pointer to buffer with chars to write
1726 * length [I] Number of cells to write to
1727 * coord [I] Coords of first cell
1728 * lpNumCharsWritten [O] Pointer to number of cells written
1735 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1736 COORD coord, LPDWORD lpNumCharsWritten )
1740 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1741 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1743 if ((length > 0 && !str) || !lpNumCharsWritten)
1745 SetLastError(ERROR_INVALID_ACCESS);
1749 *lpNumCharsWritten = 0;
1751 SERVER_START_REQ( write_console_output )
1753 req->handle = console_handle_unmap(hConsoleOutput);
1756 req->mode = CHAR_INFO_MODE_TEXT;
1758 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1759 if ((ret = !wine_server_call_err( req )))
1760 *lpNumCharsWritten = reply->written;
1767 /******************************************************************************
1768 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1771 * title [I] Address of new title
1777 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1781 TRACE("(%s)\n", debugstr_w(title));
1782 SERVER_START_REQ( set_console_input_info )
1785 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1786 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1787 ret = !wine_server_call_err( req );
1794 /***********************************************************************
1795 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1797 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1799 FIXME("(%p): stub\n", nrofbuttons);
1804 /******************************************************************************
1805 * SetConsoleInputExeNameW [KERNEL32.@]
1807 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1809 TRACE("(%s)\n", debugstr_w(name));
1811 if (!name || !name[0])
1813 SetLastError(ERROR_INVALID_PARAMETER);
1817 RtlEnterCriticalSection(&CONSOLE_CritSect);
1818 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1819 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1824 /******************************************************************************
1825 * SetConsoleInputExeNameA [KERNEL32.@]
1827 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1833 if (!name || !name[0])
1835 SetLastError(ERROR_INVALID_PARAMETER);
1839 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1840 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1842 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1843 ret = SetConsoleInputExeNameW(nameW);
1844 HeapFree(GetProcessHeap(), 0, nameW);
1849 /******************************************************************
1850 * CONSOLE_DefaultHandler
1852 * Final control event handler
1854 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1856 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1858 /* should never go here */
1862 /******************************************************************************
1863 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1866 * func [I] Address of handler function
1867 * add [I] Handler to add or remove
1874 struct ConsoleHandler
1876 PHANDLER_ROUTINE handler;
1877 struct ConsoleHandler* next;
1880 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1881 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1883 /*****************************************************************************/
1885 /******************************************************************
1886 * SetConsoleCtrlHandler (KERNEL32.@)
1888 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1892 TRACE("(%p,%i)\n", func, add);
1896 RtlEnterCriticalSection(&CONSOLE_CritSect);
1898 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1900 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1901 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1905 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1907 if (!ch) return FALSE;
1909 RtlEnterCriticalSection(&CONSOLE_CritSect);
1910 ch->next = CONSOLE_Handlers;
1911 CONSOLE_Handlers = ch;
1912 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1916 struct ConsoleHandler** ch;
1917 RtlEnterCriticalSection(&CONSOLE_CritSect);
1918 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1920 if ((*ch)->handler == func) break;
1924 struct ConsoleHandler* rch = *ch;
1927 if (rch == &CONSOLE_DefaultConsoleHandler)
1929 ERR("Who's trying to remove default handler???\n");
1930 SetLastError(ERROR_INVALID_PARAMETER);
1936 HeapFree(GetProcessHeap(), 0, rch);
1941 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1942 SetLastError(ERROR_INVALID_PARAMETER);
1945 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1950 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1952 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1953 return EXCEPTION_EXECUTE_HANDLER;
1956 /******************************************************************
1957 * CONSOLE_SendEventThread
1959 * Internal helper to pass an event to the list on installed handlers
1961 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1963 DWORD_PTR event = (DWORD_PTR)pmt;
1964 struct ConsoleHandler* ch;
1966 if (event == CTRL_C_EVENT)
1968 BOOL caught_by_dbg = TRUE;
1969 /* First, try to pass the ctrl-C event to the debugger (if any)
1970 * If it continues, there's nothing more to do
1971 * Otherwise, we need to send the ctrl-C event to the handlers
1975 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1977 __EXCEPT(CONSOLE_CtrlEventHandler)
1979 caught_by_dbg = FALSE;
1982 if (caught_by_dbg) return 0;
1983 /* the debugger didn't continue... so, pass to ctrl handlers */
1985 RtlEnterCriticalSection(&CONSOLE_CritSect);
1986 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1988 if (ch->handler(event)) break;
1990 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1994 /******************************************************************
1995 * CONSOLE_HandleCtrlC
1997 * Check whether the shall manipulate CtrlC events
1999 int CONSOLE_HandleCtrlC(unsigned sig)
2001 /* FIXME: better test whether a console is attached to this process ??? */
2002 extern unsigned CONSOLE_GetNumHistoryEntries(void);
2003 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
2005 /* check if we have to ignore ctrl-C events */
2006 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
2008 /* Create a separate thread to signal all the events.
2009 * This is needed because:
2010 * - this function can be called in an Unix signal handler (hence on an
2011 * different stack than the thread that's running). This breaks the
2012 * Win32 exception mechanisms (where the thread's stack is checked).
2013 * - since the current thread, while processing the signal, can hold the
2014 * console critical section, we need another execution environment where
2015 * we can wait on this critical section
2017 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2022 /******************************************************************************
2023 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2026 * dwCtrlEvent [I] Type of event
2027 * dwProcessGroupID [I] Process group ID to send event to
2031 * Failure: False (and *should* [but doesn't] set LastError)
2033 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2034 DWORD dwProcessGroupID)
2038 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2040 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2042 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2046 SERVER_START_REQ( send_console_signal )
2048 req->signal = dwCtrlEvent;
2049 req->group_id = dwProcessGroupID;
2050 ret = !wine_server_call_err( req );
2054 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2055 * have been handled by all processes in the given group?
2056 * As of today, we don't wait...
2062 /******************************************************************************
2063 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2066 * dwDesiredAccess [I] Access flag
2067 * dwShareMode [I] Buffer share mode
2068 * sa [I] Security attributes
2069 * dwFlags [I] Type of buffer to create
2070 * lpScreenBufferData [I] Reserved
2073 * Should call SetLastError
2076 * Success: Handle to new console screen buffer
2077 * Failure: INVALID_HANDLE_VALUE
2079 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2080 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2081 LPVOID lpScreenBufferData)
2083 HANDLE ret = INVALID_HANDLE_VALUE;
2085 TRACE("(%d,%d,%p,%d,%p)\n",
2086 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2088 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2090 SetLastError(ERROR_INVALID_PARAMETER);
2091 return INVALID_HANDLE_VALUE;
2094 SERVER_START_REQ(create_console_output)
2097 req->access = dwDesiredAccess;
2098 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2099 req->share = dwShareMode;
2101 if (!wine_server_call_err( req ))
2102 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2110 /***********************************************************************
2111 * GetConsoleScreenBufferInfo (KERNEL32.@)
2113 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2117 SERVER_START_REQ(get_console_output_info)
2119 req->handle = console_handle_unmap(hConsoleOutput);
2120 if ((ret = !wine_server_call_err( req )))
2122 csbi->dwSize.X = reply->width;
2123 csbi->dwSize.Y = reply->height;
2124 csbi->dwCursorPosition.X = reply->cursor_x;
2125 csbi->dwCursorPosition.Y = reply->cursor_y;
2126 csbi->wAttributes = reply->attr;
2127 csbi->srWindow.Left = reply->win_left;
2128 csbi->srWindow.Right = reply->win_right;
2129 csbi->srWindow.Top = reply->win_top;
2130 csbi->srWindow.Bottom = reply->win_bottom;
2131 csbi->dwMaximumWindowSize.X = reply->max_width;
2132 csbi->dwMaximumWindowSize.Y = reply->max_height;
2137 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2138 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2139 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2141 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2142 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2148 /******************************************************************************
2149 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2155 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2159 TRACE("(%p)\n", hConsoleOutput);
2161 SERVER_START_REQ( set_console_input_info )
2164 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2165 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2166 ret = !wine_server_call_err( req );
2173 /***********************************************************************
2174 * GetConsoleMode (KERNEL32.@)
2176 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2180 SERVER_START_REQ( get_console_mode )
2182 req->handle = console_handle_unmap(hcon);
2183 if ((ret = !wine_server_call_err( req )))
2185 if (mode) *mode = reply->mode;
2193 /******************************************************************************
2194 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2197 * hcon [I] Handle to console input or screen buffer
2198 * mode [I] Input or output mode to set
2205 * ENABLE_PROCESSED_INPUT 0x01
2206 * ENABLE_LINE_INPUT 0x02
2207 * ENABLE_ECHO_INPUT 0x04
2208 * ENABLE_WINDOW_INPUT 0x08
2209 * ENABLE_MOUSE_INPUT 0x10
2211 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2215 SERVER_START_REQ(set_console_mode)
2217 req->handle = console_handle_unmap(hcon);
2219 ret = !wine_server_call_err( req );
2222 /* FIXME: when resetting a console input to editline mode, I think we should
2223 * empty the S_EditString buffer
2226 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2232 /******************************************************************
2233 * CONSOLE_WriteChars
2235 * WriteConsoleOutput helper: hides server call semantics
2236 * writes a string at a given pos with standard attribute
2238 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2244 SERVER_START_REQ( write_console_output )
2246 req->handle = console_handle_unmap(hCon);
2249 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2251 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2252 if (!wine_server_call_err( req )) written = reply->written;
2256 if (written > 0) pos->X += written;
2260 /******************************************************************
2263 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2266 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2272 csbi->dwCursorPosition.X = 0;
2273 csbi->dwCursorPosition.Y++;
2275 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2278 src.Bottom = csbi->dwSize.Y - 1;
2280 src.Right = csbi->dwSize.X - 1;
2285 ci.Attributes = csbi->wAttributes;
2286 ci.Char.UnicodeChar = ' ';
2288 csbi->dwCursorPosition.Y--;
2289 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2294 /******************************************************************
2297 * WriteConsoleOutput helper: writes a block of non special characters
2298 * Block can spread on several lines, and wrapping, if needed, is
2302 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2303 DWORD mode, LPCWSTR ptr, int len)
2305 int blk; /* number of chars to write on current line */
2306 int done; /* number of chars already written */
2308 if (len <= 0) return 1;
2310 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2312 for (done = 0; done < len; done += blk)
2314 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2316 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2318 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2324 int pos = csbi->dwCursorPosition.X;
2325 /* FIXME: we could reduce the number of loops
2326 * but, in most cases we wouldn't gain lots of time (it would only
2327 * happen if we're asked to overwrite more than twice the part of the line,
2330 for (done = 0; done < len; done += blk)
2332 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2334 csbi->dwCursorPosition.X = pos;
2335 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2343 /***********************************************************************
2344 * WriteConsoleW (KERNEL32.@)
2346 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2347 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2351 const WCHAR* psz = lpBuffer;
2352 CONSOLE_SCREEN_BUFFER_INFO csbi;
2353 int k, first = 0, fd;
2355 TRACE("%p %s %d %p %p\n",
2356 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2357 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2359 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2361 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2367 IO_STATUS_BLOCK iosb;
2370 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2373 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2374 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2377 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2378 hFile = wine_server_ptr_handle(console_handle_unmap(hConsoleOutput));
2379 status = NtWriteFile(hFile, NULL, NULL, NULL, &iosb, ptr, len, 0, NULL);
2380 if (status == STATUS_PENDING)
2382 WaitForSingleObject(hFile, INFINITE);
2383 status = iosb.u.Status;
2386 if (status != STATUS_PENDING && lpNumberOfCharsWritten)
2388 if (iosb.Information == len)
2389 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2391 FIXME("Conversion not supported yet\n");
2393 HeapFree(GetProcessHeap(), 0, ptr);
2394 if (status != STATUS_SUCCESS)
2396 SetLastError(RtlNtStatusToDosError(status));
2402 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2405 if (!nNumberOfCharsToWrite) return TRUE;
2407 if (mode & ENABLE_PROCESSED_OUTPUT)
2411 for (i = 0; i < nNumberOfCharsToWrite; i++)
2415 case '\b': case '\t': case '\n': case '\a': case '\r':
2416 /* don't handle here the i-th char... done below */
2417 if ((k = i - first) > 0)
2419 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2429 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2433 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2435 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2436 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2441 next_line(hConsoleOutput, &csbi);
2447 csbi.dwCursorPosition.X = 0;
2455 /* write the remaining block (if any) if processed output is enabled, or the
2456 * entire buffer otherwise
2458 if ((k = nNumberOfCharsToWrite - first) > 0)
2460 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2466 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2467 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2472 /***********************************************************************
2473 * WriteConsoleA (KERNEL32.@)
2475 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2476 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2482 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2484 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2485 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2486 if (!xstring) return 0;
2488 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2490 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2492 HeapFree(GetProcessHeap(), 0, xstring);
2497 /******************************************************************************
2498 * SetConsoleCursorPosition [KERNEL32.@]
2499 * Sets the cursor position in console
2502 * hConsoleOutput [I] Handle of console screen buffer
2503 * dwCursorPosition [I] New cursor position coordinates
2509 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2512 CONSOLE_SCREEN_BUFFER_INFO csbi;
2516 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2518 SERVER_START_REQ(set_console_output_info)
2520 req->handle = console_handle_unmap(hcon);
2521 req->cursor_x = pos.X;
2522 req->cursor_y = pos.Y;
2523 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2524 ret = !wine_server_call_err( req );
2528 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2531 /* if cursor is no longer visible, scroll the visible window... */
2532 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2533 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2534 if (pos.X < csbi.srWindow.Left)
2536 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2539 else if (pos.X > csbi.srWindow.Right)
2541 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2544 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2546 if (pos.Y < csbi.srWindow.Top)
2548 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2551 else if (pos.Y > csbi.srWindow.Bottom)
2553 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2556 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2558 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2563 /******************************************************************************
2564 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2567 * hcon [I] Handle to console screen buffer
2568 * cinfo [O] Address of cursor information
2574 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2578 SERVER_START_REQ(get_console_output_info)
2580 req->handle = console_handle_unmap(hCon);
2581 ret = !wine_server_call_err( req );
2584 cinfo->dwSize = reply->cursor_size;
2585 cinfo->bVisible = reply->cursor_visible;
2590 if (!ret) return FALSE;
2594 SetLastError(ERROR_INVALID_ACCESS);
2597 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2603 /******************************************************************************
2604 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2607 * hcon [I] Handle to console screen buffer
2608 * cinfo [I] Address of cursor information
2613 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2617 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2618 SERVER_START_REQ(set_console_output_info)
2620 req->handle = console_handle_unmap(hCon);
2621 req->cursor_size = cinfo->dwSize;
2622 req->cursor_visible = cinfo->bVisible;
2623 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2624 ret = !wine_server_call_err( req );
2631 /******************************************************************************
2632 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2635 * hcon [I] Handle to console screen buffer
2636 * bAbsolute [I] Coordinate type flag
2637 * window [I] Address of new window rectangle
2642 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2644 SMALL_RECT p = *window;
2647 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2651 CONSOLE_SCREEN_BUFFER_INFO csbi;
2653 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2655 p.Left += csbi.srWindow.Left;
2656 p.Top += csbi.srWindow.Top;
2657 p.Right += csbi.srWindow.Right;
2658 p.Bottom += csbi.srWindow.Bottom;
2660 SERVER_START_REQ(set_console_output_info)
2662 req->handle = console_handle_unmap(hCon);
2663 req->win_left = p.Left;
2664 req->win_top = p.Top;
2665 req->win_right = p.Right;
2666 req->win_bottom = p.Bottom;
2667 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2668 ret = !wine_server_call_err( req );
2676 /******************************************************************************
2677 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2679 * Sets the foreground and background color attributes of characters
2680 * written to the screen buffer.
2686 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2690 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2691 SERVER_START_REQ(set_console_output_info)
2693 req->handle = console_handle_unmap(hConsoleOutput);
2695 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2696 ret = !wine_server_call_err( req );
2703 /******************************************************************************
2704 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2707 * hConsoleOutput [I] Handle to console screen buffer
2708 * dwSize [I] New size in character rows and cols
2714 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2718 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2719 SERVER_START_REQ(set_console_output_info)
2721 req->handle = console_handle_unmap(hConsoleOutput);
2722 req->width = dwSize.X;
2723 req->height = dwSize.Y;
2724 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2725 ret = !wine_server_call_err( req );
2732 /******************************************************************************
2733 * ScrollConsoleScreenBufferA [KERNEL32.@]
2736 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2737 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2742 ciw.Attributes = lpFill->Attributes;
2743 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2745 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2746 dwDestOrigin, &ciw);
2749 /******************************************************************
2750 * CONSOLE_FillLineUniform
2752 * Helper function for ScrollConsoleScreenBufferW
2753 * Fills a part of a line with a constant character info
2755 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2757 SERVER_START_REQ( fill_console_output )
2759 req->handle = console_handle_unmap(hConsoleOutput);
2760 req->mode = CHAR_INFO_MODE_TEXTATTR;
2765 req->data.ch = lpFill->Char.UnicodeChar;
2766 req->data.attr = lpFill->Attributes;
2767 wine_server_call_err( req );
2772 /******************************************************************************
2773 * ScrollConsoleScreenBufferW [KERNEL32.@]
2777 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2778 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2786 CONSOLE_SCREEN_BUFFER_INFO csbi;
2791 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2792 lpScrollRect->Left, lpScrollRect->Top,
2793 lpScrollRect->Right, lpScrollRect->Bottom,
2794 lpClipRect->Left, lpClipRect->Top,
2795 lpClipRect->Right, lpClipRect->Bottom,
2796 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2798 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2799 lpScrollRect->Left, lpScrollRect->Top,
2800 lpScrollRect->Right, lpScrollRect->Bottom,
2801 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2803 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2806 src.X = lpScrollRect->Left;
2807 src.Y = lpScrollRect->Top;
2809 /* step 1: get dst rect */
2810 dst.Left = dwDestOrigin.X;
2811 dst.Top = dwDestOrigin.Y;
2812 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2813 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2815 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2818 clip.Left = max(0, lpClipRect->Left);
2819 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2820 clip.Top = max(0, lpClipRect->Top);
2821 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2826 clip.Right = csbi.dwSize.X - 1;
2828 clip.Bottom = csbi.dwSize.Y - 1;
2830 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2832 /* step 2b: clip dst rect */
2833 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2834 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2835 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2836 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2838 /* step 3: transfer the bits */
2839 SERVER_START_REQ(move_console_output)
2841 req->handle = console_handle_unmap(hConsoleOutput);
2844 req->x_dst = dst.Left;
2845 req->y_dst = dst.Top;
2846 req->w = dst.Right - dst.Left + 1;
2847 req->h = dst.Bottom - dst.Top + 1;
2848 ret = !wine_server_call_err( req );
2852 if (!ret) return FALSE;
2854 /* step 4: clean out the exposed part */
2856 /* have to write cell [i,j] if it is not in dst rect (because it has already
2857 * been written to by the scroll) and is in clip (we shall not write
2860 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2862 inside = dst.Top <= j && j <= dst.Bottom;
2864 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2866 if (inside && dst.Left <= i && i <= dst.Right)
2870 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2876 if (start == -1) start = i;
2880 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2886 /******************************************************************
2887 * AttachConsole (KERNEL32.@)
2889 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2891 FIXME("stub %x\n",dwProcessId);
2895 /******************************************************************
2896 * GetConsoleDisplayMode (KERNEL32.@)
2898 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2900 TRACE("semi-stub: %p\n", lpModeFlags);
2901 /* It is safe to successfully report windowed mode */
2906 /******************************************************************
2907 * SetConsoleDisplayMode (KERNEL32.@)
2909 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2910 COORD *lpNewScreenBufferDimensions)
2912 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2913 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2916 /* We cannot switch to fullscreen */
2923 /* ====================================================================
2925 * Console manipulation functions
2927 * ====================================================================*/
2929 /* some missing functions...
2930 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2931 * should get the right API and implement them
2932 * GetConsoleCommandHistory[AW] (dword dword dword)
2933 * GetConsoleCommandHistoryLength[AW]
2934 * SetConsoleCommandHistoryMode
2935 * SetConsoleNumberOfCommands[AW]
2937 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2941 SERVER_START_REQ( get_console_input_history )
2945 if (buf && buf_len > 1)
2947 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2949 if (!wine_server_call_err( req ))
2951 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2952 len = reply->total / sizeof(WCHAR) + 1;
2959 /******************************************************************
2960 * CONSOLE_AppendHistory
2964 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2966 size_t len = strlenW(ptr);
2969 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2970 if (!len) return FALSE;
2972 SERVER_START_REQ( append_console_input_history )
2975 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2976 ret = !wine_server_call_err( req );
2982 /******************************************************************
2983 * CONSOLE_GetNumHistoryEntries
2987 unsigned CONSOLE_GetNumHistoryEntries(void)
2990 SERVER_START_REQ(get_console_input_info)
2993 if (!wine_server_call_err( req )) ret = reply->history_index;
2999 /******************************************************************
3000 * CONSOLE_GetEditionMode
3004 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
3006 unsigned ret = FALSE;
3007 SERVER_START_REQ(get_console_input_info)
3009 req->handle = console_handle_unmap(hConIn);
3010 if ((ret = !wine_server_call_err( req )))
3011 *mode = reply->edition_mode;
3017 /******************************************************************
3022 * 0 if an error occurred, non-zero for success
3025 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3026 DWORD TargetBufferLength, LPWSTR lpExename)
3028 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3029 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3033 /******************************************************************
3034 * GetConsoleProcessList (KERNEL32.@)
3036 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3038 FIXME("(%p,%d): stub\n", processlist, processcount);
3040 if (!processlist || processcount < 1)
3042 SetLastError(ERROR_INVALID_PARAMETER);
3049 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3051 memset(&S_termios, 0, sizeof(S_termios));
3052 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3056 /* FIXME: to be done even if program is a GUI ? */
3057 /* This is wine specific: we have no parent (we're started from unix)
3058 * so, create a simple console with bare handles
3061 wine_server_send_fd(0);
3062 SERVER_START_REQ( alloc_console )
3064 req->access = GENERIC_READ | GENERIC_WRITE;
3065 req->attributes = OBJ_INHERIT;
3066 req->pid = 0xffffffff;
3068 wine_server_call( req );
3069 conin = wine_server_ptr_handle( reply->handle_in );
3070 /* reply->event shouldn't be created by server */
3074 if (!params->hStdInput)
3075 params->hStdInput = conin;
3077 if (!params->hStdOutput)
3079 wine_server_send_fd(1);
3080 SERVER_START_REQ( create_console_output )
3082 req->handle_in = wine_server_obj_handle(conin);
3083 req->access = GENERIC_WRITE|GENERIC_READ;
3084 req->attributes = OBJ_INHERIT;
3085 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3087 wine_server_call(req);
3088 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3092 if (!params->hStdError)
3094 wine_server_send_fd(2);
3095 SERVER_START_REQ( create_console_output )
3097 req->handle_in = wine_server_obj_handle(conin);
3098 req->access = GENERIC_WRITE|GENERIC_READ;
3099 req->attributes = OBJ_INHERIT;
3100 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3102 wine_server_call(req);
3103 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3109 /* convert value from server:
3110 * + 0 => INVALID_HANDLE_VALUE
3111 * + console handle needs to be mapped
3113 if (!params->hStdInput)
3114 params->hStdInput = INVALID_HANDLE_VALUE;
3115 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3117 params->hStdInput = console_handle_map(params->hStdInput);
3118 save_console_mode(params->hStdInput);
3121 if (!params->hStdOutput)
3122 params->hStdOutput = INVALID_HANDLE_VALUE;
3123 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3124 params->hStdOutput = console_handle_map(params->hStdOutput);
3126 if (!params->hStdError)
3127 params->hStdError = INVALID_HANDLE_VALUE;
3128 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3129 params->hStdError = console_handle_map(params->hStdError);
3134 BOOL CONSOLE_Exit(void)
3136 /* the console is in raw mode, put it back in cooked mode */
3137 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));