2 * Win32 console functions
4 * Copyright 1995 Martin von Loewis and Cameron Heide
5 * Copyright 1997 Karl Garrison
6 * Copyright 1998 John Richardson
7 * Copyright 1998 Marcus Meissner
8 * Copyright 2001,2002,2004,2005 Eric Pouech
9 * Copyright 2001 Alexandre Julliard
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 /* Reference applications:
27 * - IDA (interactive disassembler) full version 3.75. Works.
28 * - LYNX/W32. Works mostly, some keys crash it.
32 #include "wine/port.h"
44 #ifdef HAVE_SYS_POLL_H
45 # include <sys/poll.h>
49 #define WIN32_NO_STATUS
55 #include "wine/server.h"
56 #include "wine/exception.h"
57 #include "wine/unicode.h"
58 #include "wine/debug.h"
60 #include "console_private.h"
61 #include "kernel_private.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(console);
65 static CRITICAL_SECTION CONSOLE_CritSect;
66 static CRITICAL_SECTION_DEBUG critsect_debug =
68 0, 0, &CONSOLE_CritSect,
69 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
70 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
72 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
74 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
75 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
77 /* FIXME: this is not thread safe */
78 static HANDLE console_wait_event;
80 /* map input records to ASCII */
81 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
86 for (i = 0; i < count; i++)
88 if (buffer[i].EventType != KEY_EVENT) continue;
89 WideCharToMultiByte( GetConsoleCP(), 0,
90 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
91 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
95 /* map input records to Unicode */
96 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
101 for (i = 0; i < count; i++)
103 if (buffer[i].EventType != KEY_EVENT) continue;
104 MultiByteToWideChar( GetConsoleCP(), 0,
105 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
106 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
110 /* map char infos to ASCII */
111 static void char_info_WtoA( CHAR_INFO *buffer, int count )
117 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
118 &ch, 1, NULL, NULL );
119 buffer->Char.AsciiChar = ch;
124 /* map char infos to Unicode */
125 static void char_info_AtoW( CHAR_INFO *buffer, int count )
131 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
132 buffer->Char.UnicodeChar = ch;
137 static struct termios S_termios; /* saved termios for bare consoles */
138 static BOOL S_termios_raw /* = FALSE */;
140 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
141 * - a bare console is created for all CUI programs started from command line (without
142 * wineconsole) (let's call those PS)
143 * - of course, every child of a PS which requires console inheritance will get it
144 * - the console termios attributes are saved at the start of program which is attached to be
146 * - if any program attached to a bare console requests input from console, the console is
147 * turned into raw mode
148 * - when the program which created the bare console (the program started from command line)
149 * exits, it will restore the console termios attributes it saved at startup (this
150 * will put back the console into cooked mode if it had been put in raw mode)
151 * - if any other program attached to this bare console is still alive, the Unix shell will put
152 * it in the background, hence forbidding access to the console. Therefore, reading console
153 * input will not be available when the bare console creator has died.
154 * FIXME: This is a limitation of current implementation
157 /* returns the fd for a bare console (-1 otherwise) */
158 static int get_console_bare_fd(HANDLE hin)
162 if (wine_server_handle_to_fd(wine_server_ptr_handle(console_handle_unmap(hin)),
163 0, &fd, NULL) == STATUS_SUCCESS)
168 static BOOL save_console_mode(HANDLE hin)
173 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
174 ret = tcgetattr(fd, &S_termios) >= 0;
179 static BOOL put_console_into_raw_mode(int fd)
181 RtlEnterCriticalSection(&CONSOLE_CritSect);
184 struct termios term = S_termios;
186 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
187 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
188 term.c_cflag &= ~(CSIZE | PARENB);
190 /* FIXME: we should actually disable output processing here
191 * and let kernel32/console.c do the job (with support of enable/disable of
194 /* term.c_oflag &= ~(OPOST); */
196 term.c_cc[VTIME] = 0;
197 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
199 RtlLeaveCriticalSection(&CONSOLE_CritSect);
201 return S_termios_raw;
204 /* put back the console in cooked mode iff we're the process which created the bare console
205 * we don't test if thie process has set the console in raw mode as it could be one of its
208 static BOOL restore_console_mode(HANDLE hin)
213 if (!S_termios_raw ||
214 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
216 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
217 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
222 /******************************************************************************
223 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
226 * Success: hwnd of the console window.
229 HWND WINAPI GetConsoleWindow(VOID)
233 SERVER_START_REQ(get_console_input_info)
236 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
244 /******************************************************************************
245 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
250 UINT WINAPI GetConsoleCP(VOID)
253 UINT codepage = GetOEMCP(); /* default value */
255 SERVER_START_REQ(get_console_input_info)
258 ret = !wine_server_call_err(req);
259 if (ret && reply->input_cp)
260 codepage = reply->input_cp;
268 /******************************************************************************
269 * SetConsoleCP [KERNEL32.@]
271 BOOL WINAPI SetConsoleCP(UINT cp)
275 if (!IsValidCodePage(cp))
277 SetLastError(ERROR_INVALID_PARAMETER);
281 SERVER_START_REQ(set_console_input_info)
284 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
286 ret = !wine_server_call_err(req);
294 /***********************************************************************
295 * GetConsoleOutputCP (KERNEL32.@)
297 UINT WINAPI GetConsoleOutputCP(VOID)
300 UINT codepage = GetOEMCP(); /* default value */
302 SERVER_START_REQ(get_console_input_info)
305 ret = !wine_server_call_err(req);
306 if (ret && reply->output_cp)
307 codepage = reply->output_cp;
315 /******************************************************************************
316 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
319 * cp [I] code page to set
325 BOOL WINAPI SetConsoleOutputCP(UINT cp)
329 if (!IsValidCodePage(cp))
331 SetLastError(ERROR_INVALID_PARAMETER);
335 SERVER_START_REQ(set_console_input_info)
338 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
340 ret = !wine_server_call_err(req);
348 /***********************************************************************
351 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
353 static const char beep = '\a';
354 /* dwFreq and dwDur are ignored by Win95 */
355 if (isatty(2)) write( 2, &beep, 1 );
360 /******************************************************************
361 * OpenConsoleW (KERNEL32.@)
364 * Open a handle to the current process console.
365 * Returns INVALID_HANDLE_VALUE on failure.
367 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
369 HANDLE output = INVALID_HANDLE_VALUE;
372 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
376 if (strcmpiW(coninW, name) == 0)
377 output = (HANDLE) FALSE;
378 else if (strcmpiW(conoutW, name) == 0)
379 output = (HANDLE) TRUE;
382 if (output == INVALID_HANDLE_VALUE)
384 SetLastError(ERROR_INVALID_PARAMETER);
385 return INVALID_HANDLE_VALUE;
387 else if (creation != OPEN_EXISTING)
389 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
390 SetLastError(ERROR_SHARING_VIOLATION);
392 SetLastError(ERROR_INVALID_PARAMETER);
393 return INVALID_HANDLE_VALUE;
396 SERVER_START_REQ( open_console )
398 req->from = wine_server_obj_handle( output );
399 req->access = access;
400 req->attributes = inherit ? OBJ_INHERIT : 0;
401 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
402 wine_server_call_err( req );
403 ret = wine_server_ptr_handle( reply->handle );
407 ret = console_handle_map(ret);
412 /******************************************************************
413 * VerifyConsoleIoHandle (KERNEL32.@)
417 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
421 if (!is_console_handle(handle)) return FALSE;
422 SERVER_START_REQ(get_console_mode)
424 req->handle = console_handle_unmap(handle);
425 ret = !wine_server_call( req );
431 /******************************************************************
432 * DuplicateConsoleHandle (KERNEL32.@)
436 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
441 if (!is_console_handle(handle) ||
442 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
443 GetCurrentProcess(), &ret, access, inherit, options))
444 return INVALID_HANDLE_VALUE;
445 return console_handle_map(ret);
448 /******************************************************************
449 * CloseConsoleHandle (KERNEL32.@)
453 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
455 if (!is_console_handle(handle))
457 SetLastError(ERROR_INVALID_PARAMETER);
460 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
463 /******************************************************************
464 * GetConsoleInputWaitHandle (KERNEL32.@)
468 HANDLE WINAPI GetConsoleInputWaitHandle(void)
470 if (!console_wait_event)
472 SERVER_START_REQ(get_console_wait_event)
474 if (!wine_server_call_err( req ))
475 console_wait_event = wine_server_ptr_handle( reply->handle );
479 return console_wait_event;
483 /******************************************************************************
484 * WriteConsoleInputA [KERNEL32.@]
486 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
487 DWORD count, LPDWORD written )
492 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
493 memcpy( recW, buffer, count*sizeof(*recW) );
494 input_records_AtoW( recW, count );
495 ret = WriteConsoleInputW( handle, recW, count, written );
496 HeapFree( GetProcessHeap(), 0, recW );
501 /******************************************************************************
502 * WriteConsoleInputW [KERNEL32.@]
504 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
505 DWORD count, LPDWORD written )
509 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
511 if (written) *written = 0;
512 SERVER_START_REQ( write_console_input )
514 req->handle = console_handle_unmap(handle);
515 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
516 if ((ret = !wine_server_call_err( req )) && written)
517 *written = reply->written;
525 /***********************************************************************
526 * WriteConsoleOutputA (KERNEL32.@)
528 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
529 COORD size, COORD coord, LPSMALL_RECT region )
533 COORD new_size, new_coord;
536 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
537 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
539 if (new_size.X <= 0 || new_size.Y <= 0)
541 region->Bottom = region->Top + new_size.Y - 1;
542 region->Right = region->Left + new_size.X - 1;
546 /* only copy the useful rectangle */
547 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
549 for (y = 0; y < new_size.Y; y++)
551 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
552 new_size.X * sizeof(CHAR_INFO) );
553 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
555 new_coord.X = new_coord.Y = 0;
556 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
557 HeapFree( GetProcessHeap(), 0, ciw );
562 /***********************************************************************
563 * WriteConsoleOutputW (KERNEL32.@)
565 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
566 COORD size, COORD coord, LPSMALL_RECT region )
568 int width, height, y;
571 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
572 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
573 region->Left, region->Top, region->Right, region->Bottom);
575 width = min( region->Right - region->Left + 1, size.X - coord.X );
576 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
578 if (width > 0 && height > 0)
580 for (y = 0; y < height; y++)
582 SERVER_START_REQ( write_console_output )
584 req->handle = console_handle_unmap(hConsoleOutput);
585 req->x = region->Left;
586 req->y = region->Top + y;
587 req->mode = CHAR_INFO_MODE_TEXTATTR;
589 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
590 width * sizeof(CHAR_INFO));
591 if ((ret = !wine_server_call_err( req )))
593 width = min( width, reply->width - region->Left );
594 height = min( height, reply->height - region->Top );
601 region->Bottom = region->Top + height - 1;
602 region->Right = region->Left + width - 1;
607 /******************************************************************************
608 * WriteConsoleOutputCharacterA [KERNEL32.@]
610 * See WriteConsoleOutputCharacterW.
612 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
613 COORD coord, LPDWORD lpNumCharsWritten )
619 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
620 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
622 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
624 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
626 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
627 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
629 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
630 HeapFree( GetProcessHeap(), 0, strW );
635 /******************************************************************************
636 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
637 * the console screen buffer
640 * hConsoleOutput [I] Handle to screen buffer
641 * attr [I] Pointer to buffer with write attributes
642 * length [I] Number of cells to write to
643 * coord [I] Coords of first cell
644 * lpNumAttrsWritten [O] Pointer to number of cells written
651 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
652 COORD coord, LPDWORD lpNumAttrsWritten )
656 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
658 SERVER_START_REQ( write_console_output )
660 req->handle = console_handle_unmap(hConsoleOutput);
663 req->mode = CHAR_INFO_MODE_ATTR;
665 wine_server_add_data( req, attr, length * sizeof(WORD) );
666 if ((ret = !wine_server_call_err( req )))
668 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
676 /******************************************************************************
677 * FillConsoleOutputCharacterA [KERNEL32.@]
679 * See FillConsoleOutputCharacterW.
681 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
682 COORD coord, LPDWORD lpNumCharsWritten )
686 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
687 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
691 /******************************************************************************
692 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
695 * hConsoleOutput [I] Handle to screen buffer
696 * ch [I] Character to write
697 * length [I] Number of cells to write to
698 * coord [I] Coords of first cell
699 * lpNumCharsWritten [O] Pointer to number of cells written
705 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
706 COORD coord, LPDWORD lpNumCharsWritten)
710 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
711 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
713 SERVER_START_REQ( fill_console_output )
715 req->handle = console_handle_unmap(hConsoleOutput);
718 req->mode = CHAR_INFO_MODE_TEXT;
722 if ((ret = !wine_server_call_err( req )))
724 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
732 /******************************************************************************
733 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
736 * hConsoleOutput [I] Handle to screen buffer
737 * attr [I] Color attribute to write
738 * length [I] Number of cells to write to
739 * coord [I] Coords of first cell
740 * lpNumAttrsWritten [O] Pointer to number of cells written
746 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
747 COORD coord, LPDWORD lpNumAttrsWritten )
751 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
752 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
754 SERVER_START_REQ( fill_console_output )
756 req->handle = console_handle_unmap(hConsoleOutput);
759 req->mode = CHAR_INFO_MODE_ATTR;
761 req->data.attr = attr;
763 if ((ret = !wine_server_call_err( req )))
765 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
773 /******************************************************************************
774 * ReadConsoleOutputCharacterA [KERNEL32.@]
777 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
778 COORD coord, LPDWORD read_count)
782 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
784 if (read_count) *read_count = 0;
785 if (!wptr) return FALSE;
787 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
789 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
790 if (read_count) *read_count = read;
792 HeapFree( GetProcessHeap(), 0, wptr );
797 /******************************************************************************
798 * ReadConsoleOutputCharacterW [KERNEL32.@]
801 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
802 COORD coord, LPDWORD read_count )
806 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
808 SERVER_START_REQ( read_console_output )
810 req->handle = console_handle_unmap(hConsoleOutput);
813 req->mode = CHAR_INFO_MODE_TEXT;
815 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
816 if ((ret = !wine_server_call_err( req )))
818 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
826 /******************************************************************************
827 * ReadConsoleOutputAttribute [KERNEL32.@]
829 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
830 COORD coord, LPDWORD read_count)
834 TRACE("(%p,%p,%d,%dx%d,%p)\n",
835 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
837 SERVER_START_REQ( read_console_output )
839 req->handle = console_handle_unmap(hConsoleOutput);
842 req->mode = CHAR_INFO_MODE_ATTR;
844 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
845 if ((ret = !wine_server_call_err( req )))
847 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
855 /******************************************************************************
856 * ReadConsoleOutputA [KERNEL32.@]
859 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
860 COORD coord, LPSMALL_RECT region )
865 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
866 if (ret && region->Right >= region->Left)
868 for (y = 0; y <= region->Bottom - region->Top; y++)
870 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
871 region->Right - region->Left + 1 );
878 /******************************************************************************
879 * ReadConsoleOutputW [KERNEL32.@]
881 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
882 * think we need to be *that* compatible. -- AJ
884 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
885 COORD coord, LPSMALL_RECT region )
887 int width, height, y;
890 width = min( region->Right - region->Left + 1, size.X - coord.X );
891 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
893 if (width > 0 && height > 0)
895 for (y = 0; y < height; y++)
897 SERVER_START_REQ( read_console_output )
899 req->handle = console_handle_unmap(hConsoleOutput);
900 req->x = region->Left;
901 req->y = region->Top + y;
902 req->mode = CHAR_INFO_MODE_TEXTATTR;
904 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
905 width * sizeof(CHAR_INFO) );
906 if ((ret = !wine_server_call_err( req )))
908 width = min( width, reply->width - region->Left );
909 height = min( height, reply->height - region->Top );
916 region->Bottom = region->Top + height - 1;
917 region->Right = region->Left + width - 1;
922 /******************************************************************************
923 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
926 * handle [I] Handle to console input buffer
927 * buffer [O] Address of buffer for read data
928 * count [I] Number of records to read
929 * pRead [O] Address of number of records read
935 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
939 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
940 input_records_WtoA( buffer, read );
941 if (pRead) *pRead = read;
946 /***********************************************************************
947 * PeekConsoleInputA (KERNEL32.@)
949 * Gets 'count' first events (or less) from input queue.
951 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
955 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
956 input_records_WtoA( buffer, read );
957 if (pRead) *pRead = read;
962 /***********************************************************************
963 * PeekConsoleInputW (KERNEL32.@)
965 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
968 SERVER_START_REQ( read_console_input )
970 req->handle = console_handle_unmap(handle);
972 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
973 if ((ret = !wine_server_call_err( req )))
975 if (read) *read = count ? reply->read : 0;
983 /***********************************************************************
984 * GetNumberOfConsoleInputEvents (KERNEL32.@)
986 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
989 SERVER_START_REQ( read_console_input )
991 req->handle = console_handle_unmap(handle);
993 if ((ret = !wine_server_call_err( req )))
995 if (nrofevents) *nrofevents = reply->read;
1003 /******************************************************************************
1004 * read_console_input
1006 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1009 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1011 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1012 static const int vkkeyscan_table[256] =
1014 0,0,0,0,0,0,0,0,8,9,0,0,0,13,0,0,0,0,0,19,145,556,0,0,0,0,0,27,0,0,0,
1015 0,32,305,478,307,308,309,311,222,313,304,312,443,188,189,190,191,48,
1016 49,50,51,52,53,54,55,56,57,442,186,444,187,446,447,306,321,322,323,
1017 324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,
1018 341,342,343,344,345,346,219,220,221,310,445,192,65,66,67,68,69,70,71,
1019 72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,475,476,477,
1020 448,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1021 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1022 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1023 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,400,0,0,0,0,0,0
1026 static const int mapvkey_0[256] =
1028 0,0,0,0,0,0,0,0,14,15,0,0,0,28,0,0,42,29,56,69,58,0,0,0,0,0,0,1,0,0,
1029 0,0,57,73,81,79,71,75,72,77,80,0,0,0,55,82,83,0,11,2,3,4,5,6,7,8,9,
1030 10,0,0,0,0,0,0,0,30,48,46,32,18,33,34,35,23,36,37,38,50,49,24,25,16,
1031 19,31,20,22,47,17,45,21,44,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,55,78,0,74,
1032 0,53,59,60,61,62,63,64,65,66,67,68,87,88,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1033 0,0,0,0,0,0,69,70,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1034 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,39,13,51,12,52,53,41,0,0,0,0,0,0,0,0,0,
1035 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,43,27,40,76,96,0,0,0,0,0,0,0,0,
1036 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
1039 static inline void init_complex_char(INPUT_RECORD* ir, BOOL down, WORD vk, WORD kc, DWORD cks)
1041 ir->EventType = KEY_EVENT;
1042 ir->Event.KeyEvent.bKeyDown = down;
1043 ir->Event.KeyEvent.wRepeatCount = 1;
1044 ir->Event.KeyEvent.wVirtualScanCode = vk;
1045 ir->Event.KeyEvent.wVirtualKeyCode = kc;
1046 ir->Event.KeyEvent.dwControlKeyState = cks;
1047 ir->Event.KeyEvent.uChar.UnicodeChar = 0;
1050 /******************************************************************
1051 * handle_simple_char
1055 static BOOL handle_simple_char(HANDLE conin, unsigned real_inchar)
1060 unsigned numEvent = 0;
1061 DWORD cks = 0, written;
1064 switch (real_inchar)
1066 case 9: inchar = real_inchar;
1067 real_inchar = 27; /* so that we don't think key is ctrl- something */
1070 case 10: inchar = '\r';
1071 real_inchar = 27; /* Fixme: so that we don't think key is ctrl- something */
1073 case 127: inchar = '\b';
1076 inchar = real_inchar;
1079 if ((inchar & ~0xFF) != 0) FIXME("What a char (%u)\n", inchar);
1080 vk = vkkeyscan_table[inchar];
1082 init_complex_char(&ir[numEvent++], 1, 0x2a, 0x10, SHIFT_PRESSED);
1083 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1084 init_complex_char(&ir[numEvent++], 1, 0x1d, 0x11, LEFT_CTRL_PRESSED);
1086 init_complex_char(&ir[numEvent++], 1, 0x38, 0x12, LEFT_ALT_PRESSED);
1088 ir[numEvent].EventType = KEY_EVENT;
1089 ir[numEvent].Event.KeyEvent.bKeyDown = 1;
1090 ir[numEvent].Event.KeyEvent.wRepeatCount = 1;
1091 ir[numEvent].Event.KeyEvent.dwControlKeyState = cks;
1093 ir[numEvent].Event.KeyEvent.dwControlKeyState |= SHIFT_PRESSED;
1094 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1095 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_CTRL_PRESSED;
1097 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_ALT_PRESSED;
1098 ir[numEvent].Event.KeyEvent.wVirtualKeyCode = vk;
1099 ir[numEvent].Event.KeyEvent.wVirtualScanCode = mapvkey_0[vk & 0x00ff]; /* VirtualKeyCodes to ScanCode */
1102 MultiByteToWideChar(CP_UNIXCP, 0, &ch, 1, &ir[numEvent].Event.KeyEvent.uChar.UnicodeChar, 1);
1103 ir[numEvent + 1] = ir[numEvent];
1104 ir[numEvent + 1].Event.KeyEvent.bKeyDown = 0;
1109 init_complex_char(&ir[numEvent++], 0, 0x38, 0x12, LEFT_ALT_PRESSED);
1110 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1111 init_complex_char(&ir[numEvent++], 0, 0x1d, 0x11, 0);
1113 init_complex_char(&ir[numEvent++], 0, 0x2a, 0x10, 0);
1115 return WriteConsoleInputW(conin, ir, numEvent, &written);
1118 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1120 struct pollfd pollfd;
1122 enum read_console_input_return ret;
1125 pollfd.events = POLLIN;
1128 switch (poll(&pollfd, 1, timeout))
1131 RtlEnterCriticalSection(&CONSOLE_CritSect);
1132 switch (read(fd, &ch, 1))
1134 case 1: ret = handle_simple_char(handle, ch) ? rci_gotone : rci_error; break;
1135 /* actually another thread likely beat us to reading the char
1136 * return gotone, while not perfect, it should work in most of the cases (as the new event
1137 * should be now in the queue)
1139 case 0: ret = rci_gotone; break;
1140 default: ret = rci_error; break;
1142 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1144 case 0: return rci_timeout;
1145 default: return rci_error;
1149 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1152 enum read_console_input_return ret;
1154 if ((fd = get_console_bare_fd(handle)) != -1)
1156 put_console_into_raw_mode(fd);
1157 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1159 ret = bare_console_fetch_input(handle, fd, timeout);
1161 else ret = rci_gotone;
1163 if (ret != rci_gotone) return ret;
1167 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1169 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1173 SERVER_START_REQ( read_console_input )
1175 req->handle = console_handle_unmap(handle);
1177 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1178 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1179 else ret = rci_gotone;
1187 /***********************************************************************
1188 * FlushConsoleInputBuffer (KERNEL32.@)
1190 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1192 enum read_console_input_return last;
1195 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1197 return last == rci_timeout;
1201 /***********************************************************************
1202 * SetConsoleTitleA (KERNEL32.@)
1204 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1209 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1210 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1211 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1212 ret = SetConsoleTitleW(titleW);
1213 HeapFree(GetProcessHeap(), 0, titleW);
1218 /***********************************************************************
1219 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1221 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1223 FIXME( "stub %p\n", layoutName);
1227 /***********************************************************************
1228 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1230 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1232 FIXME( "stub %p\n", layoutName);
1236 static WCHAR input_exe[MAX_PATH + 1];
1238 /***********************************************************************
1239 * GetConsoleInputExeNameW (KERNEL32.@)
1241 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1243 TRACE("%u %p\n", buflen, buffer);
1245 RtlEnterCriticalSection(&CONSOLE_CritSect);
1246 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1247 else SetLastError(ERROR_BUFFER_OVERFLOW);
1248 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1253 /***********************************************************************
1254 * GetConsoleInputExeNameA (KERNEL32.@)
1256 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1258 TRACE("%u %p\n", buflen, buffer);
1260 RtlEnterCriticalSection(&CONSOLE_CritSect);
1261 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1262 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1263 else SetLastError(ERROR_BUFFER_OVERFLOW);
1264 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1269 /***********************************************************************
1270 * GetConsoleTitleA (KERNEL32.@)
1272 * See GetConsoleTitleW.
1274 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1276 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1280 ret = GetConsoleTitleW( ptr, size );
1283 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1284 ret = strlen(title);
1286 HeapFree(GetProcessHeap(), 0, ptr);
1291 /******************************************************************************
1292 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1295 * title [O] Address of buffer for title
1296 * size [I] Size of buffer
1299 * Success: Length of string copied
1302 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1306 SERVER_START_REQ( get_console_input_info )
1309 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1310 if (!wine_server_call_err( req ))
1312 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1321 /***********************************************************************
1322 * GetLargestConsoleWindowSize (KERNEL32.@)
1325 * This should return a COORD, but calling convention for returning
1326 * structures is different between Windows and gcc on i386.
1331 #undef GetLargestConsoleWindowSize
1332 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1340 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1343 #endif /* defined(__i386__) */
1346 /***********************************************************************
1347 * GetLargestConsoleWindowSize (KERNEL32.@)
1350 * This should return a COORD, but calling convention for returning
1351 * structures is different between Windows and gcc on i386.
1356 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1361 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1364 #endif /* defined(__i386__) */
1366 static WCHAR* S_EditString /* = NULL */;
1367 static unsigned S_EditStrPos /* = 0 */;
1369 /***********************************************************************
1370 * FreeConsole (KERNEL32.@)
1372 BOOL WINAPI FreeConsole(VOID)
1376 /* invalidate local copy of input event handle */
1377 console_wait_event = 0;
1379 SERVER_START_REQ(free_console)
1381 ret = !wine_server_call_err( req );
1387 /******************************************************************
1388 * start_console_renderer
1390 * helper for AllocConsole
1391 * starts the renderer process
1393 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1398 PROCESS_INFORMATION pi;
1400 /* FIXME: use dynamic allocation for most of the buffers below */
1401 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1402 if ((ret > -1) && (ret < sizeof(buffer)) &&
1403 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1404 NULL, NULL, si, &pi))
1410 wh[1] = pi.hProcess;
1411 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1413 CloseHandle(pi.hThread);
1414 CloseHandle(pi.hProcess);
1416 if (ret != WAIT_OBJECT_0) return FALSE;
1418 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1419 pi.dwProcessId, pi.dwThreadId);
1426 static BOOL start_console_renderer(STARTUPINFOA* si)
1430 OBJECT_ATTRIBUTES attr;
1433 attr.Length = sizeof(attr);
1434 attr.RootDirectory = 0;
1435 attr.Attributes = OBJ_INHERIT;
1436 attr.ObjectName = NULL;
1437 attr.SecurityDescriptor = NULL;
1438 attr.SecurityQualityOfService = NULL;
1440 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1441 if (!hEvent) return FALSE;
1443 /* first try environment variable */
1444 if ((p = getenv("WINECONSOLE")) != NULL)
1446 ret = start_console_renderer_helper(p, si, hEvent);
1448 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1449 "trying default access\n", p);
1452 /* then try the regular PATH */
1454 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1456 CloseHandle(hEvent);
1460 /***********************************************************************
1461 * AllocConsole (KERNEL32.@)
1463 * creates an xterm with a pty to our program
1465 BOOL WINAPI AllocConsole(void)
1467 HANDLE handle_in = INVALID_HANDLE_VALUE;
1468 HANDLE handle_out = INVALID_HANDLE_VALUE;
1469 HANDLE handle_err = INVALID_HANDLE_VALUE;
1470 STARTUPINFOA siCurrent;
1471 STARTUPINFOA siConsole;
1476 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1477 FALSE, OPEN_EXISTING );
1479 if (VerifyConsoleIoHandle(handle_in))
1481 /* we already have a console opened on this process, don't create a new one */
1482 CloseHandle(handle_in);
1486 /* invalidate local copy of input event handle */
1487 console_wait_event = 0;
1489 GetStartupInfoA(&siCurrent);
1491 memset(&siConsole, 0, sizeof(siConsole));
1492 siConsole.cb = sizeof(siConsole);
1493 /* setup a view arguments for wineconsole (it'll use them as default values) */
1494 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1496 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1497 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1498 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1500 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1502 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1503 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1505 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1507 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1508 siConsole.wShowWindow = siCurrent.wShowWindow;
1510 /* FIXME (should pass the unicode form) */
1511 if (siCurrent.lpTitle)
1512 siConsole.lpTitle = siCurrent.lpTitle;
1513 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1515 buffer[sizeof(buffer) - 1] = '\0';
1516 siConsole.lpTitle = buffer;
1519 if (!start_console_renderer(&siConsole))
1522 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1523 /* all std I/O handles are inheritable by default */
1524 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1525 TRUE, OPEN_EXISTING );
1526 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1528 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1529 TRUE, OPEN_EXISTING );
1530 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1532 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1533 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1536 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1537 handle_in = siCurrent.hStdInput;
1538 handle_out = siCurrent.hStdOutput;
1539 handle_err = siCurrent.hStdError;
1542 /* NT resets the STD_*_HANDLEs on console alloc */
1543 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1544 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1545 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1547 SetLastError(ERROR_SUCCESS);
1552 ERR("Can't allocate console\n");
1553 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1554 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1555 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1561 /***********************************************************************
1562 * ReadConsoleA (KERNEL32.@)
1564 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1565 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1567 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1571 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1572 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1574 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1575 HeapFree(GetProcessHeap(), 0, ptr);
1580 /***********************************************************************
1581 * ReadConsoleW (KERNEL32.@)
1583 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1584 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1587 LPWSTR xbuf = lpBuffer;
1589 BOOL is_bare = FALSE;
1592 TRACE("(%p,%p,%d,%p,%p)\n",
1593 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1595 if (!GetConsoleMode(hConsoleInput, &mode))
1597 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1602 if (mode & ENABLE_LINE_INPUT)
1604 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1606 HeapFree(GetProcessHeap(), 0, S_EditString);
1607 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1611 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1612 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1613 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1614 S_EditStrPos += charsread;
1619 DWORD timeout = INFINITE;
1621 /* FIXME: should we read at least 1 char? The SDK does not say */
1622 /* wait for at least one available input record (it doesn't mean we'll have
1623 * chars stored in xbuf...)
1625 * Although SDK doc keeps silence about 1 char, SDK examples assume
1626 * that we should wait for at least one character (not key). --KS
1631 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1632 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1633 ir.Event.KeyEvent.uChar.UnicodeChar)
1635 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1638 } while (charsread < nNumberOfCharsToRead);
1639 /* nothing has been read */
1640 if (timeout == INFINITE) return FALSE;
1643 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1649 /***********************************************************************
1650 * ReadConsoleInputW (KERNEL32.@)
1652 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1653 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1656 DWORD timeout = INFINITE;
1660 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1664 /* loop until we get at least one event */
1665 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1669 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1674 /******************************************************************************
1675 * WriteConsoleOutputCharacterW [KERNEL32.@]
1677 * Copy character to consecutive cells in the console screen buffer.
1680 * hConsoleOutput [I] Handle to screen buffer
1681 * str [I] Pointer to buffer with chars to write
1682 * length [I] Number of cells to write to
1683 * coord [I] Coords of first cell
1684 * lpNumCharsWritten [O] Pointer to number of cells written
1691 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1692 COORD coord, LPDWORD lpNumCharsWritten )
1696 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1697 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1699 SERVER_START_REQ( write_console_output )
1701 req->handle = console_handle_unmap(hConsoleOutput);
1704 req->mode = CHAR_INFO_MODE_TEXT;
1706 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1707 if ((ret = !wine_server_call_err( req )))
1709 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1717 /******************************************************************************
1718 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1721 * title [I] Address of new title
1727 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1731 TRACE("(%s)\n", debugstr_w(title));
1732 SERVER_START_REQ( set_console_input_info )
1735 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1736 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1737 ret = !wine_server_call_err( req );
1744 /***********************************************************************
1745 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1747 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1749 FIXME("(%p): stub\n", nrofbuttons);
1754 /******************************************************************************
1755 * SetConsoleInputExeNameW [KERNEL32.@]
1757 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1759 TRACE("(%s)\n", debugstr_w(name));
1761 if (!name || !name[0])
1763 SetLastError(ERROR_INVALID_PARAMETER);
1767 RtlEnterCriticalSection(&CONSOLE_CritSect);
1768 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1769 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1774 /******************************************************************************
1775 * SetConsoleInputExeNameA [KERNEL32.@]
1777 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1783 if (!name || !name[0])
1785 SetLastError(ERROR_INVALID_PARAMETER);
1789 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1790 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1792 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1793 ret = SetConsoleInputExeNameW(nameW);
1794 HeapFree(GetProcessHeap(), 0, nameW);
1799 /******************************************************************
1800 * CONSOLE_DefaultHandler
1802 * Final control event handler
1804 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1806 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1808 /* should never go here */
1812 /******************************************************************************
1813 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1816 * func [I] Address of handler function
1817 * add [I] Handler to add or remove
1824 struct ConsoleHandler
1826 PHANDLER_ROUTINE handler;
1827 struct ConsoleHandler* next;
1830 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1831 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1833 /*****************************************************************************/
1835 /******************************************************************
1836 * SetConsoleCtrlHandler (KERNEL32.@)
1838 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1842 TRACE("(%p,%i)\n", func, add);
1846 RtlEnterCriticalSection(&CONSOLE_CritSect);
1848 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1850 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1851 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1855 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1857 if (!ch) return FALSE;
1859 RtlEnterCriticalSection(&CONSOLE_CritSect);
1860 ch->next = CONSOLE_Handlers;
1861 CONSOLE_Handlers = ch;
1862 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1866 struct ConsoleHandler** ch;
1867 RtlEnterCriticalSection(&CONSOLE_CritSect);
1868 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1870 if ((*ch)->handler == func) break;
1874 struct ConsoleHandler* rch = *ch;
1877 if (rch == &CONSOLE_DefaultConsoleHandler)
1879 ERR("Who's trying to remove default handler???\n");
1880 SetLastError(ERROR_INVALID_PARAMETER);
1886 HeapFree(GetProcessHeap(), 0, rch);
1891 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1892 SetLastError(ERROR_INVALID_PARAMETER);
1895 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1900 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1902 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1903 return EXCEPTION_EXECUTE_HANDLER;
1906 /******************************************************************
1907 * CONSOLE_SendEventThread
1909 * Internal helper to pass an event to the list on installed handlers
1911 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1913 DWORD_PTR event = (DWORD_PTR)pmt;
1914 struct ConsoleHandler* ch;
1916 if (event == CTRL_C_EVENT)
1918 BOOL caught_by_dbg = TRUE;
1919 /* First, try to pass the ctrl-C event to the debugger (if any)
1920 * If it continues, there's nothing more to do
1921 * Otherwise, we need to send the ctrl-C event to the handlers
1925 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1927 __EXCEPT(CONSOLE_CtrlEventHandler)
1929 caught_by_dbg = FALSE;
1932 if (caught_by_dbg) return 0;
1933 /* the debugger didn't continue... so, pass to ctrl handlers */
1935 RtlEnterCriticalSection(&CONSOLE_CritSect);
1936 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1938 if (ch->handler(event)) break;
1940 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1944 /******************************************************************
1945 * CONSOLE_HandleCtrlC
1947 * Check whether the shall manipulate CtrlC events
1949 int CONSOLE_HandleCtrlC(unsigned sig)
1951 /* FIXME: better test whether a console is attached to this process ??? */
1952 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1953 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1955 /* check if we have to ignore ctrl-C events */
1956 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1958 /* Create a separate thread to signal all the events.
1959 * This is needed because:
1960 * - this function can be called in an Unix signal handler (hence on an
1961 * different stack than the thread that's running). This breaks the
1962 * Win32 exception mechanisms (where the thread's stack is checked).
1963 * - since the current thread, while processing the signal, can hold the
1964 * console critical section, we need another execution environment where
1965 * we can wait on this critical section
1967 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1972 /******************************************************************************
1973 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1976 * dwCtrlEvent [I] Type of event
1977 * dwProcessGroupID [I] Process group ID to send event to
1981 * Failure: False (and *should* [but doesn't] set LastError)
1983 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1984 DWORD dwProcessGroupID)
1988 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
1990 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1992 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
1996 SERVER_START_REQ( send_console_signal )
1998 req->signal = dwCtrlEvent;
1999 req->group_id = dwProcessGroupID;
2000 ret = !wine_server_call_err( req );
2004 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2005 * have been handled by all processes in the given group?
2006 * As of today, we don't wait...
2012 /******************************************************************************
2013 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2016 * dwDesiredAccess [I] Access flag
2017 * dwShareMode [I] Buffer share mode
2018 * sa [I] Security attributes
2019 * dwFlags [I] Type of buffer to create
2020 * lpScreenBufferData [I] Reserved
2023 * Should call SetLastError
2026 * Success: Handle to new console screen buffer
2027 * Failure: INVALID_HANDLE_VALUE
2029 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2030 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2031 LPVOID lpScreenBufferData)
2033 HANDLE ret = INVALID_HANDLE_VALUE;
2035 TRACE("(%d,%d,%p,%d,%p)\n",
2036 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2038 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2040 SetLastError(ERROR_INVALID_PARAMETER);
2041 return INVALID_HANDLE_VALUE;
2044 SERVER_START_REQ(create_console_output)
2047 req->access = dwDesiredAccess;
2048 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2049 req->share = dwShareMode;
2051 if (!wine_server_call_err( req ))
2052 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2060 /***********************************************************************
2061 * GetConsoleScreenBufferInfo (KERNEL32.@)
2063 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2067 SERVER_START_REQ(get_console_output_info)
2069 req->handle = console_handle_unmap(hConsoleOutput);
2070 if ((ret = !wine_server_call_err( req )))
2072 csbi->dwSize.X = reply->width;
2073 csbi->dwSize.Y = reply->height;
2074 csbi->dwCursorPosition.X = reply->cursor_x;
2075 csbi->dwCursorPosition.Y = reply->cursor_y;
2076 csbi->wAttributes = reply->attr;
2077 csbi->srWindow.Left = reply->win_left;
2078 csbi->srWindow.Right = reply->win_right;
2079 csbi->srWindow.Top = reply->win_top;
2080 csbi->srWindow.Bottom = reply->win_bottom;
2081 csbi->dwMaximumWindowSize.X = reply->max_width;
2082 csbi->dwMaximumWindowSize.Y = reply->max_height;
2087 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2088 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2089 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2091 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2092 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2098 /******************************************************************************
2099 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2105 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2109 TRACE("(%p)\n", hConsoleOutput);
2111 SERVER_START_REQ( set_console_input_info )
2114 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2115 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2116 ret = !wine_server_call_err( req );
2123 /***********************************************************************
2124 * GetConsoleMode (KERNEL32.@)
2126 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2130 SERVER_START_REQ( get_console_mode )
2132 req->handle = console_handle_unmap(hcon);
2133 if ((ret = !wine_server_call_err( req )))
2135 if (mode) *mode = reply->mode;
2143 /******************************************************************************
2144 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2147 * hcon [I] Handle to console input or screen buffer
2148 * mode [I] Input or output mode to set
2155 * ENABLE_PROCESSED_INPUT 0x01
2156 * ENABLE_LINE_INPUT 0x02
2157 * ENABLE_ECHO_INPUT 0x04
2158 * ENABLE_WINDOW_INPUT 0x08
2159 * ENABLE_MOUSE_INPUT 0x10
2161 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2165 SERVER_START_REQ(set_console_mode)
2167 req->handle = console_handle_unmap(hcon);
2169 ret = !wine_server_call_err( req );
2172 /* FIXME: when resetting a console input to editline mode, I think we should
2173 * empty the S_EditString buffer
2176 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2182 /******************************************************************
2183 * CONSOLE_WriteChars
2185 * WriteConsoleOutput helper: hides server call semantics
2186 * writes a string at a given pos with standard attribute
2188 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2194 SERVER_START_REQ( write_console_output )
2196 req->handle = console_handle_unmap(hCon);
2199 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2201 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2202 if (!wine_server_call_err( req )) written = reply->written;
2206 if (written > 0) pos->X += written;
2210 /******************************************************************
2213 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2216 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2222 csbi->dwCursorPosition.X = 0;
2223 csbi->dwCursorPosition.Y++;
2225 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2228 src.Bottom = csbi->dwSize.Y - 1;
2230 src.Right = csbi->dwSize.X - 1;
2235 ci.Attributes = csbi->wAttributes;
2236 ci.Char.UnicodeChar = ' ';
2238 csbi->dwCursorPosition.Y--;
2239 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2244 /******************************************************************
2247 * WriteConsoleOutput helper: writes a block of non special characters
2248 * Block can spread on several lines, and wrapping, if needed, is
2252 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2253 DWORD mode, LPCWSTR ptr, int len)
2255 int blk; /* number of chars to write on current line */
2256 int done; /* number of chars already written */
2258 if (len <= 0) return 1;
2260 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2262 for (done = 0; done < len; done += blk)
2264 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2266 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2268 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2274 int pos = csbi->dwCursorPosition.X;
2275 /* FIXME: we could reduce the number of loops
2276 * but, in most cases we wouldn't gain lots of time (it would only
2277 * happen if we're asked to overwrite more than twice the part of the line,
2280 for (done = 0; done < len; done += blk)
2282 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2284 csbi->dwCursorPosition.X = pos;
2285 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2293 /***********************************************************************
2294 * WriteConsoleW (KERNEL32.@)
2296 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2297 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2301 const WCHAR* psz = lpBuffer;
2302 CONSOLE_SCREEN_BUFFER_INFO csbi;
2303 int k, first = 0, fd;
2305 TRACE("%p %s %d %p %p\n",
2306 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2307 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2309 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2311 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2318 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2321 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2322 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2325 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2326 ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2327 ptr, len, lpNumberOfCharsWritten, NULL);
2328 if (ret && lpNumberOfCharsWritten)
2330 if (*lpNumberOfCharsWritten == len)
2331 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2333 FIXME("Conversion not supported yet\n");
2335 HeapFree(GetProcessHeap(), 0, ptr);
2339 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2342 if (!nNumberOfCharsToWrite) return TRUE;
2344 if (mode & ENABLE_PROCESSED_OUTPUT)
2348 for (i = 0; i < nNumberOfCharsToWrite; i++)
2352 case '\b': case '\t': case '\n': case '\a': case '\r':
2353 /* don't handle here the i-th char... done below */
2354 if ((k = i - first) > 0)
2356 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2366 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2370 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2372 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2373 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2378 next_line(hConsoleOutput, &csbi);
2384 csbi.dwCursorPosition.X = 0;
2392 /* write the remaining block (if any) if processed output is enabled, or the
2393 * entire buffer otherwise
2395 if ((k = nNumberOfCharsToWrite - first) > 0)
2397 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2403 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2404 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2409 /***********************************************************************
2410 * WriteConsoleA (KERNEL32.@)
2412 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2413 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2419 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2421 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2422 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2423 if (!xstring) return 0;
2425 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2427 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2429 HeapFree(GetProcessHeap(), 0, xstring);
2434 /******************************************************************************
2435 * SetConsoleCursorPosition [KERNEL32.@]
2436 * Sets the cursor position in console
2439 * hConsoleOutput [I] Handle of console screen buffer
2440 * dwCursorPosition [I] New cursor position coordinates
2446 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2449 CONSOLE_SCREEN_BUFFER_INFO csbi;
2453 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2455 SERVER_START_REQ(set_console_output_info)
2457 req->handle = console_handle_unmap(hcon);
2458 req->cursor_x = pos.X;
2459 req->cursor_y = pos.Y;
2460 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2461 ret = !wine_server_call_err( req );
2465 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2468 /* if cursor is no longer visible, scroll the visible window... */
2469 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2470 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2471 if (pos.X < csbi.srWindow.Left)
2473 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2476 else if (pos.X > csbi.srWindow.Right)
2478 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2481 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2483 if (pos.Y < csbi.srWindow.Top)
2485 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2488 else if (pos.Y > csbi.srWindow.Bottom)
2490 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2493 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2495 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2500 /******************************************************************************
2501 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2504 * hcon [I] Handle to console screen buffer
2505 * cinfo [O] Address of cursor information
2511 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2515 SERVER_START_REQ(get_console_output_info)
2517 req->handle = console_handle_unmap(hCon);
2518 ret = !wine_server_call_err( req );
2521 cinfo->dwSize = reply->cursor_size;
2522 cinfo->bVisible = reply->cursor_visible;
2527 if (!ret) return FALSE;
2531 SetLastError(ERROR_INVALID_ACCESS);
2534 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2540 /******************************************************************************
2541 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2544 * hcon [I] Handle to console screen buffer
2545 * cinfo [I] Address of cursor information
2550 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2554 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2555 SERVER_START_REQ(set_console_output_info)
2557 req->handle = console_handle_unmap(hCon);
2558 req->cursor_size = cinfo->dwSize;
2559 req->cursor_visible = cinfo->bVisible;
2560 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2561 ret = !wine_server_call_err( req );
2568 /******************************************************************************
2569 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2572 * hcon [I] Handle to console screen buffer
2573 * bAbsolute [I] Coordinate type flag
2574 * window [I] Address of new window rectangle
2579 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2581 SMALL_RECT p = *window;
2584 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2588 CONSOLE_SCREEN_BUFFER_INFO csbi;
2590 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2592 p.Left += csbi.srWindow.Left;
2593 p.Top += csbi.srWindow.Top;
2594 p.Right += csbi.srWindow.Right;
2595 p.Bottom += csbi.srWindow.Bottom;
2597 SERVER_START_REQ(set_console_output_info)
2599 req->handle = console_handle_unmap(hCon);
2600 req->win_left = p.Left;
2601 req->win_top = p.Top;
2602 req->win_right = p.Right;
2603 req->win_bottom = p.Bottom;
2604 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2605 ret = !wine_server_call_err( req );
2613 /******************************************************************************
2614 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2616 * Sets the foreground and background color attributes of characters
2617 * written to the screen buffer.
2623 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2627 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2628 SERVER_START_REQ(set_console_output_info)
2630 req->handle = console_handle_unmap(hConsoleOutput);
2632 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2633 ret = !wine_server_call_err( req );
2640 /******************************************************************************
2641 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2644 * hConsoleOutput [I] Handle to console screen buffer
2645 * dwSize [I] New size in character rows and cols
2651 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2655 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2656 SERVER_START_REQ(set_console_output_info)
2658 req->handle = console_handle_unmap(hConsoleOutput);
2659 req->width = dwSize.X;
2660 req->height = dwSize.Y;
2661 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2662 ret = !wine_server_call_err( req );
2669 /******************************************************************************
2670 * ScrollConsoleScreenBufferA [KERNEL32.@]
2673 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2674 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2679 ciw.Attributes = lpFill->Attributes;
2680 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2682 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2683 dwDestOrigin, &ciw);
2686 /******************************************************************
2687 * CONSOLE_FillLineUniform
2689 * Helper function for ScrollConsoleScreenBufferW
2690 * Fills a part of a line with a constant character info
2692 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2694 SERVER_START_REQ( fill_console_output )
2696 req->handle = console_handle_unmap(hConsoleOutput);
2697 req->mode = CHAR_INFO_MODE_TEXTATTR;
2702 req->data.ch = lpFill->Char.UnicodeChar;
2703 req->data.attr = lpFill->Attributes;
2704 wine_server_call_err( req );
2709 /******************************************************************************
2710 * ScrollConsoleScreenBufferW [KERNEL32.@]
2714 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2715 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2723 CONSOLE_SCREEN_BUFFER_INFO csbi;
2728 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2729 lpScrollRect->Left, lpScrollRect->Top,
2730 lpScrollRect->Right, lpScrollRect->Bottom,
2731 lpClipRect->Left, lpClipRect->Top,
2732 lpClipRect->Right, lpClipRect->Bottom,
2733 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2735 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2736 lpScrollRect->Left, lpScrollRect->Top,
2737 lpScrollRect->Right, lpScrollRect->Bottom,
2738 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2740 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2743 src.X = lpScrollRect->Left;
2744 src.Y = lpScrollRect->Top;
2746 /* step 1: get dst rect */
2747 dst.Left = dwDestOrigin.X;
2748 dst.Top = dwDestOrigin.Y;
2749 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2750 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2752 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2755 clip.Left = max(0, lpClipRect->Left);
2756 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2757 clip.Top = max(0, lpClipRect->Top);
2758 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2763 clip.Right = csbi.dwSize.X - 1;
2765 clip.Bottom = csbi.dwSize.Y - 1;
2767 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2769 /* step 2b: clip dst rect */
2770 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2771 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2772 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2773 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2775 /* step 3: transfer the bits */
2776 SERVER_START_REQ(move_console_output)
2778 req->handle = console_handle_unmap(hConsoleOutput);
2781 req->x_dst = dst.Left;
2782 req->y_dst = dst.Top;
2783 req->w = dst.Right - dst.Left + 1;
2784 req->h = dst.Bottom - dst.Top + 1;
2785 ret = !wine_server_call_err( req );
2789 if (!ret) return FALSE;
2791 /* step 4: clean out the exposed part */
2793 /* have to write cell [i,j] if it is not in dst rect (because it has already
2794 * been written to by the scroll) and is in clip (we shall not write
2797 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2799 inside = dst.Top <= j && j <= dst.Bottom;
2801 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2803 if (inside && dst.Left <= i && i <= dst.Right)
2807 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2813 if (start == -1) start = i;
2817 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2823 /******************************************************************
2824 * AttachConsole (KERNEL32.@)
2826 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2828 FIXME("stub %x\n",dwProcessId);
2832 /******************************************************************
2833 * GetConsoleDisplayMode (KERNEL32.@)
2835 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2837 TRACE("semi-stub: %p\n", lpModeFlags);
2838 /* It is safe to successfully report windowed mode */
2843 /******************************************************************
2844 * SetConsoleDisplayMode (KERNEL32.@)
2846 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2847 COORD *lpNewScreenBufferDimensions)
2849 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2850 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2853 /* We cannot switch to fullscreen */
2860 /* ====================================================================
2862 * Console manipulation functions
2864 * ====================================================================*/
2866 /* some missing functions...
2867 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2868 * should get the right API and implement them
2869 * GetConsoleCommandHistory[AW] (dword dword dword)
2870 * GetConsoleCommandHistoryLength[AW]
2871 * SetConsoleCommandHistoryMode
2872 * SetConsoleNumberOfCommands[AW]
2874 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2878 SERVER_START_REQ( get_console_input_history )
2882 if (buf && buf_len > 1)
2884 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2886 if (!wine_server_call_err( req ))
2888 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2889 len = reply->total / sizeof(WCHAR) + 1;
2896 /******************************************************************
2897 * CONSOLE_AppendHistory
2901 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2903 size_t len = strlenW(ptr);
2906 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2907 if (!len) return FALSE;
2909 SERVER_START_REQ( append_console_input_history )
2912 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2913 ret = !wine_server_call_err( req );
2919 /******************************************************************
2920 * CONSOLE_GetNumHistoryEntries
2924 unsigned CONSOLE_GetNumHistoryEntries(void)
2927 SERVER_START_REQ(get_console_input_info)
2930 if (!wine_server_call_err( req )) ret = reply->history_index;
2936 /******************************************************************
2937 * CONSOLE_GetEditionMode
2941 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2943 unsigned ret = FALSE;
2944 SERVER_START_REQ(get_console_input_info)
2946 req->handle = console_handle_unmap(hConIn);
2947 if ((ret = !wine_server_call_err( req )))
2948 *mode = reply->edition_mode;
2954 /******************************************************************
2959 * 0 if an error occurred, non-zero for success
2962 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
2963 DWORD TargetBufferLength, LPWSTR lpExename)
2965 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
2966 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2970 /******************************************************************
2971 * GetConsoleProcessList (KERNEL32.@)
2973 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
2975 FIXME("(%p,%d): stub\n", processlist, processcount);
2977 if (!processlist || processcount < 1)
2979 SetLastError(ERROR_INVALID_PARAMETER);
2986 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
2988 memset(&S_termios, 0, sizeof(S_termios));
2989 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
2993 /* FIXME: to be done even if program is a GUI ? */
2994 /* This is wine specific: we have no parent (we're started from unix)
2995 * so, create a simple console with bare handles
2997 wine_server_send_fd(0);
2998 SERVER_START_REQ( alloc_console )
3000 req->access = GENERIC_READ | GENERIC_WRITE;
3001 req->attributes = OBJ_INHERIT;
3002 req->pid = 0xffffffff;
3004 wine_server_call( req );
3005 conin = wine_server_ptr_handle( reply->handle_in );
3006 /* reply->event shouldn't be created by server */
3010 if (!params->hStdInput)
3011 params->hStdInput = conin;
3013 if (!params->hStdOutput)
3015 wine_server_send_fd(1);
3016 SERVER_START_REQ( create_console_output )
3018 req->handle_in = wine_server_obj_handle(conin);
3019 req->access = GENERIC_WRITE|GENERIC_READ;
3020 req->attributes = OBJ_INHERIT;
3021 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3023 wine_server_call(req);
3024 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3028 if (!params->hStdError)
3030 wine_server_send_fd(2);
3031 SERVER_START_REQ( create_console_output )
3033 req->handle_in = wine_server_obj_handle(conin);
3034 req->access = GENERIC_WRITE|GENERIC_READ;
3035 req->attributes = OBJ_INHERIT;
3036 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3038 wine_server_call(req);
3039 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3045 /* convert value from server:
3046 * + 0 => INVALID_HANDLE_VALUE
3047 * + console handle needs to be mapped
3049 if (!params->hStdInput)
3050 params->hStdInput = INVALID_HANDLE_VALUE;
3051 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3053 params->hStdInput = console_handle_map(params->hStdInput);
3054 save_console_mode(params->hStdInput);
3057 if (!params->hStdOutput)
3058 params->hStdOutput = INVALID_HANDLE_VALUE;
3059 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3060 params->hStdOutput = console_handle_map(params->hStdOutput);
3062 if (!params->hStdError)
3063 params->hStdError = INVALID_HANDLE_VALUE;
3064 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3065 params->hStdError = console_handle_map(params->hStdError);
3070 BOOL CONSOLE_Exit(void)
3072 /* the console is in raw mode, put it back in cooked mode */
3073 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));