2 * Win32 console functions
4 * Copyright 1995 Martin von Loewis and Cameron Heide
5 * Copyright 1997 Karl Garrison
6 * Copyright 1998 John Richardson
7 * Copyright 1998 Marcus Meissner
8 * Copyright 2001,2002,2004,2005 Eric Pouech
9 * Copyright 2001 Alexandre Julliard
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 /* Reference applications:
27 * - IDA (interactive disassembler) full version 3.75. Works.
28 * - LYNX/W32. Works mostly, some keys crash it.
32 #include "wine/port.h"
46 #define WIN32_NO_STATUS
52 #include "wine/server.h"
53 #include "wine/exception.h"
54 #include "wine/unicode.h"
55 #include "wine/debug.h"
57 #include "console_private.h"
58 #include "kernel_private.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(console);
62 static CRITICAL_SECTION CONSOLE_CritSect;
63 static CRITICAL_SECTION_DEBUG critsect_debug =
65 0, 0, &CONSOLE_CritSect,
66 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
67 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
69 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
71 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
72 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
74 /* FIXME: this is not thread safe */
75 static HANDLE console_wait_event;
77 /* map input records to ASCII */
78 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
83 for (i = 0; i < count; i++)
85 if (buffer[i].EventType != KEY_EVENT) continue;
86 WideCharToMultiByte( GetConsoleCP(), 0,
87 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
88 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
92 /* map input records to Unicode */
93 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
98 for (i = 0; i < count; i++)
100 if (buffer[i].EventType != KEY_EVENT) continue;
101 MultiByteToWideChar( GetConsoleCP(), 0,
102 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
103 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
107 /* map char infos to ASCII */
108 static void char_info_WtoA( CHAR_INFO *buffer, int count )
114 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
115 &ch, 1, NULL, NULL );
116 buffer->Char.AsciiChar = ch;
121 /* map char infos to Unicode */
122 static void char_info_AtoW( CHAR_INFO *buffer, int count )
128 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
129 buffer->Char.UnicodeChar = ch;
134 static struct termios S_termios; /* saved termios for bare consoles */
135 static BOOL S_termios_raw /* = FALSE */;
137 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
138 * - a bare console is created for all CUI programs started from command line (without
139 * wineconsole) (let's call those PS)
140 * - of course, every child of a PS which requires console inheritance will get it
141 * - the console termios attributes are saved at the start of program which is attached to be
143 * - if any program attached to a bare console requests input from console, the console is
144 * turned into raw mode
145 * - when the program which created the bare console (the program started from command line)
146 * exits, it will restore the console termios attributes it saved at startup (this
147 * will put back the console into cooked mode if it had been put in raw mode)
148 * - if any other program attached to this bare console is still alive, the Unix shell will put
149 * it in the background, hence forbidding access to the console. Therefore, reading console
150 * input will not be available when the bare console creator has died.
151 * FIXME: This is a limitation of current implementation
154 /* returns the fd for a bare console (-1 otherwise) */
155 static int get_console_bare_fd(HANDLE hin)
159 if (wine_server_handle_to_fd(hin, 0, &fd, NULL) == STATUS_SUCCESS)
164 static BOOL save_console_mode(HANDLE hin)
169 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
170 ret = tcgetattr(fd, &S_termios) >= 0;
175 static BOOL put_console_into_raw_mode(int fd)
177 RtlEnterCriticalSection(&CONSOLE_CritSect);
180 struct termios term = S_termios;
182 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
183 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
184 term.c_cflag &= ~(CSIZE | PARENB);
186 /* FIXME: we should actually disable output processing here
187 * and let kernel32/console.c do the job (with support of enable/disable of
190 /* term.c_oflag &= ~(OPOST); */
192 term.c_cc[VTIME] = 0;
193 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
195 RtlLeaveCriticalSection(&CONSOLE_CritSect);
197 return S_termios_raw;
200 /* put back the console in cooked mode iff we're the process which created the bare console
201 * we don't test if thie process has set the console in raw mode as it could be one of its
204 static BOOL restore_console_mode(HANDLE hin)
209 if (!S_termios_raw ||
210 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
212 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
213 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
218 /******************************************************************************
219 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
222 * Success: hwnd of the console window.
225 HWND WINAPI GetConsoleWindow(VOID)
229 SERVER_START_REQ(get_console_input_info)
232 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
240 /******************************************************************************
241 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
246 UINT WINAPI GetConsoleCP(VOID)
249 UINT codepage = GetOEMCP(); /* default value */
251 SERVER_START_REQ(get_console_input_info)
254 ret = !wine_server_call_err(req);
255 if (ret && reply->input_cp)
256 codepage = reply->input_cp;
264 /******************************************************************************
265 * SetConsoleCP [KERNEL32.@]
267 BOOL WINAPI SetConsoleCP(UINT cp)
271 if (!IsValidCodePage(cp))
273 SetLastError(ERROR_INVALID_PARAMETER);
277 SERVER_START_REQ(set_console_input_info)
280 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
282 ret = !wine_server_call_err(req);
290 /***********************************************************************
291 * GetConsoleOutputCP (KERNEL32.@)
293 UINT WINAPI GetConsoleOutputCP(VOID)
296 UINT codepage = GetOEMCP(); /* default value */
298 SERVER_START_REQ(get_console_input_info)
301 ret = !wine_server_call_err(req);
302 if (ret && reply->output_cp)
303 codepage = reply->output_cp;
311 /******************************************************************************
312 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
315 * cp [I] code page to set
321 BOOL WINAPI SetConsoleOutputCP(UINT cp)
325 if (!IsValidCodePage(cp))
327 SetLastError(ERROR_INVALID_PARAMETER);
331 SERVER_START_REQ(set_console_input_info)
334 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
336 ret = !wine_server_call_err(req);
344 /***********************************************************************
347 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
349 static const char beep = '\a';
350 /* dwFreq and dwDur are ignored by Win95 */
351 if (isatty(2)) write( 2, &beep, 1 );
356 /******************************************************************
357 * OpenConsoleW (KERNEL32.@)
360 * Open a handle to the current process console.
361 * Returns INVALID_HANDLE_VALUE on failure.
363 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
365 HANDLE output = INVALID_HANDLE_VALUE;
368 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
372 if (strcmpiW(coninW, name) == 0)
373 output = (HANDLE) FALSE;
374 else if (strcmpiW(conoutW, name) == 0)
375 output = (HANDLE) TRUE;
378 if (output == INVALID_HANDLE_VALUE)
380 SetLastError(ERROR_INVALID_PARAMETER);
381 return INVALID_HANDLE_VALUE;
383 else if (creation != OPEN_EXISTING)
385 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
386 SetLastError(ERROR_SHARING_VIOLATION);
388 SetLastError(ERROR_INVALID_PARAMETER);
389 return INVALID_HANDLE_VALUE;
392 SERVER_START_REQ( open_console )
394 req->from = wine_server_obj_handle( output );
395 req->access = access;
396 req->attributes = inherit ? OBJ_INHERIT : 0;
397 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
398 wine_server_call_err( req );
399 ret = wine_server_ptr_handle( reply->handle );
403 ret = console_handle_map(ret);
408 /******************************************************************
409 * VerifyConsoleIoHandle (KERNEL32.@)
413 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
417 if (!is_console_handle(handle)) return FALSE;
418 SERVER_START_REQ(get_console_mode)
420 req->handle = console_handle_unmap(handle);
421 ret = !wine_server_call( req );
427 /******************************************************************
428 * DuplicateConsoleHandle (KERNEL32.@)
432 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
437 if (!is_console_handle(handle) ||
438 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
439 GetCurrentProcess(), &ret, access, inherit, options))
440 return INVALID_HANDLE_VALUE;
441 return console_handle_map(ret);
444 /******************************************************************
445 * CloseConsoleHandle (KERNEL32.@)
449 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
451 if (!is_console_handle(handle))
453 SetLastError(ERROR_INVALID_PARAMETER);
456 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
459 /******************************************************************
460 * GetConsoleInputWaitHandle (KERNEL32.@)
464 HANDLE WINAPI GetConsoleInputWaitHandle(void)
466 if (!console_wait_event)
468 SERVER_START_REQ(get_console_wait_event)
470 if (!wine_server_call_err( req ))
471 console_wait_event = wine_server_ptr_handle( reply->handle );
475 return console_wait_event;
479 /******************************************************************************
480 * WriteConsoleInputA [KERNEL32.@]
482 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
483 DWORD count, LPDWORD written )
488 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
489 memcpy( recW, buffer, count*sizeof(*recW) );
490 input_records_AtoW( recW, count );
491 ret = WriteConsoleInputW( handle, recW, count, written );
492 HeapFree( GetProcessHeap(), 0, recW );
497 /******************************************************************************
498 * WriteConsoleInputW [KERNEL32.@]
500 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
501 DWORD count, LPDWORD written )
505 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
507 if (written) *written = 0;
508 SERVER_START_REQ( write_console_input )
510 req->handle = console_handle_unmap(handle);
511 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
512 if ((ret = !wine_server_call_err( req )) && written)
513 *written = reply->written;
521 /***********************************************************************
522 * WriteConsoleOutputA (KERNEL32.@)
524 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
525 COORD size, COORD coord, LPSMALL_RECT region )
529 COORD new_size, new_coord;
532 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
533 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
535 if (new_size.X <= 0 || new_size.Y <= 0)
537 region->Bottom = region->Top + new_size.Y - 1;
538 region->Right = region->Left + new_size.X - 1;
542 /* only copy the useful rectangle */
543 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
545 for (y = 0; y < new_size.Y; y++)
547 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
548 new_size.X * sizeof(CHAR_INFO) );
549 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
551 new_coord.X = new_coord.Y = 0;
552 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
553 HeapFree( GetProcessHeap(), 0, ciw );
558 /***********************************************************************
559 * WriteConsoleOutputW (KERNEL32.@)
561 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
562 COORD size, COORD coord, LPSMALL_RECT region )
564 int width, height, y;
567 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
568 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
569 region->Left, region->Top, region->Right, region->Bottom);
571 width = min( region->Right - region->Left + 1, size.X - coord.X );
572 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
574 if (width > 0 && height > 0)
576 for (y = 0; y < height; y++)
578 SERVER_START_REQ( write_console_output )
580 req->handle = console_handle_unmap(hConsoleOutput);
581 req->x = region->Left;
582 req->y = region->Top + y;
583 req->mode = CHAR_INFO_MODE_TEXTATTR;
585 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
586 width * sizeof(CHAR_INFO));
587 if ((ret = !wine_server_call_err( req )))
589 width = min( width, reply->width - region->Left );
590 height = min( height, reply->height - region->Top );
597 region->Bottom = region->Top + height - 1;
598 region->Right = region->Left + width - 1;
603 /******************************************************************************
604 * WriteConsoleOutputCharacterA [KERNEL32.@]
606 * See WriteConsoleOutputCharacterW.
608 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
609 COORD coord, LPDWORD lpNumCharsWritten )
615 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
616 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
618 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
620 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
622 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
623 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
625 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
626 HeapFree( GetProcessHeap(), 0, strW );
631 /******************************************************************************
632 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
633 * the console screen buffer
636 * hConsoleOutput [I] Handle to screen buffer
637 * attr [I] Pointer to buffer with write attributes
638 * length [I] Number of cells to write to
639 * coord [I] Coords of first cell
640 * lpNumAttrsWritten [O] Pointer to number of cells written
647 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
648 COORD coord, LPDWORD lpNumAttrsWritten )
652 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
654 SERVER_START_REQ( write_console_output )
656 req->handle = console_handle_unmap(hConsoleOutput);
659 req->mode = CHAR_INFO_MODE_ATTR;
661 wine_server_add_data( req, attr, length * sizeof(WORD) );
662 if ((ret = !wine_server_call_err( req )))
664 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
672 /******************************************************************************
673 * FillConsoleOutputCharacterA [KERNEL32.@]
675 * See FillConsoleOutputCharacterW.
677 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
678 COORD coord, LPDWORD lpNumCharsWritten )
682 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
683 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
687 /******************************************************************************
688 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
691 * hConsoleOutput [I] Handle to screen buffer
692 * ch [I] Character to write
693 * length [I] Number of cells to write to
694 * coord [I] Coords of first cell
695 * lpNumCharsWritten [O] Pointer to number of cells written
701 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
702 COORD coord, LPDWORD lpNumCharsWritten)
706 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
707 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
709 SERVER_START_REQ( fill_console_output )
711 req->handle = console_handle_unmap(hConsoleOutput);
714 req->mode = CHAR_INFO_MODE_TEXT;
718 if ((ret = !wine_server_call_err( req )))
720 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
728 /******************************************************************************
729 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
732 * hConsoleOutput [I] Handle to screen buffer
733 * attr [I] Color attribute to write
734 * length [I] Number of cells to write to
735 * coord [I] Coords of first cell
736 * lpNumAttrsWritten [O] Pointer to number of cells written
742 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
743 COORD coord, LPDWORD lpNumAttrsWritten )
747 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
748 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
750 SERVER_START_REQ( fill_console_output )
752 req->handle = console_handle_unmap(hConsoleOutput);
755 req->mode = CHAR_INFO_MODE_ATTR;
757 req->data.attr = attr;
759 if ((ret = !wine_server_call_err( req )))
761 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
769 /******************************************************************************
770 * ReadConsoleOutputCharacterA [KERNEL32.@]
773 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
774 COORD coord, LPDWORD read_count)
778 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
780 if (read_count) *read_count = 0;
781 if (!wptr) return FALSE;
783 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
785 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
786 if (read_count) *read_count = read;
788 HeapFree( GetProcessHeap(), 0, wptr );
793 /******************************************************************************
794 * ReadConsoleOutputCharacterW [KERNEL32.@]
797 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
798 COORD coord, LPDWORD read_count )
802 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
804 SERVER_START_REQ( read_console_output )
806 req->handle = console_handle_unmap(hConsoleOutput);
809 req->mode = CHAR_INFO_MODE_TEXT;
811 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
812 if ((ret = !wine_server_call_err( req )))
814 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
822 /******************************************************************************
823 * ReadConsoleOutputAttribute [KERNEL32.@]
825 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
826 COORD coord, LPDWORD read_count)
830 TRACE("(%p,%p,%d,%dx%d,%p)\n",
831 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
833 SERVER_START_REQ( read_console_output )
835 req->handle = console_handle_unmap(hConsoleOutput);
838 req->mode = CHAR_INFO_MODE_ATTR;
840 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
841 if ((ret = !wine_server_call_err( req )))
843 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
851 /******************************************************************************
852 * ReadConsoleOutputA [KERNEL32.@]
855 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
856 COORD coord, LPSMALL_RECT region )
861 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
862 if (ret && region->Right >= region->Left)
864 for (y = 0; y <= region->Bottom - region->Top; y++)
866 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
867 region->Right - region->Left + 1 );
874 /******************************************************************************
875 * ReadConsoleOutputW [KERNEL32.@]
877 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
878 * think we need to be *that* compatible. -- AJ
880 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
881 COORD coord, LPSMALL_RECT region )
883 int width, height, y;
886 width = min( region->Right - region->Left + 1, size.X - coord.X );
887 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
889 if (width > 0 && height > 0)
891 for (y = 0; y < height; y++)
893 SERVER_START_REQ( read_console_output )
895 req->handle = console_handle_unmap(hConsoleOutput);
896 req->x = region->Left;
897 req->y = region->Top + y;
898 req->mode = CHAR_INFO_MODE_TEXTATTR;
900 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
901 width * sizeof(CHAR_INFO) );
902 if ((ret = !wine_server_call_err( req )))
904 width = min( width, reply->width - region->Left );
905 height = min( height, reply->height - region->Top );
912 region->Bottom = region->Top + height - 1;
913 region->Right = region->Left + width - 1;
918 /******************************************************************************
919 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
922 * handle [I] Handle to console input buffer
923 * buffer [O] Address of buffer for read data
924 * count [I] Number of records to read
925 * pRead [O] Address of number of records read
931 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
935 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
936 input_records_WtoA( buffer, read );
937 if (pRead) *pRead = read;
942 /***********************************************************************
943 * PeekConsoleInputA (KERNEL32.@)
945 * Gets 'count' first events (or less) from input queue.
947 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
951 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
952 input_records_WtoA( buffer, read );
953 if (pRead) *pRead = read;
958 /***********************************************************************
959 * PeekConsoleInputW (KERNEL32.@)
961 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
964 SERVER_START_REQ( read_console_input )
966 req->handle = console_handle_unmap(handle);
968 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
969 if ((ret = !wine_server_call_err( req )))
971 if (read) *read = count ? reply->read : 0;
979 /***********************************************************************
980 * GetNumberOfConsoleInputEvents (KERNEL32.@)
982 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
985 SERVER_START_REQ( read_console_input )
987 req->handle = console_handle_unmap(handle);
989 if ((ret = !wine_server_call_err( req )))
991 if (nrofevents) *nrofevents = reply->read;
999 /******************************************************************************
1000 * read_console_input
1002 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1005 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1007 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1008 static const int vkkeyscan_table[256] =
1010 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,
1011 0,32,305,478,307,308,309,311,222,313,304,312,443,188,189,190,191,48,
1012 49,50,51,52,53,54,55,56,57,442,186,444,187,446,447,306,321,322,323,
1013 324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,
1014 341,342,343,344,345,346,219,220,221,310,445,192,65,66,67,68,69,70,71,
1015 72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,475,476,477,
1016 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,
1017 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,
1018 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1019 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,400,0,0,0,0,0,0
1022 static const int mapvkey_0[256] =
1024 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,
1025 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,
1026 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,
1027 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,
1028 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,
1029 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,
1030 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,
1031 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,
1032 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
1035 static inline void init_complex_char(INPUT_RECORD* ir, BOOL down, WORD vk, WORD kc, DWORD cks)
1037 ir->EventType = KEY_EVENT;
1038 ir->Event.KeyEvent.bKeyDown = down;
1039 ir->Event.KeyEvent.wRepeatCount = 1;
1040 ir->Event.KeyEvent.wVirtualScanCode = vk;
1041 ir->Event.KeyEvent.wVirtualKeyCode = kc;
1042 ir->Event.KeyEvent.dwControlKeyState = cks;
1043 ir->Event.KeyEvent.uChar.UnicodeChar = 0;
1046 /******************************************************************
1047 * handle_simple_char
1051 static BOOL handle_simple_char(HANDLE conin, unsigned real_inchar)
1056 unsigned numEvent = 0;
1057 DWORD cks = 0, written;
1060 switch (real_inchar)
1062 case 9: inchar = real_inchar;
1063 real_inchar = 27; /* so that we don't think key is ctrl- something */
1066 case 10: inchar = '\r';
1067 real_inchar = 27; /* Fixme: so that we don't think key is ctrl- something */
1069 case 127: inchar = '\b';
1072 inchar = real_inchar;
1075 if ((inchar & ~0xFF) != 0) FIXME("What a char (%u)\n", inchar);
1076 vk = vkkeyscan_table[inchar];
1078 init_complex_char(&ir[numEvent++], 1, 0x2a, 0x10, SHIFT_PRESSED);
1079 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1080 init_complex_char(&ir[numEvent++], 1, 0x1d, 0x11, LEFT_CTRL_PRESSED);
1082 init_complex_char(&ir[numEvent++], 1, 0x38, 0x12, LEFT_ALT_PRESSED);
1084 ir[numEvent].EventType = KEY_EVENT;
1085 ir[numEvent].Event.KeyEvent.bKeyDown = 1;
1086 ir[numEvent].Event.KeyEvent.wRepeatCount = 1;
1087 ir[numEvent].Event.KeyEvent.dwControlKeyState = cks;
1089 ir[numEvent].Event.KeyEvent.dwControlKeyState |= SHIFT_PRESSED;
1090 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1091 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_CTRL_PRESSED;
1093 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_ALT_PRESSED;
1094 ir[numEvent].Event.KeyEvent.wVirtualKeyCode = vk;
1095 ir[numEvent].Event.KeyEvent.wVirtualScanCode = mapvkey_0[vk & 0x00ff]; /* VirtualKeyCodes to ScanCode */
1098 MultiByteToWideChar(CP_UNIXCP, 0, &ch, 1, &ir[numEvent].Event.KeyEvent.uChar.UnicodeChar, 1);
1099 ir[numEvent + 1] = ir[numEvent];
1100 ir[numEvent + 1].Event.KeyEvent.bKeyDown = 0;
1105 init_complex_char(&ir[numEvent++], 0, 0x38, 0x12, LEFT_ALT_PRESSED);
1106 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1107 init_complex_char(&ir[numEvent++], 0, 0x1d, 0x11, 0);
1109 init_complex_char(&ir[numEvent++], 0, 0x2a, 0x10, 0);
1111 return WriteConsoleInputW(conin, ir, numEvent, &written);
1114 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, DWORD timeout)
1117 enum read_console_input_return ret;
1120 /* get the real handle to the console object */
1121 handle = wine_server_ptr_handle(console_handle_unmap(handle));
1123 memset(&ov, 0, sizeof(ov));
1124 ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1126 if (ReadFile(handle, &ch, 1, NULL, &ov) ||
1127 (GetLastError() == ERROR_IO_PENDING &&
1128 WaitForSingleObject(ov.hEvent, timeout) == WAIT_OBJECT_0 &&
1129 GetOverlappedResult(handle, &ov, NULL, FALSE)))
1131 ret = handle_simple_char(handle, ch) ? rci_gotone : rci_error;
1135 WARN("Failed read %x\n", GetLastError());
1138 CloseHandle(ov.hEvent);
1143 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1146 enum read_console_input_return ret;
1148 if ((fd = get_console_bare_fd(handle)) != -1)
1150 put_console_into_raw_mode(fd);
1152 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1154 ret = bare_console_fetch_input(handle, timeout);
1155 if (ret != rci_gotone) return ret;
1160 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1162 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1166 SERVER_START_REQ( read_console_input )
1168 req->handle = console_handle_unmap(handle);
1170 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1171 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1172 else ret = rci_gotone;
1180 /***********************************************************************
1181 * FlushConsoleInputBuffer (KERNEL32.@)
1183 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1185 enum read_console_input_return last;
1188 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1190 return last == rci_timeout;
1194 /***********************************************************************
1195 * SetConsoleTitleA (KERNEL32.@)
1197 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1202 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1203 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1204 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1205 ret = SetConsoleTitleW(titleW);
1206 HeapFree(GetProcessHeap(), 0, titleW);
1211 /***********************************************************************
1212 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1214 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1216 FIXME( "stub %p\n", layoutName);
1220 /***********************************************************************
1221 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1223 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1225 FIXME( "stub %p\n", layoutName);
1229 static WCHAR input_exe[MAX_PATH + 1];
1231 /***********************************************************************
1232 * GetConsoleInputExeNameW (KERNEL32.@)
1234 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1236 TRACE("%u %p\n", buflen, buffer);
1238 RtlEnterCriticalSection(&CONSOLE_CritSect);
1239 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1240 else SetLastError(ERROR_BUFFER_OVERFLOW);
1241 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1246 /***********************************************************************
1247 * GetConsoleInputExeNameA (KERNEL32.@)
1249 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1251 TRACE("%u %p\n", buflen, buffer);
1253 RtlEnterCriticalSection(&CONSOLE_CritSect);
1254 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1255 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1256 else SetLastError(ERROR_BUFFER_OVERFLOW);
1257 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1262 /***********************************************************************
1263 * GetConsoleTitleA (KERNEL32.@)
1265 * See GetConsoleTitleW.
1267 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1269 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1273 ret = GetConsoleTitleW( ptr, size );
1276 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1277 ret = strlen(title);
1279 HeapFree(GetProcessHeap(), 0, ptr);
1284 /******************************************************************************
1285 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1288 * title [O] Address of buffer for title
1289 * size [I] Size of buffer
1292 * Success: Length of string copied
1295 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1299 SERVER_START_REQ( get_console_input_info )
1302 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1303 if (!wine_server_call_err( req ))
1305 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1314 /***********************************************************************
1315 * GetLargestConsoleWindowSize (KERNEL32.@)
1318 * This should return a COORD, but calling convention for returning
1319 * structures is different between Windows and gcc on i386.
1324 #undef GetLargestConsoleWindowSize
1325 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1333 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1336 #endif /* defined(__i386__) */
1339 /***********************************************************************
1340 * GetLargestConsoleWindowSize (KERNEL32.@)
1343 * This should return a COORD, but calling convention for returning
1344 * structures is different between Windows and gcc on i386.
1349 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1354 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1357 #endif /* defined(__i386__) */
1359 static WCHAR* S_EditString /* = NULL */;
1360 static unsigned S_EditStrPos /* = 0 */;
1362 /***********************************************************************
1363 * FreeConsole (KERNEL32.@)
1365 BOOL WINAPI FreeConsole(VOID)
1369 /* invalidate local copy of input event handle */
1370 console_wait_event = 0;
1372 SERVER_START_REQ(free_console)
1374 ret = !wine_server_call_err( req );
1380 /******************************************************************
1381 * start_console_renderer
1383 * helper for AllocConsole
1384 * starts the renderer process
1386 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1391 PROCESS_INFORMATION pi;
1393 /* FIXME: use dynamic allocation for most of the buffers below */
1394 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1395 if ((ret > -1) && (ret < sizeof(buffer)) &&
1396 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1397 NULL, NULL, si, &pi))
1403 wh[1] = pi.hProcess;
1404 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1406 CloseHandle(pi.hThread);
1407 CloseHandle(pi.hProcess);
1409 if (ret != WAIT_OBJECT_0) return FALSE;
1411 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1412 pi.dwProcessId, pi.dwThreadId);
1419 static BOOL start_console_renderer(STARTUPINFOA* si)
1423 OBJECT_ATTRIBUTES attr;
1426 attr.Length = sizeof(attr);
1427 attr.RootDirectory = 0;
1428 attr.Attributes = OBJ_INHERIT;
1429 attr.ObjectName = NULL;
1430 attr.SecurityDescriptor = NULL;
1431 attr.SecurityQualityOfService = NULL;
1433 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1434 if (!hEvent) return FALSE;
1436 /* first try environment variable */
1437 if ((p = getenv("WINECONSOLE")) != NULL)
1439 ret = start_console_renderer_helper(p, si, hEvent);
1441 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1442 "trying default access\n", p);
1445 /* then try the regular PATH */
1447 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1449 CloseHandle(hEvent);
1453 /***********************************************************************
1454 * AllocConsole (KERNEL32.@)
1456 * creates an xterm with a pty to our program
1458 BOOL WINAPI AllocConsole(void)
1460 HANDLE handle_in = INVALID_HANDLE_VALUE;
1461 HANDLE handle_out = INVALID_HANDLE_VALUE;
1462 HANDLE handle_err = INVALID_HANDLE_VALUE;
1463 STARTUPINFOA siCurrent;
1464 STARTUPINFOA siConsole;
1469 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1470 FALSE, OPEN_EXISTING );
1472 if (VerifyConsoleIoHandle(handle_in))
1474 /* we already have a console opened on this process, don't create a new one */
1475 CloseHandle(handle_in);
1479 /* invalidate local copy of input event handle */
1480 console_wait_event = 0;
1482 GetStartupInfoA(&siCurrent);
1484 memset(&siConsole, 0, sizeof(siConsole));
1485 siConsole.cb = sizeof(siConsole);
1486 /* setup a view arguments for wineconsole (it'll use them as default values) */
1487 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1489 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1490 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1491 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1493 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1495 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1496 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1498 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1500 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1501 siConsole.wShowWindow = siCurrent.wShowWindow;
1503 /* FIXME (should pass the unicode form) */
1504 if (siCurrent.lpTitle)
1505 siConsole.lpTitle = siCurrent.lpTitle;
1506 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1508 buffer[sizeof(buffer) - 1] = '\0';
1509 siConsole.lpTitle = buffer;
1512 if (!start_console_renderer(&siConsole))
1515 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1516 /* all std I/O handles are inheritable by default */
1517 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1518 TRUE, OPEN_EXISTING );
1519 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1521 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1522 TRUE, OPEN_EXISTING );
1523 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1525 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1526 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1529 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1530 handle_in = siCurrent.hStdInput;
1531 handle_out = siCurrent.hStdOutput;
1532 handle_err = siCurrent.hStdError;
1535 /* NT resets the STD_*_HANDLEs on console alloc */
1536 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1537 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1538 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1540 SetLastError(ERROR_SUCCESS);
1545 ERR("Can't allocate console\n");
1546 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1547 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1548 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1554 /***********************************************************************
1555 * ReadConsoleA (KERNEL32.@)
1557 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1558 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1560 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1564 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1565 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1567 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1568 HeapFree(GetProcessHeap(), 0, ptr);
1573 /***********************************************************************
1574 * ReadConsoleW (KERNEL32.@)
1576 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1577 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1580 LPWSTR xbuf = lpBuffer;
1582 BOOL is_bare = FALSE;
1585 TRACE("(%p,%p,%d,%p,%p)\n",
1586 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1588 if (!GetConsoleMode(hConsoleInput, &mode))
1590 if ((fd == get_console_bare_fd(hConsoleInput)) == -1)
1595 if (mode & ENABLE_LINE_INPUT)
1597 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1599 HeapFree(GetProcessHeap(), 0, S_EditString);
1600 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1604 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1605 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1606 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1607 S_EditStrPos += charsread;
1612 DWORD timeout = INFINITE;
1614 /* FIXME: should we read at least 1 char? The SDK does not say */
1615 /* wait for at least one available input record (it doesn't mean we'll have
1616 * chars stored in xbuf...)
1618 * Although SDK doc keeps silence about 1 char, SDK examples assume
1619 * that we should wait for at least one character (not key). --KS
1624 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1625 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1626 ir.Event.KeyEvent.uChar.UnicodeChar)
1628 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1631 } while (charsread < nNumberOfCharsToRead);
1632 /* nothing has been read */
1633 if (timeout == INFINITE) return FALSE;
1636 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1642 /***********************************************************************
1643 * ReadConsoleInputW (KERNEL32.@)
1645 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1646 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1649 DWORD timeout = INFINITE;
1653 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1657 /* loop until we get at least one event */
1658 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1662 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1667 /******************************************************************************
1668 * WriteConsoleOutputCharacterW [KERNEL32.@]
1670 * Copy character to consecutive cells in the console screen buffer.
1673 * hConsoleOutput [I] Handle to screen buffer
1674 * str [I] Pointer to buffer with chars to write
1675 * length [I] Number of cells to write to
1676 * coord [I] Coords of first cell
1677 * lpNumCharsWritten [O] Pointer to number of cells written
1684 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1685 COORD coord, LPDWORD lpNumCharsWritten )
1689 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1690 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1692 SERVER_START_REQ( write_console_output )
1694 req->handle = console_handle_unmap(hConsoleOutput);
1697 req->mode = CHAR_INFO_MODE_TEXT;
1699 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1700 if ((ret = !wine_server_call_err( req )))
1702 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1710 /******************************************************************************
1711 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1714 * title [I] Address of new title
1720 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1724 TRACE("(%s)\n", debugstr_w(title));
1725 SERVER_START_REQ( set_console_input_info )
1728 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1729 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1730 ret = !wine_server_call_err( req );
1737 /***********************************************************************
1738 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1740 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1742 FIXME("(%p): stub\n", nrofbuttons);
1747 /******************************************************************************
1748 * SetConsoleInputExeNameW [KERNEL32.@]
1750 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1752 TRACE("(%s)\n", debugstr_w(name));
1754 if (!name || !name[0])
1756 SetLastError(ERROR_INVALID_PARAMETER);
1760 RtlEnterCriticalSection(&CONSOLE_CritSect);
1761 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1762 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1767 /******************************************************************************
1768 * SetConsoleInputExeNameA [KERNEL32.@]
1770 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1776 if (!name || !name[0])
1778 SetLastError(ERROR_INVALID_PARAMETER);
1782 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1783 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1785 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1786 ret = SetConsoleInputExeNameW(nameW);
1787 HeapFree(GetProcessHeap(), 0, nameW);
1792 /******************************************************************
1793 * CONSOLE_DefaultHandler
1795 * Final control event handler
1797 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1799 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1801 /* should never go here */
1805 /******************************************************************************
1806 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1809 * func [I] Address of handler function
1810 * add [I] Handler to add or remove
1817 struct ConsoleHandler
1819 PHANDLER_ROUTINE handler;
1820 struct ConsoleHandler* next;
1823 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1824 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1826 /*****************************************************************************/
1828 /******************************************************************
1829 * SetConsoleCtrlHandler (KERNEL32.@)
1831 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1835 TRACE("(%p,%i)\n", func, add);
1839 RtlEnterCriticalSection(&CONSOLE_CritSect);
1841 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1843 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1844 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1848 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1850 if (!ch) return FALSE;
1852 RtlEnterCriticalSection(&CONSOLE_CritSect);
1853 ch->next = CONSOLE_Handlers;
1854 CONSOLE_Handlers = ch;
1855 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1859 struct ConsoleHandler** ch;
1860 RtlEnterCriticalSection(&CONSOLE_CritSect);
1861 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1863 if ((*ch)->handler == func) break;
1867 struct ConsoleHandler* rch = *ch;
1870 if (rch == &CONSOLE_DefaultConsoleHandler)
1872 ERR("Who's trying to remove default handler???\n");
1873 SetLastError(ERROR_INVALID_PARAMETER);
1879 HeapFree(GetProcessHeap(), 0, rch);
1884 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1885 SetLastError(ERROR_INVALID_PARAMETER);
1888 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1893 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1895 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1896 return EXCEPTION_EXECUTE_HANDLER;
1899 /******************************************************************
1900 * CONSOLE_SendEventThread
1902 * Internal helper to pass an event to the list on installed handlers
1904 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1906 DWORD_PTR event = (DWORD_PTR)pmt;
1907 struct ConsoleHandler* ch;
1909 if (event == CTRL_C_EVENT)
1911 BOOL caught_by_dbg = TRUE;
1912 /* First, try to pass the ctrl-C event to the debugger (if any)
1913 * If it continues, there's nothing more to do
1914 * Otherwise, we need to send the ctrl-C event to the handlers
1918 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1920 __EXCEPT(CONSOLE_CtrlEventHandler)
1922 caught_by_dbg = FALSE;
1925 if (caught_by_dbg) return 0;
1926 /* the debugger didn't continue... so, pass to ctrl handlers */
1928 RtlEnterCriticalSection(&CONSOLE_CritSect);
1929 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1931 if (ch->handler(event)) break;
1933 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1937 /******************************************************************
1938 * CONSOLE_HandleCtrlC
1940 * Check whether the shall manipulate CtrlC events
1942 int CONSOLE_HandleCtrlC(unsigned sig)
1944 /* FIXME: better test whether a console is attached to this process ??? */
1945 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1946 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1948 /* check if we have to ignore ctrl-C events */
1949 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1951 /* Create a separate thread to signal all the events.
1952 * This is needed because:
1953 * - this function can be called in an Unix signal handler (hence on an
1954 * different stack than the thread that's running). This breaks the
1955 * Win32 exception mechanisms (where the thread's stack is checked).
1956 * - since the current thread, while processing the signal, can hold the
1957 * console critical section, we need another execution environment where
1958 * we can wait on this critical section
1960 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1965 /******************************************************************************
1966 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1969 * dwCtrlEvent [I] Type of event
1970 * dwProcessGroupID [I] Process group ID to send event to
1974 * Failure: False (and *should* [but doesn't] set LastError)
1976 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1977 DWORD dwProcessGroupID)
1981 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
1983 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1985 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
1989 SERVER_START_REQ( send_console_signal )
1991 req->signal = dwCtrlEvent;
1992 req->group_id = dwProcessGroupID;
1993 ret = !wine_server_call_err( req );
1997 /* FIXME: Shall this function be synchronous, i.e., only return when all events
1998 * have been handled by all processes in the given group?
1999 * As of today, we don't wait...
2005 /******************************************************************************
2006 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2009 * dwDesiredAccess [I] Access flag
2010 * dwShareMode [I] Buffer share mode
2011 * sa [I] Security attributes
2012 * dwFlags [I] Type of buffer to create
2013 * lpScreenBufferData [I] Reserved
2016 * Should call SetLastError
2019 * Success: Handle to new console screen buffer
2020 * Failure: INVALID_HANDLE_VALUE
2022 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2023 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2024 LPVOID lpScreenBufferData)
2026 HANDLE ret = INVALID_HANDLE_VALUE;
2028 TRACE("(%d,%d,%p,%d,%p)\n",
2029 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2031 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2033 SetLastError(ERROR_INVALID_PARAMETER);
2034 return INVALID_HANDLE_VALUE;
2037 SERVER_START_REQ(create_console_output)
2040 req->access = dwDesiredAccess;
2041 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2042 req->share = dwShareMode;
2044 if (!wine_server_call_err( req ))
2045 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2053 /***********************************************************************
2054 * GetConsoleScreenBufferInfo (KERNEL32.@)
2056 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2060 SERVER_START_REQ(get_console_output_info)
2062 req->handle = console_handle_unmap(hConsoleOutput);
2063 if ((ret = !wine_server_call_err( req )))
2065 csbi->dwSize.X = reply->width;
2066 csbi->dwSize.Y = reply->height;
2067 csbi->dwCursorPosition.X = reply->cursor_x;
2068 csbi->dwCursorPosition.Y = reply->cursor_y;
2069 csbi->wAttributes = reply->attr;
2070 csbi->srWindow.Left = reply->win_left;
2071 csbi->srWindow.Right = reply->win_right;
2072 csbi->srWindow.Top = reply->win_top;
2073 csbi->srWindow.Bottom = reply->win_bottom;
2074 csbi->dwMaximumWindowSize.X = reply->max_width;
2075 csbi->dwMaximumWindowSize.Y = reply->max_height;
2080 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2081 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2082 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2084 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2085 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2091 /******************************************************************************
2092 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2098 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2102 TRACE("(%p)\n", hConsoleOutput);
2104 SERVER_START_REQ( set_console_input_info )
2107 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2108 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2109 ret = !wine_server_call_err( req );
2116 /***********************************************************************
2117 * GetConsoleMode (KERNEL32.@)
2119 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2123 SERVER_START_REQ( get_console_mode )
2125 req->handle = console_handle_unmap(hcon);
2126 if ((ret = !wine_server_call_err( req )))
2128 if (mode) *mode = reply->mode;
2136 /******************************************************************************
2137 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2140 * hcon [I] Handle to console input or screen buffer
2141 * mode [I] Input or output mode to set
2148 * ENABLE_PROCESSED_INPUT 0x01
2149 * ENABLE_LINE_INPUT 0x02
2150 * ENABLE_ECHO_INPUT 0x04
2151 * ENABLE_WINDOW_INPUT 0x08
2152 * ENABLE_MOUSE_INPUT 0x10
2154 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2158 SERVER_START_REQ(set_console_mode)
2160 req->handle = console_handle_unmap(hcon);
2162 ret = !wine_server_call_err( req );
2165 /* FIXME: when resetting a console input to editline mode, I think we should
2166 * empty the S_EditString buffer
2169 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2175 /******************************************************************
2176 * CONSOLE_WriteChars
2178 * WriteConsoleOutput helper: hides server call semantics
2179 * writes a string at a given pos with standard attribute
2181 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2187 SERVER_START_REQ( write_console_output )
2189 req->handle = console_handle_unmap(hCon);
2192 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2194 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2195 if (!wine_server_call_err( req )) written = reply->written;
2199 if (written > 0) pos->X += written;
2203 /******************************************************************
2206 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2209 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2215 csbi->dwCursorPosition.X = 0;
2216 csbi->dwCursorPosition.Y++;
2218 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2221 src.Bottom = csbi->dwSize.Y - 1;
2223 src.Right = csbi->dwSize.X - 1;
2228 ci.Attributes = csbi->wAttributes;
2229 ci.Char.UnicodeChar = ' ';
2231 csbi->dwCursorPosition.Y--;
2232 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2237 /******************************************************************
2240 * WriteConsoleOutput helper: writes a block of non special characters
2241 * Block can spread on several lines, and wrapping, if needed, is
2245 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2246 DWORD mode, LPCWSTR ptr, int len)
2248 int blk; /* number of chars to write on current line */
2249 int done; /* number of chars already written */
2251 if (len <= 0) return 1;
2253 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2255 for (done = 0; done < len; done += blk)
2257 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2259 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2261 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2267 int pos = csbi->dwCursorPosition.X;
2268 /* FIXME: we could reduce the number of loops
2269 * but, in most cases we wouldn't gain lots of time (it would only
2270 * happen if we're asked to overwrite more than twice the part of the line,
2273 for (done = 0; done < len; done += blk)
2275 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2277 csbi->dwCursorPosition.X = pos;
2278 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2286 /***********************************************************************
2287 * WriteConsoleW (KERNEL32.@)
2289 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2290 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2294 const WCHAR* psz = lpBuffer;
2295 CONSOLE_SCREEN_BUFFER_INFO csbi;
2296 int k, first = 0, fd;
2298 TRACE("%p %s %d %p %p\n",
2299 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2300 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2302 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2304 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2311 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2314 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2315 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2318 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2319 ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2320 ptr, len, lpNumberOfCharsWritten, NULL);
2321 if (ret && lpNumberOfCharsWritten)
2323 if (*lpNumberOfCharsWritten == len)
2324 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2326 FIXME("Conversion not supported yet\n");
2328 HeapFree(GetProcessHeap(), 0, ptr);
2332 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2335 if (!nNumberOfCharsToWrite) return TRUE;
2337 if (mode & ENABLE_PROCESSED_OUTPUT)
2341 for (i = 0; i < nNumberOfCharsToWrite; i++)
2345 case '\b': case '\t': case '\n': case '\a': case '\r':
2346 /* don't handle here the i-th char... done below */
2347 if ((k = i - first) > 0)
2349 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2359 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2363 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2365 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2366 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2371 next_line(hConsoleOutput, &csbi);
2377 csbi.dwCursorPosition.X = 0;
2385 /* write the remaining block (if any) if processed output is enabled, or the
2386 * entire buffer otherwise
2388 if ((k = nNumberOfCharsToWrite - first) > 0)
2390 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2396 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2397 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2402 /***********************************************************************
2403 * WriteConsoleA (KERNEL32.@)
2405 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2406 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2412 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2414 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2415 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2416 if (!xstring) return 0;
2418 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2420 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2422 HeapFree(GetProcessHeap(), 0, xstring);
2427 /******************************************************************************
2428 * SetConsoleCursorPosition [KERNEL32.@]
2429 * Sets the cursor position in console
2432 * hConsoleOutput [I] Handle of console screen buffer
2433 * dwCursorPosition [I] New cursor position coordinates
2439 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2442 CONSOLE_SCREEN_BUFFER_INFO csbi;
2446 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2448 SERVER_START_REQ(set_console_output_info)
2450 req->handle = console_handle_unmap(hcon);
2451 req->cursor_x = pos.X;
2452 req->cursor_y = pos.Y;
2453 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2454 ret = !wine_server_call_err( req );
2458 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2461 /* if cursor is no longer visible, scroll the visible window... */
2462 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2463 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2464 if (pos.X < csbi.srWindow.Left)
2466 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2469 else if (pos.X > csbi.srWindow.Right)
2471 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2474 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2476 if (pos.Y < csbi.srWindow.Top)
2478 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2481 else if (pos.Y > csbi.srWindow.Bottom)
2483 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2486 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2488 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2493 /******************************************************************************
2494 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2497 * hcon [I] Handle to console screen buffer
2498 * cinfo [O] Address of cursor information
2504 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2508 SERVER_START_REQ(get_console_output_info)
2510 req->handle = console_handle_unmap(hCon);
2511 ret = !wine_server_call_err( req );
2514 cinfo->dwSize = reply->cursor_size;
2515 cinfo->bVisible = reply->cursor_visible;
2520 if (!ret) return FALSE;
2524 SetLastError(ERROR_INVALID_ACCESS);
2527 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2533 /******************************************************************************
2534 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2537 * hcon [I] Handle to console screen buffer
2538 * cinfo [I] Address of cursor information
2543 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2547 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2548 SERVER_START_REQ(set_console_output_info)
2550 req->handle = console_handle_unmap(hCon);
2551 req->cursor_size = cinfo->dwSize;
2552 req->cursor_visible = cinfo->bVisible;
2553 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2554 ret = !wine_server_call_err( req );
2561 /******************************************************************************
2562 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2565 * hcon [I] Handle to console screen buffer
2566 * bAbsolute [I] Coordinate type flag
2567 * window [I] Address of new window rectangle
2572 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2574 SMALL_RECT p = *window;
2577 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2581 CONSOLE_SCREEN_BUFFER_INFO csbi;
2583 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2585 p.Left += csbi.srWindow.Left;
2586 p.Top += csbi.srWindow.Top;
2587 p.Right += csbi.srWindow.Right;
2588 p.Bottom += csbi.srWindow.Bottom;
2590 SERVER_START_REQ(set_console_output_info)
2592 req->handle = console_handle_unmap(hCon);
2593 req->win_left = p.Left;
2594 req->win_top = p.Top;
2595 req->win_right = p.Right;
2596 req->win_bottom = p.Bottom;
2597 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2598 ret = !wine_server_call_err( req );
2606 /******************************************************************************
2607 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2609 * Sets the foreground and background color attributes of characters
2610 * written to the screen buffer.
2616 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2620 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2621 SERVER_START_REQ(set_console_output_info)
2623 req->handle = console_handle_unmap(hConsoleOutput);
2625 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2626 ret = !wine_server_call_err( req );
2633 /******************************************************************************
2634 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2637 * hConsoleOutput [I] Handle to console screen buffer
2638 * dwSize [I] New size in character rows and cols
2644 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2648 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2649 SERVER_START_REQ(set_console_output_info)
2651 req->handle = console_handle_unmap(hConsoleOutput);
2652 req->width = dwSize.X;
2653 req->height = dwSize.Y;
2654 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2655 ret = !wine_server_call_err( req );
2662 /******************************************************************************
2663 * ScrollConsoleScreenBufferA [KERNEL32.@]
2666 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2667 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2672 ciw.Attributes = lpFill->Attributes;
2673 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2675 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2676 dwDestOrigin, &ciw);
2679 /******************************************************************
2680 * CONSOLE_FillLineUniform
2682 * Helper function for ScrollConsoleScreenBufferW
2683 * Fills a part of a line with a constant character info
2685 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2687 SERVER_START_REQ( fill_console_output )
2689 req->handle = console_handle_unmap(hConsoleOutput);
2690 req->mode = CHAR_INFO_MODE_TEXTATTR;
2695 req->data.ch = lpFill->Char.UnicodeChar;
2696 req->data.attr = lpFill->Attributes;
2697 wine_server_call_err( req );
2702 /******************************************************************************
2703 * ScrollConsoleScreenBufferW [KERNEL32.@]
2707 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2708 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2716 CONSOLE_SCREEN_BUFFER_INFO csbi;
2721 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2722 lpScrollRect->Left, lpScrollRect->Top,
2723 lpScrollRect->Right, lpScrollRect->Bottom,
2724 lpClipRect->Left, lpClipRect->Top,
2725 lpClipRect->Right, lpClipRect->Bottom,
2726 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2728 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2729 lpScrollRect->Left, lpScrollRect->Top,
2730 lpScrollRect->Right, lpScrollRect->Bottom,
2731 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2733 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2736 src.X = lpScrollRect->Left;
2737 src.Y = lpScrollRect->Top;
2739 /* step 1: get dst rect */
2740 dst.Left = dwDestOrigin.X;
2741 dst.Top = dwDestOrigin.Y;
2742 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2743 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2745 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2748 clip.Left = max(0, lpClipRect->Left);
2749 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2750 clip.Top = max(0, lpClipRect->Top);
2751 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2756 clip.Right = csbi.dwSize.X - 1;
2758 clip.Bottom = csbi.dwSize.Y - 1;
2760 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2762 /* step 2b: clip dst rect */
2763 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2764 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2765 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2766 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2768 /* step 3: transfer the bits */
2769 SERVER_START_REQ(move_console_output)
2771 req->handle = console_handle_unmap(hConsoleOutput);
2774 req->x_dst = dst.Left;
2775 req->y_dst = dst.Top;
2776 req->w = dst.Right - dst.Left + 1;
2777 req->h = dst.Bottom - dst.Top + 1;
2778 ret = !wine_server_call_err( req );
2782 if (!ret) return FALSE;
2784 /* step 4: clean out the exposed part */
2786 /* have to write cell [i,j] if it is not in dst rect (because it has already
2787 * been written to by the scroll) and is in clip (we shall not write
2790 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2792 inside = dst.Top <= j && j <= dst.Bottom;
2794 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2796 if (inside && dst.Left <= i && i <= dst.Right)
2800 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2806 if (start == -1) start = i;
2810 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2816 /******************************************************************
2817 * AttachConsole (KERNEL32.@)
2819 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2821 FIXME("stub %x\n",dwProcessId);
2825 /******************************************************************
2826 * GetConsoleDisplayMode (KERNEL32.@)
2828 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2830 TRACE("semi-stub: %p\n", lpModeFlags);
2831 /* It is safe to successfully report windowed mode */
2836 /******************************************************************
2837 * SetConsoleDisplayMode (KERNEL32.@)
2839 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2840 COORD *lpNewScreenBufferDimensions)
2842 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2843 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2846 /* We cannot switch to fullscreen */
2853 /* ====================================================================
2855 * Console manipulation functions
2857 * ====================================================================*/
2859 /* some missing functions...
2860 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2861 * should get the right API and implement them
2862 * GetConsoleCommandHistory[AW] (dword dword dword)
2863 * GetConsoleCommandHistoryLength[AW]
2864 * SetConsoleCommandHistoryMode
2865 * SetConsoleNumberOfCommands[AW]
2867 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2871 SERVER_START_REQ( get_console_input_history )
2875 if (buf && buf_len > 1)
2877 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2879 if (!wine_server_call_err( req ))
2881 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2882 len = reply->total / sizeof(WCHAR) + 1;
2889 /******************************************************************
2890 * CONSOLE_AppendHistory
2894 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2896 size_t len = strlenW(ptr);
2899 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2900 if (!len) return FALSE;
2902 SERVER_START_REQ( append_console_input_history )
2905 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2906 ret = !wine_server_call_err( req );
2912 /******************************************************************
2913 * CONSOLE_GetNumHistoryEntries
2917 unsigned CONSOLE_GetNumHistoryEntries(void)
2920 SERVER_START_REQ(get_console_input_info)
2923 if (!wine_server_call_err( req )) ret = reply->history_index;
2929 /******************************************************************
2930 * CONSOLE_GetEditionMode
2934 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2936 unsigned ret = FALSE;
2937 SERVER_START_REQ(get_console_input_info)
2939 req->handle = console_handle_unmap(hConIn);
2940 if ((ret = !wine_server_call_err( req )))
2941 *mode = reply->edition_mode;
2947 /******************************************************************
2952 * 0 if an error occurred, non-zero for success
2955 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
2956 DWORD TargetBufferLength, LPWSTR lpExename)
2958 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
2959 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2963 /******************************************************************
2964 * GetConsoleProcessList (KERNEL32.@)
2966 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
2968 FIXME("(%p,%d): stub\n", processlist, processcount);
2970 if (!processlist || processcount < 1)
2972 SetLastError(ERROR_INVALID_PARAMETER);
2979 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
2981 memset(&S_termios, 0, sizeof(S_termios));
2982 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
2986 /* FIXME: to be done even if program is a GUI ? */
2987 /* This is wine specific: we have no parent (we're started from unix)
2988 * so, create a simple console with bare handles
2990 wine_server_send_fd(0);
2991 SERVER_START_REQ( alloc_console )
2993 req->access = GENERIC_READ | GENERIC_WRITE;
2994 req->attributes = OBJ_INHERIT;
2995 req->pid = 0xffffffff;
2997 wine_server_call( req );
2998 conin = wine_server_ptr_handle( reply->handle_in );
2999 /* reply->event shouldn't be created by server */
3003 if (!params->hStdInput)
3004 params->hStdInput = conin;
3006 if (!params->hStdOutput)
3008 wine_server_send_fd(1);
3009 SERVER_START_REQ( create_console_output )
3011 req->handle_in = wine_server_obj_handle(conin);
3012 req->access = GENERIC_WRITE|GENERIC_READ;
3013 req->attributes = OBJ_INHERIT;
3014 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3016 wine_server_call(req);
3017 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3021 if (!params->hStdError)
3023 wine_server_send_fd(2);
3024 SERVER_START_REQ( create_console_output )
3026 req->handle_in = wine_server_obj_handle(conin);
3027 req->access = GENERIC_WRITE|GENERIC_READ;
3028 req->attributes = OBJ_INHERIT;
3029 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3031 wine_server_call(req);
3032 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3038 /* convert value from server:
3039 * + 0 => INVALID_HANDLE_VALUE
3040 * + console handle needs to be mapped
3042 if (!params->hStdInput)
3043 params->hStdInput = INVALID_HANDLE_VALUE;
3044 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3046 params->hStdInput = console_handle_map(params->hStdInput);
3047 save_console_mode(params->hStdInput);
3050 if (!params->hStdOutput)
3051 params->hStdOutput = INVALID_HANDLE_VALUE;
3052 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3053 params->hStdOutput = console_handle_map(params->hStdOutput);
3055 if (!params->hStdError)
3056 params->hStdError = INVALID_HANDLE_VALUE;
3057 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3058 params->hStdError = console_handle_map(params->hStdError);
3063 BOOL CONSOLE_Exit(void)
3065 /* the console is in raw mode, put it back in cooked mode */
3066 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));