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>
49 #define WIN32_NO_STATUS
55 #include "wine/server.h"
56 #include "wine/exception.h"
57 #include "wine/unicode.h"
58 #include "wine/debug.h"
60 #include "console_private.h"
61 #include "kernel_private.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(console);
65 static CRITICAL_SECTION CONSOLE_CritSect;
66 static CRITICAL_SECTION_DEBUG critsect_debug =
68 0, 0, &CONSOLE_CritSect,
69 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
70 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
72 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
74 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
75 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
77 /* FIXME: this is not thread safe */
78 static HANDLE console_wait_event;
80 /* map input records to ASCII */
81 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
86 for (i = 0; i < count; i++)
88 if (buffer[i].EventType != KEY_EVENT) continue;
89 WideCharToMultiByte( GetConsoleCP(), 0,
90 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
91 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
95 /* map input records to Unicode */
96 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
101 for (i = 0; i < count; i++)
103 if (buffer[i].EventType != KEY_EVENT) continue;
104 MultiByteToWideChar( GetConsoleCP(), 0,
105 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
106 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
110 /* map char infos to ASCII */
111 static void char_info_WtoA( CHAR_INFO *buffer, int count )
117 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
118 &ch, 1, NULL, NULL );
119 buffer->Char.AsciiChar = ch;
124 /* map char infos to Unicode */
125 static void char_info_AtoW( CHAR_INFO *buffer, int count )
131 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
132 buffer->Char.UnicodeChar = ch;
137 static struct termios S_termios; /* saved termios for bare consoles */
138 static BOOL S_termios_raw /* = FALSE */;
140 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
141 * - a bare console is created for all CUI programs started from command line (without
142 * wineconsole) (let's call those PS)
143 * - of course, every child of a PS which requires console inheritance will get it
144 * - the console termios attributes are saved at the start of program which is attached to be
146 * - if any program attached to a bare console requests input from console, the console is
147 * turned into raw mode
148 * - when the program which created the bare console (the program started from command line)
149 * exits, it will restore the console termios attributes it saved at startup (this
150 * will put back the console into cooked mode if it had been put in raw mode)
151 * - if any other program attached to this bare console is still alive, the Unix shell will put
152 * it in the background, hence forbidding access to the console. Therefore, reading console
153 * input will not be available when the bare console creator has died.
154 * FIXME: This is a limitation of current implementation
157 /* returns the fd for a bare console (-1 otherwise) */
158 static int get_console_bare_fd(HANDLE hin)
162 if (wine_server_handle_to_fd(wine_server_ptr_handle(console_handle_unmap(hin)),
163 0, &fd, NULL) == STATUS_SUCCESS)
168 static BOOL save_console_mode(HANDLE hin)
173 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
174 ret = tcgetattr(fd, &S_termios) >= 0;
179 static BOOL put_console_into_raw_mode(int fd)
181 RtlEnterCriticalSection(&CONSOLE_CritSect);
184 struct termios term = S_termios;
186 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
187 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
188 term.c_cflag &= ~(CSIZE | PARENB);
190 /* FIXME: we should actually disable output processing here
191 * and let kernel32/console.c do the job (with support of enable/disable of
194 /* term.c_oflag &= ~(OPOST); */
196 term.c_cc[VTIME] = 0;
197 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
199 RtlLeaveCriticalSection(&CONSOLE_CritSect);
201 return S_termios_raw;
204 /* put back the console in cooked mode iff we're the process which created the bare console
205 * we don't test if thie process has set the console in raw mode as it could be one of its
208 static BOOL restore_console_mode(HANDLE hin)
213 if (!S_termios_raw ||
214 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
216 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
217 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
223 /******************************************************************************
224 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
227 * Success: hwnd of the console window.
230 HWND WINAPI GetConsoleWindow(VOID)
234 SERVER_START_REQ(get_console_input_info)
237 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
245 /******************************************************************************
246 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
251 UINT WINAPI GetConsoleCP(VOID)
254 UINT codepage = GetOEMCP(); /* default value */
256 SERVER_START_REQ(get_console_input_info)
259 ret = !wine_server_call_err(req);
260 if (ret && reply->input_cp)
261 codepage = reply->input_cp;
269 /******************************************************************************
270 * SetConsoleCP [KERNEL32.@]
272 BOOL WINAPI SetConsoleCP(UINT cp)
276 if (!IsValidCodePage(cp))
278 SetLastError(ERROR_INVALID_PARAMETER);
282 SERVER_START_REQ(set_console_input_info)
285 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
287 ret = !wine_server_call_err(req);
295 /***********************************************************************
296 * GetConsoleOutputCP (KERNEL32.@)
298 UINT WINAPI GetConsoleOutputCP(VOID)
301 UINT codepage = GetOEMCP(); /* default value */
303 SERVER_START_REQ(get_console_input_info)
306 ret = !wine_server_call_err(req);
307 if (ret && reply->output_cp)
308 codepage = reply->output_cp;
316 /******************************************************************************
317 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
320 * cp [I] code page to set
326 BOOL WINAPI SetConsoleOutputCP(UINT cp)
330 if (!IsValidCodePage(cp))
332 SetLastError(ERROR_INVALID_PARAMETER);
336 SERVER_START_REQ(set_console_input_info)
339 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
341 ret = !wine_server_call_err(req);
349 /***********************************************************************
352 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
354 static const char beep = '\a';
355 /* dwFreq and dwDur are ignored by Win95 */
356 if (isatty(2)) write( 2, &beep, 1 );
361 /******************************************************************
362 * OpenConsoleW (KERNEL32.@)
365 * Open a handle to the current process console.
366 * Returns INVALID_HANDLE_VALUE on failure.
368 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
370 HANDLE output = INVALID_HANDLE_VALUE;
373 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
377 if (strcmpiW(coninW, name) == 0)
378 output = (HANDLE) FALSE;
379 else if (strcmpiW(conoutW, name) == 0)
380 output = (HANDLE) TRUE;
383 if (output == INVALID_HANDLE_VALUE)
385 SetLastError(ERROR_INVALID_PARAMETER);
386 return INVALID_HANDLE_VALUE;
388 else if (creation != OPEN_EXISTING)
390 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
391 SetLastError(ERROR_SHARING_VIOLATION);
393 SetLastError(ERROR_INVALID_PARAMETER);
394 return INVALID_HANDLE_VALUE;
397 SERVER_START_REQ( open_console )
399 req->from = wine_server_obj_handle( output );
400 req->access = access;
401 req->attributes = inherit ? OBJ_INHERIT : 0;
402 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
403 wine_server_call_err( req );
404 ret = wine_server_ptr_handle( reply->handle );
408 ret = console_handle_map(ret);
413 /******************************************************************
414 * VerifyConsoleIoHandle (KERNEL32.@)
418 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
422 if (!is_console_handle(handle)) return FALSE;
423 SERVER_START_REQ(get_console_mode)
425 req->handle = console_handle_unmap(handle);
426 ret = !wine_server_call( req );
432 /******************************************************************
433 * DuplicateConsoleHandle (KERNEL32.@)
437 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
442 if (!is_console_handle(handle) ||
443 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
444 GetCurrentProcess(), &ret, access, inherit, options))
445 return INVALID_HANDLE_VALUE;
446 return console_handle_map(ret);
449 /******************************************************************
450 * CloseConsoleHandle (KERNEL32.@)
454 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
456 if (!is_console_handle(handle))
458 SetLastError(ERROR_INVALID_PARAMETER);
461 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
464 /******************************************************************
465 * GetConsoleInputWaitHandle (KERNEL32.@)
469 HANDLE WINAPI GetConsoleInputWaitHandle(void)
471 if (!console_wait_event)
473 SERVER_START_REQ(get_console_wait_event)
475 if (!wine_server_call_err( req ))
476 console_wait_event = wine_server_ptr_handle( reply->handle );
480 return console_wait_event;
484 /******************************************************************************
485 * WriteConsoleInputA [KERNEL32.@]
487 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
488 DWORD count, LPDWORD written )
490 INPUT_RECORD *recW = NULL;
497 SetLastError( ERROR_INVALID_ACCESS );
501 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) )))
503 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
507 memcpy( recW, buffer, count * sizeof(*recW) );
508 input_records_AtoW( recW, count );
511 ret = WriteConsoleInputW( handle, recW, count, written );
512 HeapFree( GetProcessHeap(), 0, recW );
517 /******************************************************************************
518 * WriteConsoleInputW [KERNEL32.@]
520 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
521 DWORD count, LPDWORD written )
523 DWORD events_written = 0;
526 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
528 if (count > 0 && !buffer)
530 SetLastError(ERROR_INVALID_ACCESS);
534 SERVER_START_REQ( write_console_input )
536 req->handle = console_handle_unmap(handle);
537 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
538 if ((ret = !wine_server_call_err( req )))
539 events_written = reply->written;
543 if (written) *written = events_written;
546 SetLastError(ERROR_INVALID_ACCESS);
553 /***********************************************************************
554 * WriteConsoleOutputA (KERNEL32.@)
556 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
557 COORD size, COORD coord, LPSMALL_RECT region )
561 COORD new_size, new_coord;
564 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
565 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
567 if (new_size.X <= 0 || new_size.Y <= 0)
569 region->Bottom = region->Top + new_size.Y - 1;
570 region->Right = region->Left + new_size.X - 1;
574 /* only copy the useful rectangle */
575 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
577 for (y = 0; y < new_size.Y; y++)
579 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
580 new_size.X * sizeof(CHAR_INFO) );
581 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
583 new_coord.X = new_coord.Y = 0;
584 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
585 HeapFree( GetProcessHeap(), 0, ciw );
590 /***********************************************************************
591 * WriteConsoleOutputW (KERNEL32.@)
593 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
594 COORD size, COORD coord, LPSMALL_RECT region )
596 int width, height, y;
599 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
600 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
601 region->Left, region->Top, region->Right, region->Bottom);
603 width = min( region->Right - region->Left + 1, size.X - coord.X );
604 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
606 if (width > 0 && height > 0)
608 for (y = 0; y < height; y++)
610 SERVER_START_REQ( write_console_output )
612 req->handle = console_handle_unmap(hConsoleOutput);
613 req->x = region->Left;
614 req->y = region->Top + y;
615 req->mode = CHAR_INFO_MODE_TEXTATTR;
617 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
618 width * sizeof(CHAR_INFO));
619 if ((ret = !wine_server_call_err( req )))
621 width = min( width, reply->width - region->Left );
622 height = min( height, reply->height - region->Top );
629 region->Bottom = region->Top + height - 1;
630 region->Right = region->Left + width - 1;
635 /******************************************************************************
636 * WriteConsoleOutputCharacterA [KERNEL32.@]
638 * See WriteConsoleOutputCharacterW.
640 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
641 COORD coord, LPDWORD lpNumCharsWritten )
647 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
648 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
654 SetLastError( ERROR_INVALID_ACCESS );
658 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
660 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
662 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
666 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
669 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
670 HeapFree( GetProcessHeap(), 0, strW );
675 /******************************************************************************
676 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
677 * the console screen buffer
680 * hConsoleOutput [I] Handle to screen buffer
681 * attr [I] Pointer to buffer with write attributes
682 * length [I] Number of cells to write to
683 * coord [I] Coords of first cell
684 * lpNumAttrsWritten [O] Pointer to number of cells written
691 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
692 COORD coord, LPDWORD lpNumAttrsWritten )
696 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
698 if ((length > 0 && !attr) || !lpNumAttrsWritten)
700 SetLastError(ERROR_INVALID_ACCESS);
704 *lpNumAttrsWritten = 0;
706 SERVER_START_REQ( write_console_output )
708 req->handle = console_handle_unmap(hConsoleOutput);
711 req->mode = CHAR_INFO_MODE_ATTR;
713 wine_server_add_data( req, attr, length * sizeof(WORD) );
714 if ((ret = !wine_server_call_err( req )))
715 *lpNumAttrsWritten = reply->written;
722 /******************************************************************************
723 * FillConsoleOutputCharacterA [KERNEL32.@]
725 * See FillConsoleOutputCharacterW.
727 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
728 COORD coord, LPDWORD lpNumCharsWritten )
732 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
733 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
737 /******************************************************************************
738 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
741 * hConsoleOutput [I] Handle to screen buffer
742 * ch [I] Character to write
743 * length [I] Number of cells to write to
744 * coord [I] Coords of first cell
745 * lpNumCharsWritten [O] Pointer to number of cells written
751 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
752 COORD coord, LPDWORD lpNumCharsWritten)
756 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
757 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
759 if (!lpNumCharsWritten)
761 SetLastError(ERROR_INVALID_ACCESS);
765 *lpNumCharsWritten = 0;
767 SERVER_START_REQ( fill_console_output )
769 req->handle = console_handle_unmap(hConsoleOutput);
772 req->mode = CHAR_INFO_MODE_TEXT;
776 if ((ret = !wine_server_call_err( req )))
777 *lpNumCharsWritten = reply->written;
784 /******************************************************************************
785 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
788 * hConsoleOutput [I] Handle to screen buffer
789 * attr [I] Color attribute to write
790 * length [I] Number of cells to write to
791 * coord [I] Coords of first cell
792 * lpNumAttrsWritten [O] Pointer to number of cells written
798 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
799 COORD coord, LPDWORD lpNumAttrsWritten )
803 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
804 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
806 if (!lpNumAttrsWritten)
808 SetLastError(ERROR_INVALID_ACCESS);
812 *lpNumAttrsWritten = 0;
814 SERVER_START_REQ( fill_console_output )
816 req->handle = console_handle_unmap(hConsoleOutput);
819 req->mode = CHAR_INFO_MODE_ATTR;
821 req->data.attr = attr;
823 if ((ret = !wine_server_call_err( req )))
824 *lpNumAttrsWritten = reply->written;
831 /******************************************************************************
832 * ReadConsoleOutputCharacterA [KERNEL32.@]
835 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
836 COORD coord, LPDWORD read_count)
844 SetLastError(ERROR_INVALID_ACCESS);
850 if (!(wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR))))
852 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
856 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
858 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
861 HeapFree( GetProcessHeap(), 0, wptr );
866 /******************************************************************************
867 * ReadConsoleOutputCharacterW [KERNEL32.@]
870 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
871 COORD coord, LPDWORD read_count )
875 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
879 SetLastError(ERROR_INVALID_ACCESS);
885 SERVER_START_REQ( read_console_output )
887 req->handle = console_handle_unmap(hConsoleOutput);
890 req->mode = CHAR_INFO_MODE_TEXT;
892 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
893 if ((ret = !wine_server_call_err( req )))
894 *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
901 /******************************************************************************
902 * ReadConsoleOutputAttribute [KERNEL32.@]
904 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
905 COORD coord, LPDWORD read_count)
909 TRACE("(%p,%p,%d,%dx%d,%p)\n",
910 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
914 SetLastError(ERROR_INVALID_ACCESS);
920 SERVER_START_REQ( read_console_output )
922 req->handle = console_handle_unmap(hConsoleOutput);
925 req->mode = CHAR_INFO_MODE_ATTR;
927 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
928 if ((ret = !wine_server_call_err( req )))
929 *read_count = wine_server_reply_size(reply) / sizeof(WORD);
936 /******************************************************************************
937 * ReadConsoleOutputA [KERNEL32.@]
940 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
941 COORD coord, LPSMALL_RECT region )
946 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
947 if (ret && region->Right >= region->Left)
949 for (y = 0; y <= region->Bottom - region->Top; y++)
951 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
952 region->Right - region->Left + 1 );
959 /******************************************************************************
960 * ReadConsoleOutputW [KERNEL32.@]
962 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
963 * think we need to be *that* compatible. -- AJ
965 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
966 COORD coord, LPSMALL_RECT region )
968 int width, height, y;
971 width = min( region->Right - region->Left + 1, size.X - coord.X );
972 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
974 if (width > 0 && height > 0)
976 for (y = 0; y < height; y++)
978 SERVER_START_REQ( read_console_output )
980 req->handle = console_handle_unmap(hConsoleOutput);
981 req->x = region->Left;
982 req->y = region->Top + y;
983 req->mode = CHAR_INFO_MODE_TEXTATTR;
985 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
986 width * sizeof(CHAR_INFO) );
987 if ((ret = !wine_server_call_err( req )))
989 width = min( width, reply->width - region->Left );
990 height = min( height, reply->height - region->Top );
997 region->Bottom = region->Top + height - 1;
998 region->Right = region->Left + width - 1;
1003 /******************************************************************************
1004 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
1007 * handle [I] Handle to console input buffer
1008 * buffer [O] Address of buffer for read data
1009 * count [I] Number of records to read
1010 * pRead [O] Address of number of records read
1016 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1020 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
1021 input_records_WtoA( buffer, read );
1022 if (pRead) *pRead = read;
1027 /***********************************************************************
1028 * PeekConsoleInputA (KERNEL32.@)
1030 * Gets 'count' first events (or less) from input queue.
1032 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1036 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
1037 input_records_WtoA( buffer, read );
1038 if (pRead) *pRead = read;
1043 /***********************************************************************
1044 * PeekConsoleInputW (KERNEL32.@)
1046 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
1049 SERVER_START_REQ( read_console_input )
1051 req->handle = console_handle_unmap(handle);
1053 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1054 if ((ret = !wine_server_call_err( req )))
1056 if (read) *read = count ? reply->read : 0;
1064 /***********************************************************************
1065 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1067 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1070 SERVER_START_REQ( read_console_input )
1072 req->handle = console_handle_unmap(handle);
1074 if ((ret = !wine_server_call_err( req )))
1077 *nrofevents = reply->read;
1080 SetLastError(ERROR_INVALID_ACCESS);
1090 /******************************************************************************
1091 * read_console_input
1093 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1096 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1098 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1100 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1102 enum read_console_input_return ret;
1106 size_t idx = 0, idxw;
1110 struct pollfd pollfd;
1111 BOOL locked = FALSE, next_char;
1115 if (idx == sizeof(input))
1117 FIXME("buffer too small (%s)\n", wine_dbgstr_an(input, idx));
1122 pollfd.events = POLLIN;
1126 switch (poll(&pollfd, 1, timeout))
1131 RtlEnterCriticalSection(&CONSOLE_CritSect);
1134 i = read(fd, &input[idx], 1);
1142 /* actually another thread likely beat us to reading the char
1143 * return rci_gotone, while not perfect, it should work in most of the cases (as the new event
1144 * should be now in the queue, fed from the other thread)
1151 numEvent = TERM_FillInputRecord(input, idx, ir);
1155 /* we need more char(s) to tell if it matches a key-db entry. wait 1/2s for next char */
1160 /* we haven't found the string into key-db, push full input string into server */
1161 idxw = MultiByteToWideChar(CP_UNIXCP, 0, input, idx, inputw, sizeof(inputw) / sizeof(inputw[0]));
1163 /* we cannot translate yet... likely we need more chars (wait max 1/2s for next char) */
1170 for (i = 0; i < idxw; i++)
1172 numEvent = TERM_FillSimpleChar(inputw[i], ir);
1173 WriteConsoleInputW(handle, ir, numEvent, &written);
1178 /* we got a transformation from key-db... push this into server */
1179 ret = WriteConsoleInputW(handle, ir, numEvent, &written) ? rci_gotone : rci_error;
1183 case 0: ret = rci_timeout; break;
1184 default: ret = rci_error; break;
1186 } while (next_char);
1187 if (locked) RtlLeaveCriticalSection(&CONSOLE_CritSect);
1192 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1195 enum read_console_input_return ret;
1197 if ((fd = get_console_bare_fd(handle)) != -1)
1199 put_console_into_raw_mode(fd);
1200 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1202 ret = bare_console_fetch_input(handle, fd, timeout);
1204 else ret = rci_gotone;
1206 if (ret != rci_gotone) return ret;
1210 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1212 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1216 SERVER_START_REQ( read_console_input )
1218 req->handle = console_handle_unmap(handle);
1220 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1221 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1222 else ret = rci_gotone;
1230 /***********************************************************************
1231 * FlushConsoleInputBuffer (KERNEL32.@)
1233 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1235 enum read_console_input_return last;
1238 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1240 return last == rci_timeout;
1244 /***********************************************************************
1245 * SetConsoleTitleA (KERNEL32.@)
1247 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1252 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1253 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1254 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1255 ret = SetConsoleTitleW(titleW);
1256 HeapFree(GetProcessHeap(), 0, titleW);
1261 /***********************************************************************
1262 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1264 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1266 FIXME( "stub %p\n", layoutName);
1270 /***********************************************************************
1271 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1273 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1275 FIXME( "stub %p\n", layoutName);
1279 static WCHAR input_exe[MAX_PATH + 1];
1281 /***********************************************************************
1282 * GetConsoleInputExeNameW (KERNEL32.@)
1284 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1286 TRACE("%u %p\n", buflen, buffer);
1288 RtlEnterCriticalSection(&CONSOLE_CritSect);
1289 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1290 else SetLastError(ERROR_BUFFER_OVERFLOW);
1291 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1296 /***********************************************************************
1297 * GetConsoleInputExeNameA (KERNEL32.@)
1299 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1301 TRACE("%u %p\n", buflen, buffer);
1303 RtlEnterCriticalSection(&CONSOLE_CritSect);
1304 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1305 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1306 else SetLastError(ERROR_BUFFER_OVERFLOW);
1307 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1312 /***********************************************************************
1313 * GetConsoleTitleA (KERNEL32.@)
1315 * See GetConsoleTitleW.
1317 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1319 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1323 ret = GetConsoleTitleW( ptr, size );
1326 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1327 ret = strlen(title);
1329 HeapFree(GetProcessHeap(), 0, ptr);
1334 /******************************************************************************
1335 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1338 * title [O] Address of buffer for title
1339 * size [I] Size of buffer
1342 * Success: Length of string copied
1345 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1349 SERVER_START_REQ( get_console_input_info )
1352 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1353 if (!wine_server_call_err( req ))
1355 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1364 /***********************************************************************
1365 * GetLargestConsoleWindowSize (KERNEL32.@)
1368 * This should return a COORD, but calling convention for returning
1369 * structures is different between Windows and gcc on i386.
1374 #undef GetLargestConsoleWindowSize
1375 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1383 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1386 #endif /* defined(__i386__) */
1389 /***********************************************************************
1390 * GetLargestConsoleWindowSize (KERNEL32.@)
1393 * This should return a COORD, but calling convention for returning
1394 * structures is different between Windows and gcc on i386.
1399 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1404 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1407 #endif /* defined(__i386__) */
1409 static WCHAR* S_EditString /* = NULL */;
1410 static unsigned S_EditStrPos /* = 0 */;
1412 /***********************************************************************
1413 * FreeConsole (KERNEL32.@)
1415 BOOL WINAPI FreeConsole(VOID)
1419 /* invalidate local copy of input event handle */
1420 console_wait_event = 0;
1422 SERVER_START_REQ(free_console)
1424 ret = !wine_server_call_err( req );
1430 /******************************************************************
1431 * start_console_renderer
1433 * helper for AllocConsole
1434 * starts the renderer process
1436 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1441 PROCESS_INFORMATION pi;
1443 /* FIXME: use dynamic allocation for most of the buffers below */
1444 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1445 if ((ret > -1) && (ret < sizeof(buffer)) &&
1446 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1447 NULL, NULL, si, &pi))
1453 wh[1] = pi.hProcess;
1454 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1456 CloseHandle(pi.hThread);
1457 CloseHandle(pi.hProcess);
1459 if (ret != WAIT_OBJECT_0) return FALSE;
1461 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1462 pi.dwProcessId, pi.dwThreadId);
1469 static BOOL start_console_renderer(STARTUPINFOA* si)
1473 OBJECT_ATTRIBUTES attr;
1476 attr.Length = sizeof(attr);
1477 attr.RootDirectory = 0;
1478 attr.Attributes = OBJ_INHERIT;
1479 attr.ObjectName = NULL;
1480 attr.SecurityDescriptor = NULL;
1481 attr.SecurityQualityOfService = NULL;
1483 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1484 if (!hEvent) return FALSE;
1486 /* first try environment variable */
1487 if ((p = getenv("WINECONSOLE")) != NULL)
1489 ret = start_console_renderer_helper(p, si, hEvent);
1491 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1492 "trying default access\n", p);
1495 /* then try the regular PATH */
1497 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1499 CloseHandle(hEvent);
1503 /***********************************************************************
1504 * AllocConsole (KERNEL32.@)
1506 * creates an xterm with a pty to our program
1508 BOOL WINAPI AllocConsole(void)
1510 HANDLE handle_in = INVALID_HANDLE_VALUE;
1511 HANDLE handle_out = INVALID_HANDLE_VALUE;
1512 HANDLE handle_err = INVALID_HANDLE_VALUE;
1513 STARTUPINFOA siCurrent;
1514 STARTUPINFOA siConsole;
1519 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1520 FALSE, OPEN_EXISTING );
1522 if (VerifyConsoleIoHandle(handle_in))
1524 /* we already have a console opened on this process, don't create a new one */
1525 CloseHandle(handle_in);
1529 /* invalidate local copy of input event handle */
1530 console_wait_event = 0;
1532 GetStartupInfoA(&siCurrent);
1534 memset(&siConsole, 0, sizeof(siConsole));
1535 siConsole.cb = sizeof(siConsole);
1536 /* setup a view arguments for wineconsole (it'll use them as default values) */
1537 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1539 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1540 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1541 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1543 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1545 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1546 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1548 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1550 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1551 siConsole.wShowWindow = siCurrent.wShowWindow;
1553 /* FIXME (should pass the unicode form) */
1554 if (siCurrent.lpTitle)
1555 siConsole.lpTitle = siCurrent.lpTitle;
1556 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1558 buffer[sizeof(buffer) - 1] = '\0';
1559 siConsole.lpTitle = buffer;
1562 if (!start_console_renderer(&siConsole))
1565 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1566 /* all std I/O handles are inheritable by default */
1567 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1568 TRUE, OPEN_EXISTING );
1569 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1571 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1572 TRUE, OPEN_EXISTING );
1573 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1575 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1576 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1579 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1580 handle_in = siCurrent.hStdInput;
1581 handle_out = siCurrent.hStdOutput;
1582 handle_err = siCurrent.hStdError;
1585 /* NT resets the STD_*_HANDLEs on console alloc */
1586 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1587 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1588 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1590 SetLastError(ERROR_SUCCESS);
1595 ERR("Can't allocate console\n");
1596 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1597 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1598 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1604 /***********************************************************************
1605 * ReadConsoleA (KERNEL32.@)
1607 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1608 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1610 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1614 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1615 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1617 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1618 HeapFree(GetProcessHeap(), 0, ptr);
1623 /***********************************************************************
1624 * ReadConsoleW (KERNEL32.@)
1626 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1627 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1630 LPWSTR xbuf = lpBuffer;
1632 BOOL is_bare = FALSE;
1635 TRACE("(%p,%p,%d,%p,%p)\n",
1636 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1638 if (!GetConsoleMode(hConsoleInput, &mode))
1640 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1645 if (mode & ENABLE_LINE_INPUT)
1647 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1649 HeapFree(GetProcessHeap(), 0, S_EditString);
1650 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1654 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1655 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1656 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1657 S_EditStrPos += charsread;
1662 DWORD timeout = INFINITE;
1664 /* FIXME: should we read at least 1 char? The SDK does not say */
1665 /* wait for at least one available input record (it doesn't mean we'll have
1666 * chars stored in xbuf...)
1668 * Although SDK doc keeps silence about 1 char, SDK examples assume
1669 * that we should wait for at least one character (not key). --KS
1674 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1675 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1676 ir.Event.KeyEvent.uChar.UnicodeChar)
1678 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1681 } while (charsread < nNumberOfCharsToRead);
1682 /* nothing has been read */
1683 if (timeout == INFINITE) return FALSE;
1686 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1692 /***********************************************************************
1693 * ReadConsoleInputW (KERNEL32.@)
1695 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1696 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1699 DWORD timeout = INFINITE;
1703 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1707 /* loop until we get at least one event */
1708 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1712 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1717 /******************************************************************************
1718 * WriteConsoleOutputCharacterW [KERNEL32.@]
1720 * Copy character to consecutive cells in the console screen buffer.
1723 * hConsoleOutput [I] Handle to screen buffer
1724 * str [I] Pointer to buffer with chars to write
1725 * length [I] Number of cells to write to
1726 * coord [I] Coords of first cell
1727 * lpNumCharsWritten [O] Pointer to number of cells written
1734 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1735 COORD coord, LPDWORD lpNumCharsWritten )
1739 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1740 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1742 if ((length > 0 && !str) || !lpNumCharsWritten)
1744 SetLastError(ERROR_INVALID_ACCESS);
1748 *lpNumCharsWritten = 0;
1750 SERVER_START_REQ( write_console_output )
1752 req->handle = console_handle_unmap(hConsoleOutput);
1755 req->mode = CHAR_INFO_MODE_TEXT;
1757 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1758 if ((ret = !wine_server_call_err( req )))
1759 *lpNumCharsWritten = reply->written;
1766 /******************************************************************************
1767 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1770 * title [I] Address of new title
1776 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1780 TRACE("(%s)\n", debugstr_w(title));
1781 SERVER_START_REQ( set_console_input_info )
1784 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1785 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1786 ret = !wine_server_call_err( req );
1793 /***********************************************************************
1794 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1796 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1798 FIXME("(%p): stub\n", nrofbuttons);
1803 /******************************************************************************
1804 * SetConsoleInputExeNameW [KERNEL32.@]
1806 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1808 TRACE("(%s)\n", debugstr_w(name));
1810 if (!name || !name[0])
1812 SetLastError(ERROR_INVALID_PARAMETER);
1816 RtlEnterCriticalSection(&CONSOLE_CritSect);
1817 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1818 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1823 /******************************************************************************
1824 * SetConsoleInputExeNameA [KERNEL32.@]
1826 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1832 if (!name || !name[0])
1834 SetLastError(ERROR_INVALID_PARAMETER);
1838 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1839 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1841 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1842 ret = SetConsoleInputExeNameW(nameW);
1843 HeapFree(GetProcessHeap(), 0, nameW);
1848 /******************************************************************
1849 * CONSOLE_DefaultHandler
1851 * Final control event handler
1853 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1855 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1857 /* should never go here */
1861 /******************************************************************************
1862 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1865 * func [I] Address of handler function
1866 * add [I] Handler to add or remove
1873 struct ConsoleHandler
1875 PHANDLER_ROUTINE handler;
1876 struct ConsoleHandler* next;
1879 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1880 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1882 /*****************************************************************************/
1884 /******************************************************************
1885 * SetConsoleCtrlHandler (KERNEL32.@)
1887 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1891 TRACE("(%p,%i)\n", func, add);
1895 RtlEnterCriticalSection(&CONSOLE_CritSect);
1897 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1899 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1900 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1904 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1906 if (!ch) return FALSE;
1908 RtlEnterCriticalSection(&CONSOLE_CritSect);
1909 ch->next = CONSOLE_Handlers;
1910 CONSOLE_Handlers = ch;
1911 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1915 struct ConsoleHandler** ch;
1916 RtlEnterCriticalSection(&CONSOLE_CritSect);
1917 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1919 if ((*ch)->handler == func) break;
1923 struct ConsoleHandler* rch = *ch;
1926 if (rch == &CONSOLE_DefaultConsoleHandler)
1928 ERR("Who's trying to remove default handler???\n");
1929 SetLastError(ERROR_INVALID_PARAMETER);
1935 HeapFree(GetProcessHeap(), 0, rch);
1940 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1941 SetLastError(ERROR_INVALID_PARAMETER);
1944 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1949 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1951 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1952 return EXCEPTION_EXECUTE_HANDLER;
1955 /******************************************************************
1956 * CONSOLE_SendEventThread
1958 * Internal helper to pass an event to the list on installed handlers
1960 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1962 DWORD_PTR event = (DWORD_PTR)pmt;
1963 struct ConsoleHandler* ch;
1965 if (event == CTRL_C_EVENT)
1967 BOOL caught_by_dbg = TRUE;
1968 /* First, try to pass the ctrl-C event to the debugger (if any)
1969 * If it continues, there's nothing more to do
1970 * Otherwise, we need to send the ctrl-C event to the handlers
1974 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1976 __EXCEPT(CONSOLE_CtrlEventHandler)
1978 caught_by_dbg = FALSE;
1981 if (caught_by_dbg) return 0;
1982 /* the debugger didn't continue... so, pass to ctrl handlers */
1984 RtlEnterCriticalSection(&CONSOLE_CritSect);
1985 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1987 if (ch->handler(event)) break;
1989 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1993 /******************************************************************
1994 * CONSOLE_HandleCtrlC
1996 * Check whether the shall manipulate CtrlC events
1998 int CONSOLE_HandleCtrlC(unsigned sig)
2000 /* FIXME: better test whether a console is attached to this process ??? */
2001 extern unsigned CONSOLE_GetNumHistoryEntries(void);
2002 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
2004 /* check if we have to ignore ctrl-C events */
2005 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
2007 /* Create a separate thread to signal all the events.
2008 * This is needed because:
2009 * - this function can be called in an Unix signal handler (hence on an
2010 * different stack than the thread that's running). This breaks the
2011 * Win32 exception mechanisms (where the thread's stack is checked).
2012 * - since the current thread, while processing the signal, can hold the
2013 * console critical section, we need another execution environment where
2014 * we can wait on this critical section
2016 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2021 /******************************************************************************
2022 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2025 * dwCtrlEvent [I] Type of event
2026 * dwProcessGroupID [I] Process group ID to send event to
2030 * Failure: False (and *should* [but doesn't] set LastError)
2032 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2033 DWORD dwProcessGroupID)
2037 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2039 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2041 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2045 SERVER_START_REQ( send_console_signal )
2047 req->signal = dwCtrlEvent;
2048 req->group_id = dwProcessGroupID;
2049 ret = !wine_server_call_err( req );
2053 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2054 * have been handled by all processes in the given group?
2055 * As of today, we don't wait...
2061 /******************************************************************************
2062 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2065 * dwDesiredAccess [I] Access flag
2066 * dwShareMode [I] Buffer share mode
2067 * sa [I] Security attributes
2068 * dwFlags [I] Type of buffer to create
2069 * lpScreenBufferData [I] Reserved
2072 * Should call SetLastError
2075 * Success: Handle to new console screen buffer
2076 * Failure: INVALID_HANDLE_VALUE
2078 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2079 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2080 LPVOID lpScreenBufferData)
2082 HANDLE ret = INVALID_HANDLE_VALUE;
2084 TRACE("(%d,%d,%p,%d,%p)\n",
2085 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2087 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2089 SetLastError(ERROR_INVALID_PARAMETER);
2090 return INVALID_HANDLE_VALUE;
2093 SERVER_START_REQ(create_console_output)
2096 req->access = dwDesiredAccess;
2097 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2098 req->share = dwShareMode;
2100 if (!wine_server_call_err( req ))
2101 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2109 /***********************************************************************
2110 * GetConsoleScreenBufferInfo (KERNEL32.@)
2112 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2116 SERVER_START_REQ(get_console_output_info)
2118 req->handle = console_handle_unmap(hConsoleOutput);
2119 if ((ret = !wine_server_call_err( req )))
2121 csbi->dwSize.X = reply->width;
2122 csbi->dwSize.Y = reply->height;
2123 csbi->dwCursorPosition.X = reply->cursor_x;
2124 csbi->dwCursorPosition.Y = reply->cursor_y;
2125 csbi->wAttributes = reply->attr;
2126 csbi->srWindow.Left = reply->win_left;
2127 csbi->srWindow.Right = reply->win_right;
2128 csbi->srWindow.Top = reply->win_top;
2129 csbi->srWindow.Bottom = reply->win_bottom;
2130 csbi->dwMaximumWindowSize.X = reply->max_width;
2131 csbi->dwMaximumWindowSize.Y = reply->max_height;
2136 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2137 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2138 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2140 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2141 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2147 /******************************************************************************
2148 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2154 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2158 TRACE("(%p)\n", hConsoleOutput);
2160 SERVER_START_REQ( set_console_input_info )
2163 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2164 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2165 ret = !wine_server_call_err( req );
2172 /***********************************************************************
2173 * GetConsoleMode (KERNEL32.@)
2175 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2179 SERVER_START_REQ( get_console_mode )
2181 req->handle = console_handle_unmap(hcon);
2182 if ((ret = !wine_server_call_err( req )))
2184 if (mode) *mode = reply->mode;
2192 /******************************************************************************
2193 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2196 * hcon [I] Handle to console input or screen buffer
2197 * mode [I] Input or output mode to set
2204 * ENABLE_PROCESSED_INPUT 0x01
2205 * ENABLE_LINE_INPUT 0x02
2206 * ENABLE_ECHO_INPUT 0x04
2207 * ENABLE_WINDOW_INPUT 0x08
2208 * ENABLE_MOUSE_INPUT 0x10
2210 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2214 SERVER_START_REQ(set_console_mode)
2216 req->handle = console_handle_unmap(hcon);
2218 ret = !wine_server_call_err( req );
2221 /* FIXME: when resetting a console input to editline mode, I think we should
2222 * empty the S_EditString buffer
2225 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2231 /******************************************************************
2232 * CONSOLE_WriteChars
2234 * WriteConsoleOutput helper: hides server call semantics
2235 * writes a string at a given pos with standard attribute
2237 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2243 SERVER_START_REQ( write_console_output )
2245 req->handle = console_handle_unmap(hCon);
2248 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2250 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2251 if (!wine_server_call_err( req )) written = reply->written;
2255 if (written > 0) pos->X += written;
2259 /******************************************************************
2262 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2265 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2271 csbi->dwCursorPosition.X = 0;
2272 csbi->dwCursorPosition.Y++;
2274 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2277 src.Bottom = csbi->dwSize.Y - 1;
2279 src.Right = csbi->dwSize.X - 1;
2284 ci.Attributes = csbi->wAttributes;
2285 ci.Char.UnicodeChar = ' ';
2287 csbi->dwCursorPosition.Y--;
2288 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2293 /******************************************************************
2296 * WriteConsoleOutput helper: writes a block of non special characters
2297 * Block can spread on several lines, and wrapping, if needed, is
2301 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2302 DWORD mode, LPCWSTR ptr, int len)
2304 int blk; /* number of chars to write on current line */
2305 int done; /* number of chars already written */
2307 if (len <= 0) return 1;
2309 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2311 for (done = 0; done < len; done += blk)
2313 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2315 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2317 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2323 int pos = csbi->dwCursorPosition.X;
2324 /* FIXME: we could reduce the number of loops
2325 * but, in most cases we wouldn't gain lots of time (it would only
2326 * happen if we're asked to overwrite more than twice the part of the line,
2329 for (done = 0; done < len; done += blk)
2331 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2333 csbi->dwCursorPosition.X = pos;
2334 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2342 /***********************************************************************
2343 * WriteConsoleW (KERNEL32.@)
2345 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2346 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2350 const WCHAR* psz = lpBuffer;
2351 CONSOLE_SCREEN_BUFFER_INFO csbi;
2352 int k, first = 0, fd;
2354 TRACE("%p %s %d %p %p\n",
2355 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2356 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2358 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2360 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2367 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2370 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2371 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2374 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2375 ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2376 ptr, len, lpNumberOfCharsWritten, NULL);
2377 if (ret && lpNumberOfCharsWritten)
2379 if (*lpNumberOfCharsWritten == len)
2380 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2382 FIXME("Conversion not supported yet\n");
2384 HeapFree(GetProcessHeap(), 0, ptr);
2388 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2391 if (!nNumberOfCharsToWrite) return TRUE;
2393 if (mode & ENABLE_PROCESSED_OUTPUT)
2397 for (i = 0; i < nNumberOfCharsToWrite; i++)
2401 case '\b': case '\t': case '\n': case '\a': case '\r':
2402 /* don't handle here the i-th char... done below */
2403 if ((k = i - first) > 0)
2405 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2415 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2419 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2421 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2422 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2427 next_line(hConsoleOutput, &csbi);
2433 csbi.dwCursorPosition.X = 0;
2441 /* write the remaining block (if any) if processed output is enabled, or the
2442 * entire buffer otherwise
2444 if ((k = nNumberOfCharsToWrite - first) > 0)
2446 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2452 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2453 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2458 /***********************************************************************
2459 * WriteConsoleA (KERNEL32.@)
2461 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2462 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2468 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2470 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2471 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2472 if (!xstring) return 0;
2474 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2476 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2478 HeapFree(GetProcessHeap(), 0, xstring);
2483 /******************************************************************************
2484 * SetConsoleCursorPosition [KERNEL32.@]
2485 * Sets the cursor position in console
2488 * hConsoleOutput [I] Handle of console screen buffer
2489 * dwCursorPosition [I] New cursor position coordinates
2495 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2498 CONSOLE_SCREEN_BUFFER_INFO csbi;
2502 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2504 SERVER_START_REQ(set_console_output_info)
2506 req->handle = console_handle_unmap(hcon);
2507 req->cursor_x = pos.X;
2508 req->cursor_y = pos.Y;
2509 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2510 ret = !wine_server_call_err( req );
2514 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2517 /* if cursor is no longer visible, scroll the visible window... */
2518 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2519 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2520 if (pos.X < csbi.srWindow.Left)
2522 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2525 else if (pos.X > csbi.srWindow.Right)
2527 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2530 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2532 if (pos.Y < csbi.srWindow.Top)
2534 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2537 else if (pos.Y > csbi.srWindow.Bottom)
2539 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2542 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2544 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2549 /******************************************************************************
2550 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2553 * hcon [I] Handle to console screen buffer
2554 * cinfo [O] Address of cursor information
2560 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2564 SERVER_START_REQ(get_console_output_info)
2566 req->handle = console_handle_unmap(hCon);
2567 ret = !wine_server_call_err( req );
2570 cinfo->dwSize = reply->cursor_size;
2571 cinfo->bVisible = reply->cursor_visible;
2576 if (!ret) return FALSE;
2580 SetLastError(ERROR_INVALID_ACCESS);
2583 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2589 /******************************************************************************
2590 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2593 * hcon [I] Handle to console screen buffer
2594 * cinfo [I] Address of cursor information
2599 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2603 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2604 SERVER_START_REQ(set_console_output_info)
2606 req->handle = console_handle_unmap(hCon);
2607 req->cursor_size = cinfo->dwSize;
2608 req->cursor_visible = cinfo->bVisible;
2609 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2610 ret = !wine_server_call_err( req );
2617 /******************************************************************************
2618 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2621 * hcon [I] Handle to console screen buffer
2622 * bAbsolute [I] Coordinate type flag
2623 * window [I] Address of new window rectangle
2628 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2630 SMALL_RECT p = *window;
2633 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2637 CONSOLE_SCREEN_BUFFER_INFO csbi;
2639 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2641 p.Left += csbi.srWindow.Left;
2642 p.Top += csbi.srWindow.Top;
2643 p.Right += csbi.srWindow.Right;
2644 p.Bottom += csbi.srWindow.Bottom;
2646 SERVER_START_REQ(set_console_output_info)
2648 req->handle = console_handle_unmap(hCon);
2649 req->win_left = p.Left;
2650 req->win_top = p.Top;
2651 req->win_right = p.Right;
2652 req->win_bottom = p.Bottom;
2653 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2654 ret = !wine_server_call_err( req );
2662 /******************************************************************************
2663 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2665 * Sets the foreground and background color attributes of characters
2666 * written to the screen buffer.
2672 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2676 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2677 SERVER_START_REQ(set_console_output_info)
2679 req->handle = console_handle_unmap(hConsoleOutput);
2681 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2682 ret = !wine_server_call_err( req );
2689 /******************************************************************************
2690 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2693 * hConsoleOutput [I] Handle to console screen buffer
2694 * dwSize [I] New size in character rows and cols
2700 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2704 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2705 SERVER_START_REQ(set_console_output_info)
2707 req->handle = console_handle_unmap(hConsoleOutput);
2708 req->width = dwSize.X;
2709 req->height = dwSize.Y;
2710 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2711 ret = !wine_server_call_err( req );
2718 /******************************************************************************
2719 * ScrollConsoleScreenBufferA [KERNEL32.@]
2722 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2723 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2728 ciw.Attributes = lpFill->Attributes;
2729 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2731 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2732 dwDestOrigin, &ciw);
2735 /******************************************************************
2736 * CONSOLE_FillLineUniform
2738 * Helper function for ScrollConsoleScreenBufferW
2739 * Fills a part of a line with a constant character info
2741 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2743 SERVER_START_REQ( fill_console_output )
2745 req->handle = console_handle_unmap(hConsoleOutput);
2746 req->mode = CHAR_INFO_MODE_TEXTATTR;
2751 req->data.ch = lpFill->Char.UnicodeChar;
2752 req->data.attr = lpFill->Attributes;
2753 wine_server_call_err( req );
2758 /******************************************************************************
2759 * ScrollConsoleScreenBufferW [KERNEL32.@]
2763 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2764 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2772 CONSOLE_SCREEN_BUFFER_INFO csbi;
2777 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2778 lpScrollRect->Left, lpScrollRect->Top,
2779 lpScrollRect->Right, lpScrollRect->Bottom,
2780 lpClipRect->Left, lpClipRect->Top,
2781 lpClipRect->Right, lpClipRect->Bottom,
2782 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2784 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2785 lpScrollRect->Left, lpScrollRect->Top,
2786 lpScrollRect->Right, lpScrollRect->Bottom,
2787 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2789 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2792 src.X = lpScrollRect->Left;
2793 src.Y = lpScrollRect->Top;
2795 /* step 1: get dst rect */
2796 dst.Left = dwDestOrigin.X;
2797 dst.Top = dwDestOrigin.Y;
2798 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2799 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2801 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2804 clip.Left = max(0, lpClipRect->Left);
2805 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2806 clip.Top = max(0, lpClipRect->Top);
2807 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2812 clip.Right = csbi.dwSize.X - 1;
2814 clip.Bottom = csbi.dwSize.Y - 1;
2816 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2818 /* step 2b: clip dst rect */
2819 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2820 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2821 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2822 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2824 /* step 3: transfer the bits */
2825 SERVER_START_REQ(move_console_output)
2827 req->handle = console_handle_unmap(hConsoleOutput);
2830 req->x_dst = dst.Left;
2831 req->y_dst = dst.Top;
2832 req->w = dst.Right - dst.Left + 1;
2833 req->h = dst.Bottom - dst.Top + 1;
2834 ret = !wine_server_call_err( req );
2838 if (!ret) return FALSE;
2840 /* step 4: clean out the exposed part */
2842 /* have to write cell [i,j] if it is not in dst rect (because it has already
2843 * been written to by the scroll) and is in clip (we shall not write
2846 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2848 inside = dst.Top <= j && j <= dst.Bottom;
2850 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2852 if (inside && dst.Left <= i && i <= dst.Right)
2856 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2862 if (start == -1) start = i;
2866 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2872 /******************************************************************
2873 * AttachConsole (KERNEL32.@)
2875 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2877 FIXME("stub %x\n",dwProcessId);
2881 /******************************************************************
2882 * GetConsoleDisplayMode (KERNEL32.@)
2884 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2886 TRACE("semi-stub: %p\n", lpModeFlags);
2887 /* It is safe to successfully report windowed mode */
2892 /******************************************************************
2893 * SetConsoleDisplayMode (KERNEL32.@)
2895 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2896 COORD *lpNewScreenBufferDimensions)
2898 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2899 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2902 /* We cannot switch to fullscreen */
2909 /* ====================================================================
2911 * Console manipulation functions
2913 * ====================================================================*/
2915 /* some missing functions...
2916 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2917 * should get the right API and implement them
2918 * GetConsoleCommandHistory[AW] (dword dword dword)
2919 * GetConsoleCommandHistoryLength[AW]
2920 * SetConsoleCommandHistoryMode
2921 * SetConsoleNumberOfCommands[AW]
2923 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2927 SERVER_START_REQ( get_console_input_history )
2931 if (buf && buf_len > 1)
2933 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2935 if (!wine_server_call_err( req ))
2937 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2938 len = reply->total / sizeof(WCHAR) + 1;
2945 /******************************************************************
2946 * CONSOLE_AppendHistory
2950 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2952 size_t len = strlenW(ptr);
2955 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2956 if (!len) return FALSE;
2958 SERVER_START_REQ( append_console_input_history )
2961 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2962 ret = !wine_server_call_err( req );
2968 /******************************************************************
2969 * CONSOLE_GetNumHistoryEntries
2973 unsigned CONSOLE_GetNumHistoryEntries(void)
2976 SERVER_START_REQ(get_console_input_info)
2979 if (!wine_server_call_err( req )) ret = reply->history_index;
2985 /******************************************************************
2986 * CONSOLE_GetEditionMode
2990 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2992 unsigned ret = FALSE;
2993 SERVER_START_REQ(get_console_input_info)
2995 req->handle = console_handle_unmap(hConIn);
2996 if ((ret = !wine_server_call_err( req )))
2997 *mode = reply->edition_mode;
3003 /******************************************************************
3008 * 0 if an error occurred, non-zero for success
3011 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3012 DWORD TargetBufferLength, LPWSTR lpExename)
3014 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3015 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3019 /******************************************************************
3020 * GetConsoleProcessList (KERNEL32.@)
3022 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3024 FIXME("(%p,%d): stub\n", processlist, processcount);
3026 if (!processlist || processcount < 1)
3028 SetLastError(ERROR_INVALID_PARAMETER);
3035 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3037 memset(&S_termios, 0, sizeof(S_termios));
3038 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3042 /* FIXME: to be done even if program is a GUI ? */
3043 /* This is wine specific: we have no parent (we're started from unix)
3044 * so, create a simple console with bare handles
3047 wine_server_send_fd(0);
3048 SERVER_START_REQ( alloc_console )
3050 req->access = GENERIC_READ | GENERIC_WRITE;
3051 req->attributes = OBJ_INHERIT;
3052 req->pid = 0xffffffff;
3054 wine_server_call( req );
3055 conin = wine_server_ptr_handle( reply->handle_in );
3056 /* reply->event shouldn't be created by server */
3060 if (!params->hStdInput)
3061 params->hStdInput = conin;
3063 if (!params->hStdOutput)
3065 wine_server_send_fd(1);
3066 SERVER_START_REQ( create_console_output )
3068 req->handle_in = wine_server_obj_handle(conin);
3069 req->access = GENERIC_WRITE|GENERIC_READ;
3070 req->attributes = OBJ_INHERIT;
3071 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3073 wine_server_call(req);
3074 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3078 if (!params->hStdError)
3080 wine_server_send_fd(2);
3081 SERVER_START_REQ( create_console_output )
3083 req->handle_in = wine_server_obj_handle(conin);
3084 req->access = GENERIC_WRITE|GENERIC_READ;
3085 req->attributes = OBJ_INHERIT;
3086 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3088 wine_server_call(req);
3089 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3095 /* convert value from server:
3096 * + 0 => INVALID_HANDLE_VALUE
3097 * + console handle needs to be mapped
3099 if (!params->hStdInput)
3100 params->hStdInput = INVALID_HANDLE_VALUE;
3101 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3103 params->hStdInput = console_handle_map(params->hStdInput);
3104 save_console_mode(params->hStdInput);
3107 if (!params->hStdOutput)
3108 params->hStdOutput = INVALID_HANDLE_VALUE;
3109 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3110 params->hStdOutput = console_handle_map(params->hStdOutput);
3112 if (!params->hStdError)
3113 params->hStdError = INVALID_HANDLE_VALUE;
3114 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3115 params->hStdError = console_handle_map(params->hStdError);
3120 BOOL CONSOLE_Exit(void)
3122 /* the console is in raw mode, put it back in cooked mode */
3123 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));