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"
47 #include "wine/winbase16.h"
48 #include "wine/server.h"
49 #include "wine/exception.h"
50 #include "wine/unicode.h"
51 #include "wine/debug.h"
53 #include "console_private.h"
54 #include "kernel_private.h"
56 WINE_DEFAULT_DEBUG_CHANNEL(console);
58 static UINT console_input_codepage;
59 static UINT console_output_codepage;
61 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
62 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
64 /* map input records to ASCII */
65 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
70 for (i = 0; i < count; i++)
72 if (buffer[i].EventType != KEY_EVENT) continue;
73 WideCharToMultiByte( GetConsoleCP(), 0,
74 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
75 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
79 /* map input records to Unicode */
80 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
85 for (i = 0; i < count; i++)
87 if (buffer[i].EventType != KEY_EVENT) continue;
88 MultiByteToWideChar( GetConsoleCP(), 0,
89 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
90 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
94 /* map char infos to ASCII */
95 static void char_info_WtoA( CHAR_INFO *buffer, int count )
101 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
102 &ch, 1, NULL, NULL );
103 buffer->Char.AsciiChar = ch;
108 /* map char infos to Unicode */
109 static void char_info_AtoW( CHAR_INFO *buffer, int count )
115 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
116 buffer->Char.UnicodeChar = ch;
122 /******************************************************************************
123 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
126 * Success: hwnd of the console window.
129 HWND WINAPI GetConsoleWindow(VOID)
136 /******************************************************************************
137 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
142 UINT WINAPI GetConsoleCP(VOID)
144 if (!console_input_codepage)
146 console_input_codepage = GetOEMCP();
147 TRACE("%u\n", console_input_codepage);
149 return console_input_codepage;
153 /******************************************************************************
154 * SetConsoleCP [KERNEL32.@]
156 BOOL WINAPI SetConsoleCP(UINT cp)
158 if (!IsValidCodePage( cp )) return FALSE;
159 console_input_codepage = cp;
164 /***********************************************************************
165 * GetConsoleOutputCP (KERNEL32.@)
167 UINT WINAPI GetConsoleOutputCP(VOID)
169 if (!console_output_codepage)
171 console_output_codepage = GetOEMCP();
172 TRACE("%u\n", console_output_codepage);
174 return console_output_codepage;
178 /******************************************************************************
179 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
182 * cp [I] code page to set
188 BOOL WINAPI SetConsoleOutputCP(UINT cp)
190 if (!IsValidCodePage( cp )) return FALSE;
191 console_output_codepage = cp;
196 /***********************************************************************
199 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
201 static const char beep = '\a';
202 /* dwFreq and dwDur are ignored by Win95 */
203 if (isatty(2)) write( 2, &beep, 1 );
208 /******************************************************************
209 * OpenConsoleW (KERNEL32.@)
212 * Open a handle to the current process console.
213 * Returns INVALID_HANDLE_VALUE on failure.
215 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
220 if (strcmpiW(coninW, name) == 0)
221 output = (HANDLE) FALSE;
222 else if (strcmpiW(conoutW, name) == 0)
223 output = (HANDLE) TRUE;
226 SetLastError(ERROR_INVALID_NAME);
227 return INVALID_HANDLE_VALUE;
229 if (creation != OPEN_EXISTING)
231 SetLastError(ERROR_INVALID_PARAMETER);
232 return INVALID_HANDLE_VALUE;
235 SERVER_START_REQ( open_console )
238 req->access = access;
239 req->attributes = inherit ? OBJ_INHERIT : 0;
240 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
242 wine_server_call_err( req );
247 ret = console_handle_map(ret);
250 /* likely, we're not attached to wineconsole
251 * let's try to return a handle to the unix-console
253 int fd = open("/dev/tty", output ? O_WRONLY : O_RDONLY);
254 ret = INVALID_HANDLE_VALUE;
257 DWORD access = (output ? GENERIC_WRITE : GENERIC_READ) | SYNCHRONIZE;
258 wine_server_fd_to_handle(fd, access, inherit ? OBJ_INHERIT : 0, &ret);
265 /******************************************************************
266 * VerifyConsoleIoHandle (KERNEL32.@)
270 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
274 if (!is_console_handle(handle)) return FALSE;
275 SERVER_START_REQ(get_console_mode)
277 req->handle = console_handle_unmap(handle);
278 ret = !wine_server_call_err( req );
284 /******************************************************************
285 * DuplicateConsoleHandle (KERNEL32.@)
289 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
294 if (!is_console_handle(handle) ||
295 !DuplicateHandle(GetCurrentProcess(), console_handle_unmap(handle),
296 GetCurrentProcess(), &ret, access, inherit, options))
297 return INVALID_HANDLE_VALUE;
298 return console_handle_map(ret);
301 /******************************************************************
302 * CloseConsoleHandle (KERNEL32.@)
306 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
308 if (!is_console_handle(handle))
310 SetLastError(ERROR_INVALID_PARAMETER);
313 return CloseHandle(console_handle_unmap(handle));
316 /******************************************************************
317 * GetConsoleInputWaitHandle (KERNEL32.@)
321 HANDLE WINAPI GetConsoleInputWaitHandle(void)
323 static HANDLE console_wait_event;
325 /* FIXME: this is not thread safe */
326 if (!console_wait_event)
328 SERVER_START_REQ(get_console_wait_event)
330 if (!wine_server_call_err( req )) console_wait_event = reply->handle;
334 return console_wait_event;
338 /******************************************************************************
339 * WriteConsoleInputA [KERNEL32.@]
341 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
342 DWORD count, LPDWORD written )
347 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
348 memcpy( recW, buffer, count*sizeof(*recW) );
349 input_records_AtoW( recW, count );
350 ret = WriteConsoleInputW( handle, recW, count, written );
351 HeapFree( GetProcessHeap(), 0, recW );
356 /******************************************************************************
357 * WriteConsoleInputW [KERNEL32.@]
359 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
360 DWORD count, LPDWORD written )
364 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
366 if (written) *written = 0;
367 SERVER_START_REQ( write_console_input )
369 req->handle = console_handle_unmap(handle);
370 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
371 if ((ret = !wine_server_call_err( req )) && written)
372 *written = reply->written;
380 /***********************************************************************
381 * WriteConsoleOutputA (KERNEL32.@)
383 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
384 COORD size, COORD coord, LPSMALL_RECT region )
388 COORD new_size, new_coord;
391 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
392 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
394 if (new_size.X <= 0 || new_size.Y <= 0)
396 region->Bottom = region->Top + new_size.Y - 1;
397 region->Right = region->Left + new_size.X - 1;
401 /* only copy the useful rectangle */
402 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
404 for (y = 0; y < new_size.Y; y++)
406 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
407 new_size.X * sizeof(CHAR_INFO) );
408 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
410 new_coord.X = new_coord.Y = 0;
411 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
412 HeapFree( GetProcessHeap(), 0, ciw );
417 /***********************************************************************
418 * WriteConsoleOutputW (KERNEL32.@)
420 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
421 COORD size, COORD coord, LPSMALL_RECT region )
423 int width, height, y;
426 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
427 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
428 region->Left, region->Top, region->Right, region->Bottom);
430 width = min( region->Right - region->Left + 1, size.X - coord.X );
431 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
433 if (width > 0 && height > 0)
435 for (y = 0; y < height; y++)
437 SERVER_START_REQ( write_console_output )
439 req->handle = console_handle_unmap(hConsoleOutput);
440 req->x = region->Left;
441 req->y = region->Top + y;
442 req->mode = CHAR_INFO_MODE_TEXTATTR;
444 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
445 width * sizeof(CHAR_INFO));
446 if ((ret = !wine_server_call_err( req )))
448 width = min( width, reply->width - region->Left );
449 height = min( height, reply->height - region->Top );
456 region->Bottom = region->Top + height - 1;
457 region->Right = region->Left + width - 1;
462 /******************************************************************************
463 * WriteConsoleOutputCharacterA [KERNEL32.@]
465 * See WriteConsoleOutputCharacterW.
467 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
468 COORD coord, LPDWORD lpNumCharsWritten )
474 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
475 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
477 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
479 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
481 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
482 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
484 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
485 HeapFree( GetProcessHeap(), 0, strW );
490 /******************************************************************************
491 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
492 * the console screen buffer
495 * hConsoleOutput [I] Handle to screen buffer
496 * attr [I] Pointer to buffer with write attributes
497 * length [I] Number of cells to write to
498 * coord [I] Coords of first cell
499 * lpNumAttrsWritten [O] Pointer to number of cells written
506 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
507 COORD coord, LPDWORD lpNumAttrsWritten )
511 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
513 SERVER_START_REQ( write_console_output )
515 req->handle = console_handle_unmap(hConsoleOutput);
518 req->mode = CHAR_INFO_MODE_ATTR;
520 wine_server_add_data( req, attr, length * sizeof(WORD) );
521 if ((ret = !wine_server_call_err( req )))
523 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
531 /******************************************************************************
532 * FillConsoleOutputCharacterA [KERNEL32.@]
534 * See FillConsoleOutputCharacterW.
536 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
537 COORD coord, LPDWORD lpNumCharsWritten )
541 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
542 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
546 /******************************************************************************
547 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
550 * hConsoleOutput [I] Handle to screen buffer
551 * ch [I] Character to write
552 * length [I] Number of cells to write to
553 * coord [I] Coords of first cell
554 * lpNumCharsWritten [O] Pointer to number of cells written
560 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
561 COORD coord, LPDWORD lpNumCharsWritten)
565 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
566 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
568 SERVER_START_REQ( fill_console_output )
570 req->handle = console_handle_unmap(hConsoleOutput);
573 req->mode = CHAR_INFO_MODE_TEXT;
577 if ((ret = !wine_server_call_err( req )))
579 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
587 /******************************************************************************
588 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
591 * hConsoleOutput [I] Handle to screen buffer
592 * attr [I] Color attribute to write
593 * length [I] Number of cells to write to
594 * coord [I] Coords of first cell
595 * lpNumAttrsWritten [O] Pointer to number of cells written
601 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
602 COORD coord, LPDWORD lpNumAttrsWritten )
606 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
607 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
609 SERVER_START_REQ( fill_console_output )
611 req->handle = console_handle_unmap(hConsoleOutput);
614 req->mode = CHAR_INFO_MODE_ATTR;
616 req->data.attr = attr;
618 if ((ret = !wine_server_call_err( req )))
620 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
628 /******************************************************************************
629 * ReadConsoleOutputCharacterA [KERNEL32.@]
632 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
633 COORD coord, LPDWORD read_count)
637 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
639 if (read_count) *read_count = 0;
640 if (!wptr) return FALSE;
642 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
644 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
645 if (read_count) *read_count = read;
647 HeapFree( GetProcessHeap(), 0, wptr );
652 /******************************************************************************
653 * ReadConsoleOutputCharacterW [KERNEL32.@]
656 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
657 COORD coord, LPDWORD read_count )
661 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
663 SERVER_START_REQ( read_console_output )
665 req->handle = console_handle_unmap(hConsoleOutput);
668 req->mode = CHAR_INFO_MODE_TEXT;
670 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
671 if ((ret = !wine_server_call_err( req )))
673 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
681 /******************************************************************************
682 * ReadConsoleOutputAttribute [KERNEL32.@]
684 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
685 COORD coord, LPDWORD read_count)
689 TRACE("(%p,%p,%d,%dx%d,%p)\n",
690 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
692 SERVER_START_REQ( read_console_output )
694 req->handle = console_handle_unmap(hConsoleOutput);
697 req->mode = CHAR_INFO_MODE_ATTR;
699 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
700 if ((ret = !wine_server_call_err( req )))
702 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
710 /******************************************************************************
711 * ReadConsoleOutputA [KERNEL32.@]
714 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
715 COORD coord, LPSMALL_RECT region )
720 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
721 if (ret && region->Right >= region->Left)
723 for (y = 0; y <= region->Bottom - region->Top; y++)
725 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
726 region->Right - region->Left + 1 );
733 /******************************************************************************
734 * ReadConsoleOutputW [KERNEL32.@]
736 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
737 * think we need to be *that* compatible. -- AJ
739 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
740 COORD coord, LPSMALL_RECT region )
742 int width, height, y;
745 width = min( region->Right - region->Left + 1, size.X - coord.X );
746 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
748 if (width > 0 && height > 0)
750 for (y = 0; y < height; y++)
752 SERVER_START_REQ( read_console_output )
754 req->handle = console_handle_unmap(hConsoleOutput);
755 req->x = region->Left;
756 req->y = region->Top + y;
757 req->mode = CHAR_INFO_MODE_TEXTATTR;
759 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
760 width * sizeof(CHAR_INFO) );
761 if ((ret = !wine_server_call_err( req )))
763 width = min( width, reply->width - region->Left );
764 height = min( height, reply->height - region->Top );
771 region->Bottom = region->Top + height - 1;
772 region->Right = region->Left + width - 1;
777 /******************************************************************************
778 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
781 * handle [I] Handle to console input buffer
782 * buffer [O] Address of buffer for read data
783 * count [I] Number of records to read
784 * pRead [O] Address of number of records read
790 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
794 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
795 input_records_WtoA( buffer, read );
796 if (pRead) *pRead = read;
801 /***********************************************************************
802 * PeekConsoleInputA (KERNEL32.@)
804 * Gets 'count' first events (or less) from input queue.
806 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
810 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
811 input_records_WtoA( buffer, read );
812 if (pRead) *pRead = read;
817 /***********************************************************************
818 * PeekConsoleInputW (KERNEL32.@)
820 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
823 SERVER_START_REQ( read_console_input )
825 req->handle = console_handle_unmap(handle);
827 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
828 if ((ret = !wine_server_call_err( req )))
830 if (read) *read = count ? reply->read : 0;
838 /***********************************************************************
839 * GetNumberOfConsoleInputEvents (KERNEL32.@)
841 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
844 SERVER_START_REQ( read_console_input )
846 req->handle = console_handle_unmap(handle);
848 if ((ret = !wine_server_call_err( req )))
850 if (nrofevents) *nrofevents = reply->read;
858 /******************************************************************************
861 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
864 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
866 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
867 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
869 enum read_console_input_return ret;
871 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
873 SERVER_START_REQ( read_console_input )
875 req->handle = console_handle_unmap(handle);
877 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
878 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
879 else ret = rci_gotone;
887 /***********************************************************************
888 * FlushConsoleInputBuffer (KERNEL32.@)
890 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
892 enum read_console_input_return last;
895 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
897 return last == rci_timeout;
901 /***********************************************************************
902 * SetConsoleTitleA (KERNEL32.@)
904 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
909 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
910 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
911 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
912 ret = SetConsoleTitleW(titleW);
913 HeapFree(GetProcessHeap(), 0, titleW);
918 /***********************************************************************
919 * GetConsoleTitleA (KERNEL32.@)
921 * See GetConsoleTitleW.
923 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
925 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
929 ret = GetConsoleTitleW( ptr, size );
932 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
935 HeapFree(GetProcessHeap(), 0, ptr);
940 /******************************************************************************
941 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
944 * title [O] Address of buffer for title
945 * size [I] Size of buffer
948 * Success: Length of string copied
951 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
955 SERVER_START_REQ( get_console_input_info )
958 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
959 if (!wine_server_call_err( req ))
961 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
970 /***********************************************************************
971 * GetLargestConsoleWindowSize (KERNEL32.@)
974 * This should return a COORD, but calling convention for returning
975 * structures is different between Windows and gcc on i386.
980 #undef GetLargestConsoleWindowSize
981 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
989 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
992 #endif /* defined(__i386__) */
995 /***********************************************************************
996 * GetLargestConsoleWindowSize (KERNEL32.@)
999 * This should return a COORD, but calling convention for returning
1000 * structures is different between Windows and gcc on i386.
1005 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1010 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1013 #endif /* defined(__i386__) */
1015 static WCHAR* S_EditString /* = NULL */;
1016 static unsigned S_EditStrPos /* = 0 */;
1018 /***********************************************************************
1019 * FreeConsole (KERNEL32.@)
1021 BOOL WINAPI FreeConsole(VOID)
1025 SERVER_START_REQ(free_console)
1027 ret = !wine_server_call_err( req );
1033 /******************************************************************
1034 * start_console_renderer
1036 * helper for AllocConsole
1037 * starts the renderer process
1039 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1044 PROCESS_INFORMATION pi;
1046 /* FIXME: use dynamic allocation for most of the buffers below */
1047 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1048 if ((ret > -1) && (ret < sizeof(buffer)) &&
1049 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1050 NULL, NULL, si, &pi))
1052 if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
1054 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1055 pi.dwProcessId, pi.dwThreadId);
1062 static BOOL start_console_renderer(STARTUPINFOA* si)
1066 OBJECT_ATTRIBUTES attr;
1069 attr.Length = sizeof(attr);
1070 attr.RootDirectory = 0;
1071 attr.Attributes = OBJ_INHERIT;
1072 attr.ObjectName = NULL;
1073 attr.SecurityDescriptor = NULL;
1074 attr.SecurityQualityOfService = NULL;
1076 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
1077 if (!hEvent) return FALSE;
1079 /* first try environment variable */
1080 if ((p = getenv("WINECONSOLE")) != NULL)
1082 ret = start_console_renderer_helper(p, si, hEvent);
1084 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1085 "trying default access\n", p);
1088 /* then try the regular PATH */
1090 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1092 CloseHandle(hEvent);
1096 /***********************************************************************
1097 * AllocConsole (KERNEL32.@)
1099 * creates an xterm with a pty to our program
1101 BOOL WINAPI AllocConsole(void)
1103 HANDLE handle_in = INVALID_HANDLE_VALUE;
1104 HANDLE handle_out = INVALID_HANDLE_VALUE;
1105 HANDLE handle_err = INVALID_HANDLE_VALUE;
1106 STARTUPINFOA siCurrent;
1107 STARTUPINFOA siConsole;
1112 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1113 FALSE, OPEN_EXISTING );
1115 if (VerifyConsoleIoHandle(handle_in))
1117 /* we already have a console opened on this process, don't create a new one */
1118 CloseHandle(handle_in);
1121 /* happens when we're running on a Unix console */
1122 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1124 GetStartupInfoA(&siCurrent);
1126 memset(&siConsole, 0, sizeof(siConsole));
1127 siConsole.cb = sizeof(siConsole);
1128 /* setup a view arguments for wineconsole (it'll use them as default values) */
1129 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1131 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1132 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1133 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1135 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1137 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1138 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1140 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1142 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1143 siConsole.wShowWindow = siCurrent.wShowWindow;
1145 /* FIXME (should pass the unicode form) */
1146 if (siCurrent.lpTitle)
1147 siConsole.lpTitle = siCurrent.lpTitle;
1148 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1150 buffer[sizeof(buffer) - 1] = '\0';
1151 siConsole.lpTitle = buffer;
1154 if (!start_console_renderer(&siConsole))
1157 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1158 /* all std I/O handles are inheritable by default */
1159 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1160 TRUE, OPEN_EXISTING );
1161 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1163 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1164 TRUE, OPEN_EXISTING );
1165 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1167 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1168 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1171 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1172 handle_in = siCurrent.hStdInput;
1173 handle_out = siCurrent.hStdOutput;
1174 handle_err = siCurrent.hStdError;
1177 /* NT resets the STD_*_HANDLEs on console alloc */
1178 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1179 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1180 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1182 SetLastError(ERROR_SUCCESS);
1187 ERR("Can't allocate console\n");
1188 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1189 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1190 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1196 /***********************************************************************
1197 * ReadConsoleA (KERNEL32.@)
1199 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1200 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1202 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1206 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1207 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1209 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1210 HeapFree(GetProcessHeap(), 0, ptr);
1215 /***********************************************************************
1216 * ReadConsoleW (KERNEL32.@)
1218 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1219 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1222 LPWSTR xbuf = (LPWSTR)lpBuffer;
1225 TRACE("(%p,%p,%d,%p,%p)\n",
1226 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1228 if (!GetConsoleMode(hConsoleInput, &mode))
1231 if (mode & ENABLE_LINE_INPUT)
1233 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1235 HeapFree(GetProcessHeap(), 0, S_EditString);
1236 if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1240 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1241 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1242 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1243 S_EditStrPos += charsread;
1248 DWORD timeout = INFINITE;
1250 /* FIXME: should we read at least 1 char? The SDK does not say */
1251 /* wait for at least one available input record (it doesn't mean we'll have
1252 * chars stored in xbuf...)
1257 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1259 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1260 ir.Event.KeyEvent.uChar.UnicodeChar &&
1261 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
1263 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1265 } while (charsread < nNumberOfCharsToRead);
1266 /* nothing has been read */
1267 if (timeout == INFINITE) return FALSE;
1270 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1276 /***********************************************************************
1277 * ReadConsoleInputW (KERNEL32.@)
1279 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1280 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1283 DWORD timeout = INFINITE;
1287 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1291 /* loop until we get at least one event */
1292 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1296 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1301 /******************************************************************************
1302 * WriteConsoleOutputCharacterW [KERNEL32.@]
1304 * Copy character to consecutive cells in the console screen buffer.
1307 * hConsoleOutput [I] Handle to screen buffer
1308 * str [I] Pointer to buffer with chars to write
1309 * length [I] Number of cells to write to
1310 * coord [I] Coords of first cell
1311 * lpNumCharsWritten [O] Pointer to number of cells written
1318 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1319 COORD coord, LPDWORD lpNumCharsWritten )
1323 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1324 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1326 SERVER_START_REQ( write_console_output )
1328 req->handle = console_handle_unmap(hConsoleOutput);
1331 req->mode = CHAR_INFO_MODE_TEXT;
1333 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1334 if ((ret = !wine_server_call_err( req )))
1336 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1344 /******************************************************************************
1345 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1348 * title [I] Address of new title
1354 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1358 TRACE("(%s)\n", debugstr_w(title));
1359 SERVER_START_REQ( set_console_input_info )
1362 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1363 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1364 ret = !wine_server_call_err( req );
1371 /***********************************************************************
1372 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1374 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1376 FIXME("(%p): stub\n", nrofbuttons);
1381 /******************************************************************************
1382 * SetConsoleInputExeNameW [KERNEL32.@]
1387 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1389 FIXME("(%s): stub!\n", debugstr_w(name));
1391 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1395 /******************************************************************************
1396 * SetConsoleInputExeNameA [KERNEL32.@]
1401 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1403 int len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1404 LPWSTR xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1407 if (!xptr) return FALSE;
1409 MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
1410 ret = SetConsoleInputExeNameW(xptr);
1411 HeapFree(GetProcessHeap(), 0, xptr);
1416 /******************************************************************
1417 * CONSOLE_DefaultHandler
1419 * Final control event handler
1421 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1423 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1425 /* should never go here */
1429 /******************************************************************************
1430 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1433 * func [I] Address of handler function
1434 * add [I] Handler to add or remove
1441 struct ConsoleHandler
1443 PHANDLER_ROUTINE handler;
1444 struct ConsoleHandler* next;
1447 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1448 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1450 static CRITICAL_SECTION CONSOLE_CritSect;
1451 static CRITICAL_SECTION_DEBUG critsect_debug =
1453 0, 0, &CONSOLE_CritSect,
1454 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
1455 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
1457 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
1459 /*****************************************************************************/
1461 /******************************************************************
1462 * SetConsoleCtrlHandler (KERNEL32.@)
1464 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1468 TRACE("(%p,%i)\n", func, add);
1472 RtlEnterCriticalSection(&CONSOLE_CritSect);
1474 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1476 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1477 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1481 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1483 if (!ch) return FALSE;
1485 RtlEnterCriticalSection(&CONSOLE_CritSect);
1486 ch->next = CONSOLE_Handlers;
1487 CONSOLE_Handlers = ch;
1488 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1492 struct ConsoleHandler** ch;
1493 RtlEnterCriticalSection(&CONSOLE_CritSect);
1494 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1496 if ((*ch)->handler == func) break;
1500 struct ConsoleHandler* rch = *ch;
1503 if (rch == &CONSOLE_DefaultConsoleHandler)
1505 ERR("Who's trying to remove default handler???\n");
1506 SetLastError(ERROR_INVALID_PARAMETER);
1512 HeapFree(GetProcessHeap(), 0, rch);
1517 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1518 SetLastError(ERROR_INVALID_PARAMETER);
1521 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1526 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
1528 TRACE("(%x)\n", GetExceptionCode());
1529 return EXCEPTION_EXECUTE_HANDLER;
1532 /******************************************************************
1533 * CONSOLE_SendEventThread
1535 * Internal helper to pass an event to the list on installed handlers
1537 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1539 DWORD_PTR event = (DWORD_PTR)pmt;
1540 struct ConsoleHandler* ch;
1542 if (event == CTRL_C_EVENT)
1544 BOOL caught_by_dbg = TRUE;
1545 /* First, try to pass the ctrl-C event to the debugger (if any)
1546 * If it continues, there's nothing more to do
1547 * Otherwise, we need to send the ctrl-C event to the handlers
1551 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1553 __EXCEPT(CONSOLE_CtrlEventHandler)
1555 caught_by_dbg = FALSE;
1558 if (caught_by_dbg) return 0;
1559 /* the debugger didn't continue... so, pass to ctrl handlers */
1561 RtlEnterCriticalSection(&CONSOLE_CritSect);
1562 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1564 if (ch->handler(event)) break;
1566 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1570 /******************************************************************
1571 * CONSOLE_HandleCtrlC
1573 * Check whether the shall manipulate CtrlC events
1575 int CONSOLE_HandleCtrlC(unsigned sig)
1577 /* FIXME: better test whether a console is attached to this process ??? */
1578 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1579 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1581 /* check if we have to ignore ctrl-C events */
1582 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1584 /* Create a separate thread to signal all the events.
1585 * This is needed because:
1586 * - this function can be called in an Unix signal handler (hence on an
1587 * different stack than the thread that's running). This breaks the
1588 * Win32 exception mechanisms (where the thread's stack is checked).
1589 * - since the current thread, while processing the signal, can hold the
1590 * console critical section, we need another execution environment where
1591 * we can wait on this critical section
1593 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1598 /******************************************************************************
1599 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1602 * dwCtrlEvent [I] Type of event
1603 * dwProcessGroupID [I] Process group ID to send event to
1607 * Failure: False (and *should* [but doesn't] set LastError)
1609 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1610 DWORD dwProcessGroupID)
1614 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
1616 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1618 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
1622 SERVER_START_REQ( send_console_signal )
1624 req->signal = dwCtrlEvent;
1625 req->group_id = dwProcessGroupID;
1626 ret = !wine_server_call_err( req );
1630 /* FIXME: shall this function be synchronous, ie only return when all events
1631 * have been handled by all processes in the given group ?
1632 * As of today, we don't wait...
1638 /******************************************************************************
1639 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
1642 * dwDesiredAccess [I] Access flag
1643 * dwShareMode [I] Buffer share mode
1644 * sa [I] Security attributes
1645 * dwFlags [I] Type of buffer to create
1646 * lpScreenBufferData [I] Reserved
1649 * Should call SetLastError
1652 * Success: Handle to new console screen buffer
1653 * Failure: INVALID_HANDLE_VALUE
1655 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1656 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1657 LPVOID lpScreenBufferData)
1659 HANDLE ret = INVALID_HANDLE_VALUE;
1661 TRACE("(%d,%d,%p,%d,%p)\n",
1662 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1664 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1666 SetLastError(ERROR_INVALID_PARAMETER);
1667 return INVALID_HANDLE_VALUE;
1670 SERVER_START_REQ(create_console_output)
1673 req->access = dwDesiredAccess;
1674 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
1675 req->share = dwShareMode;
1676 if (!wine_server_call_err( req )) ret = reply->handle_out;
1684 /***********************************************************************
1685 * GetConsoleScreenBufferInfo (KERNEL32.@)
1687 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1691 SERVER_START_REQ(get_console_output_info)
1693 req->handle = console_handle_unmap(hConsoleOutput);
1694 if ((ret = !wine_server_call_err( req )))
1696 csbi->dwSize.X = reply->width;
1697 csbi->dwSize.Y = reply->height;
1698 csbi->dwCursorPosition.X = reply->cursor_x;
1699 csbi->dwCursorPosition.Y = reply->cursor_y;
1700 csbi->wAttributes = reply->attr;
1701 csbi->srWindow.Left = reply->win_left;
1702 csbi->srWindow.Right = reply->win_right;
1703 csbi->srWindow.Top = reply->win_top;
1704 csbi->srWindow.Bottom = reply->win_bottom;
1705 csbi->dwMaximumWindowSize.X = reply->max_width;
1706 csbi->dwMaximumWindowSize.Y = reply->max_height;
1711 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
1712 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1713 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1715 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1716 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1722 /******************************************************************************
1723 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
1729 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1733 TRACE("(%p)\n", hConsoleOutput);
1735 SERVER_START_REQ( set_console_input_info )
1738 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1739 req->active_sb = hConsoleOutput;
1740 ret = !wine_server_call_err( req );
1747 /***********************************************************************
1748 * GetConsoleMode (KERNEL32.@)
1750 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1754 SERVER_START_REQ(get_console_mode)
1756 req->handle = console_handle_unmap(hcon);
1757 ret = !wine_server_call_err( req );
1758 if (ret && mode) *mode = reply->mode;
1765 /******************************************************************************
1766 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
1769 * hcon [I] Handle to console input or screen buffer
1770 * mode [I] Input or output mode to set
1777 * ENABLE_PROCESSED_INPUT 0x01
1778 * ENABLE_LINE_INPUT 0x02
1779 * ENABLE_ECHO_INPUT 0x04
1780 * ENABLE_WINDOW_INPUT 0x08
1781 * ENABLE_MOUSE_INPUT 0x10
1783 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1787 SERVER_START_REQ(set_console_mode)
1789 req->handle = console_handle_unmap(hcon);
1791 ret = !wine_server_call_err( req );
1794 /* FIXME: when resetting a console input to editline mode, I think we should
1795 * empty the S_EditString buffer
1798 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
1804 /******************************************************************
1805 * CONSOLE_WriteChars
1807 * WriteConsoleOutput helper: hides server call semantics
1808 * writes a string at a given pos with standard attribute
1810 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1816 SERVER_START_REQ( write_console_output )
1818 req->handle = console_handle_unmap(hCon);
1821 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1823 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1824 if (!wine_server_call_err( req )) written = reply->written;
1828 if (written > 0) pos->X += written;
1832 /******************************************************************
1835 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1838 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1844 csbi->dwCursorPosition.X = 0;
1845 csbi->dwCursorPosition.Y++;
1847 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1850 src.Bottom = csbi->dwSize.Y - 1;
1852 src.Right = csbi->dwSize.X - 1;
1857 ci.Attributes = csbi->wAttributes;
1858 ci.Char.UnicodeChar = ' ';
1860 csbi->dwCursorPosition.Y--;
1861 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1866 /******************************************************************
1869 * WriteConsoleOutput helper: writes a block of non special characters
1870 * Block can spread on several lines, and wrapping, if needed, is
1874 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1875 DWORD mode, LPCWSTR ptr, int len)
1877 int blk; /* number of chars to write on current line */
1878 int done; /* number of chars already written */
1880 if (len <= 0) return 1;
1882 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1884 for (done = 0; done < len; done += blk)
1886 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1888 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1890 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
1896 int pos = csbi->dwCursorPosition.X;
1897 /* FIXME: we could reduce the number of loops
1898 * but, in most cases we wouldn't gain lots of time (it would only
1899 * happen if we're asked to overwrite more than twice the part of the line,
1902 for (blk = done = 0; done < len; done += blk)
1904 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1906 csbi->dwCursorPosition.X = pos;
1907 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1915 /***********************************************************************
1916 * WriteConsoleW (KERNEL32.@)
1918 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1919 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1923 const WCHAR* psz = lpBuffer;
1924 CONSOLE_SCREEN_BUFFER_INFO csbi;
1927 TRACE("%p %s %d %p %p\n",
1928 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
1929 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
1931 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1933 if (!GetConsoleMode(hConsoleOutput, &mode) ||
1934 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1937 if (mode & ENABLE_PROCESSED_OUTPUT)
1941 for (i = 0; i < nNumberOfCharsToWrite; i++)
1945 case '\b': case '\t': case '\n': case '\a': case '\r':
1946 /* don't handle here the i-th char... done below */
1947 if ((k = i - first) > 0)
1949 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1959 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
1963 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
1965 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
1966 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
1971 next_line(hConsoleOutput, &csbi);
1977 csbi.dwCursorPosition.X = 0;
1985 /* write the remaining block (if any) if processed output is enabled, or the
1986 * entire buffer otherwise
1988 if ((k = nNumberOfCharsToWrite - first) > 0)
1990 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1996 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
1997 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2002 /***********************************************************************
2003 * WriteConsoleA (KERNEL32.@)
2005 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2006 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2012 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2014 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2015 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2016 if (!xstring) return 0;
2018 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2020 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2022 HeapFree(GetProcessHeap(), 0, xstring);
2027 /******************************************************************************
2028 * SetConsoleCursorPosition [KERNEL32.@]
2029 * Sets the cursor position in console
2032 * hConsoleOutput [I] Handle of console screen buffer
2033 * dwCursorPosition [I] New cursor position coordinates
2039 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2042 CONSOLE_SCREEN_BUFFER_INFO csbi;
2046 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2048 SERVER_START_REQ(set_console_output_info)
2050 req->handle = console_handle_unmap(hcon);
2051 req->cursor_x = pos.X;
2052 req->cursor_y = pos.Y;
2053 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2054 ret = !wine_server_call_err( req );
2058 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2061 /* if cursor is no longer visible, scroll the visible window... */
2062 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2063 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2064 if (pos.X < csbi.srWindow.Left)
2066 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2069 else if (pos.X > csbi.srWindow.Right)
2071 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2074 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2076 if (pos.Y < csbi.srWindow.Top)
2078 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2081 else if (pos.Y > csbi.srWindow.Bottom)
2083 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2086 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2088 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2093 /******************************************************************************
2094 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2097 * hcon [I] Handle to console screen buffer
2098 * cinfo [O] Address of cursor information
2104 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2108 SERVER_START_REQ(get_console_output_info)
2110 req->handle = console_handle_unmap(hCon);
2111 ret = !wine_server_call_err( req );
2114 cinfo->dwSize = reply->cursor_size;
2115 cinfo->bVisible = reply->cursor_visible;
2120 TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2125 /******************************************************************************
2126 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2129 * hcon [I] Handle to console screen buffer
2130 * cinfo [I] Address of cursor information
2135 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2139 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2140 SERVER_START_REQ(set_console_output_info)
2142 req->handle = console_handle_unmap(hCon);
2143 req->cursor_size = cinfo->dwSize;
2144 req->cursor_visible = cinfo->bVisible;
2145 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2146 ret = !wine_server_call_err( req );
2153 /******************************************************************************
2154 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2157 * hcon [I] Handle to console screen buffer
2158 * bAbsolute [I] Coordinate type flag
2159 * window [I] Address of new window rectangle
2164 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2166 SMALL_RECT p = *window;
2169 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2173 CONSOLE_SCREEN_BUFFER_INFO csbi;
2175 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2177 p.Left += csbi.srWindow.Left;
2178 p.Top += csbi.srWindow.Top;
2179 p.Right += csbi.srWindow.Right;
2180 p.Bottom += csbi.srWindow.Bottom;
2182 SERVER_START_REQ(set_console_output_info)
2184 req->handle = console_handle_unmap(hCon);
2185 req->win_left = p.Left;
2186 req->win_top = p.Top;
2187 req->win_right = p.Right;
2188 req->win_bottom = p.Bottom;
2189 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2190 ret = !wine_server_call_err( req );
2198 /******************************************************************************
2199 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2201 * Sets the foreground and background color attributes of characters
2202 * written to the screen buffer.
2208 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2212 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2213 SERVER_START_REQ(set_console_output_info)
2215 req->handle = console_handle_unmap(hConsoleOutput);
2217 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2218 ret = !wine_server_call_err( req );
2225 /******************************************************************************
2226 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2229 * hConsoleOutput [I] Handle to console screen buffer
2230 * dwSize [I] New size in character rows and cols
2236 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2240 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2241 SERVER_START_REQ(set_console_output_info)
2243 req->handle = console_handle_unmap(hConsoleOutput);
2244 req->width = dwSize.X;
2245 req->height = dwSize.Y;
2246 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2247 ret = !wine_server_call_err( req );
2254 /******************************************************************************
2255 * ScrollConsoleScreenBufferA [KERNEL32.@]
2258 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2259 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2264 ciw.Attributes = lpFill->Attributes;
2265 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2267 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2268 dwDestOrigin, &ciw);
2271 /******************************************************************
2272 * CONSOLE_FillLineUniform
2274 * Helper function for ScrollConsoleScreenBufferW
2275 * Fills a part of a line with a constant character info
2277 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2279 SERVER_START_REQ( fill_console_output )
2281 req->handle = console_handle_unmap(hConsoleOutput);
2282 req->mode = CHAR_INFO_MODE_TEXTATTR;
2287 req->data.ch = lpFill->Char.UnicodeChar;
2288 req->data.attr = lpFill->Attributes;
2289 wine_server_call_err( req );
2294 /******************************************************************************
2295 * ScrollConsoleScreenBufferW [KERNEL32.@]
2299 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2300 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2308 CONSOLE_SCREEN_BUFFER_INFO csbi;
2313 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2314 lpScrollRect->Left, lpScrollRect->Top,
2315 lpScrollRect->Right, lpScrollRect->Bottom,
2316 lpClipRect->Left, lpClipRect->Top,
2317 lpClipRect->Right, lpClipRect->Bottom,
2318 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2320 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2321 lpScrollRect->Left, lpScrollRect->Top,
2322 lpScrollRect->Right, lpScrollRect->Bottom,
2323 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2325 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2328 src.X = lpScrollRect->Left;
2329 src.Y = lpScrollRect->Top;
2331 /* step 1: get dst rect */
2332 dst.Left = dwDestOrigin.X;
2333 dst.Top = dwDestOrigin.Y;
2334 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2335 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2337 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2340 clip.Left = max(0, lpClipRect->Left);
2341 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2342 clip.Top = max(0, lpClipRect->Top);
2343 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2348 clip.Right = csbi.dwSize.X - 1;
2350 clip.Bottom = csbi.dwSize.Y - 1;
2352 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2354 /* step 2b: clip dst rect */
2355 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2356 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2357 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2358 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2360 /* step 3: transfer the bits */
2361 SERVER_START_REQ(move_console_output)
2363 req->handle = console_handle_unmap(hConsoleOutput);
2366 req->x_dst = dst.Left;
2367 req->y_dst = dst.Top;
2368 req->w = dst.Right - dst.Left + 1;
2369 req->h = dst.Bottom - dst.Top + 1;
2370 ret = !wine_server_call_err( req );
2374 if (!ret) return FALSE;
2376 /* step 4: clean out the exposed part */
2378 /* have to write cell [i,j] if it is not in dst rect (because it has already
2379 * been written to by the scroll) and is in clip (we shall not write
2382 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2384 inside = dst.Top <= j && j <= dst.Bottom;
2386 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2388 if (inside && dst.Left <= i && i <= dst.Right)
2392 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2398 if (start == -1) start = i;
2402 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2409 /* ====================================================================
2411 * Console manipulation functions
2413 * ====================================================================*/
2415 /* some missing functions...
2416 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2417 * should get the right API and implement them
2418 * GetConsoleCommandHistory[AW] (dword dword dword)
2419 * GetConsoleCommandHistoryLength[AW]
2420 * SetConsoleCommandHistoryMode
2421 * SetConsoleNumberOfCommands[AW]
2423 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2427 SERVER_START_REQ( get_console_input_history )
2431 if (buf && buf_len > 1)
2433 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2435 if (!wine_server_call_err( req ))
2437 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2438 len = reply->total / sizeof(WCHAR) + 1;
2445 /******************************************************************
2446 * CONSOLE_AppendHistory
2450 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2452 size_t len = strlenW(ptr);
2455 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2457 SERVER_START_REQ( append_console_input_history )
2460 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2461 ret = !wine_server_call_err( req );
2467 /******************************************************************
2468 * CONSOLE_GetNumHistoryEntries
2472 unsigned CONSOLE_GetNumHistoryEntries(void)
2475 SERVER_START_REQ(get_console_input_info)
2478 if (!wine_server_call_err( req )) ret = reply->history_index;
2484 /******************************************************************
2485 * CONSOLE_GetEditionMode
2489 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2491 unsigned ret = FALSE;
2492 SERVER_START_REQ(get_console_input_info)
2494 req->handle = console_handle_unmap(hConIn);
2495 if ((ret = !wine_server_call_err( req )))
2496 *mode = reply->edition_mode;