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 const WCHAR coninW[] = {'C','O','N','I','N','$',0};
59 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
61 /* map input records to ASCII */
62 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
67 for (i = 0; i < count; i++)
69 if (buffer[i].EventType != KEY_EVENT) continue;
70 WideCharToMultiByte( GetConsoleCP(), 0,
71 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
72 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
76 /* map input records to Unicode */
77 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
82 for (i = 0; i < count; i++)
84 if (buffer[i].EventType != KEY_EVENT) continue;
85 MultiByteToWideChar( GetConsoleCP(), 0,
86 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
87 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
91 /* map char infos to ASCII */
92 static void char_info_WtoA( CHAR_INFO *buffer, int count )
98 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
100 buffer->Char.AsciiChar = ch;
105 /* map char infos to Unicode */
106 static void char_info_AtoW( CHAR_INFO *buffer, int count )
112 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
113 buffer->Char.UnicodeChar = ch;
119 /******************************************************************************
120 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
123 * Success: hwnd of the console window.
126 HWND WINAPI GetConsoleWindow(VOID)
133 /******************************************************************************
134 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
139 UINT WINAPI GetConsoleCP(VOID)
142 UINT codepage = GetOEMCP(); /* default value */
144 SERVER_START_REQ(get_console_input_info)
147 ret = !wine_server_call_err(req);
148 if (ret && reply->input_cp)
149 codepage = reply->input_cp;
157 /******************************************************************************
158 * SetConsoleCP [KERNEL32.@]
160 BOOL WINAPI SetConsoleCP(UINT cp)
164 if (!IsValidCodePage(cp))
166 SetLastError(ERROR_INVALID_PARAMETER);
170 SERVER_START_REQ(set_console_input_info)
173 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
175 ret = !wine_server_call_err(req);
183 /***********************************************************************
184 * GetConsoleOutputCP (KERNEL32.@)
186 UINT WINAPI GetConsoleOutputCP(VOID)
189 UINT codepage = GetOEMCP(); /* default value */
191 SERVER_START_REQ(get_console_input_info)
194 ret = !wine_server_call_err(req);
195 if (ret && reply->output_cp)
196 codepage = reply->output_cp;
204 /******************************************************************************
205 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
208 * cp [I] code page to set
214 BOOL WINAPI SetConsoleOutputCP(UINT cp)
218 if (!IsValidCodePage(cp))
220 SetLastError(ERROR_INVALID_PARAMETER);
224 SERVER_START_REQ(set_console_input_info)
227 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
229 ret = !wine_server_call_err(req);
237 /***********************************************************************
240 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
242 static const char beep = '\a';
243 /* dwFreq and dwDur are ignored by Win95 */
244 if (isatty(2)) write( 2, &beep, 1 );
249 /******************************************************************
250 * OpenConsoleW (KERNEL32.@)
253 * Open a handle to the current process console.
254 * Returns INVALID_HANDLE_VALUE on failure.
256 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
261 if (strcmpiW(coninW, name) == 0)
262 output = (HANDLE) FALSE;
263 else if (strcmpiW(conoutW, name) == 0)
264 output = (HANDLE) TRUE;
267 SetLastError(ERROR_INVALID_NAME);
268 return INVALID_HANDLE_VALUE;
270 if (creation != OPEN_EXISTING)
272 SetLastError(ERROR_INVALID_PARAMETER);
273 return INVALID_HANDLE_VALUE;
276 SERVER_START_REQ( open_console )
279 req->access = access;
280 req->attributes = inherit ? OBJ_INHERIT : 0;
281 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
283 wine_server_call_err( req );
288 ret = console_handle_map(ret);
291 /* likely, we're not attached to wineconsole
292 * let's try to return a handle to the unix-console
294 int fd = open("/dev/tty", output ? O_WRONLY : O_RDONLY);
295 ret = INVALID_HANDLE_VALUE;
298 DWORD access = (output ? GENERIC_WRITE : GENERIC_READ) | SYNCHRONIZE;
299 wine_server_fd_to_handle(fd, access, inherit ? OBJ_INHERIT : 0, &ret);
306 /******************************************************************
307 * VerifyConsoleIoHandle (KERNEL32.@)
311 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
315 if (!is_console_handle(handle)) return FALSE;
316 SERVER_START_REQ(get_console_mode)
318 req->handle = console_handle_unmap(handle);
319 ret = !wine_server_call_err( req );
325 /******************************************************************
326 * DuplicateConsoleHandle (KERNEL32.@)
330 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
335 if (!is_console_handle(handle) ||
336 !DuplicateHandle(GetCurrentProcess(), console_handle_unmap(handle),
337 GetCurrentProcess(), &ret, access, inherit, options))
338 return INVALID_HANDLE_VALUE;
339 return console_handle_map(ret);
342 /******************************************************************
343 * CloseConsoleHandle (KERNEL32.@)
347 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
349 if (!is_console_handle(handle))
351 SetLastError(ERROR_INVALID_PARAMETER);
354 return CloseHandle(console_handle_unmap(handle));
357 /******************************************************************
358 * GetConsoleInputWaitHandle (KERNEL32.@)
362 HANDLE WINAPI GetConsoleInputWaitHandle(void)
364 static HANDLE console_wait_event;
366 /* FIXME: this is not thread safe */
367 if (!console_wait_event)
369 SERVER_START_REQ(get_console_wait_event)
371 if (!wine_server_call_err( req )) console_wait_event = reply->handle;
375 return console_wait_event;
379 /******************************************************************************
380 * WriteConsoleInputA [KERNEL32.@]
382 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
383 DWORD count, LPDWORD written )
388 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
389 memcpy( recW, buffer, count*sizeof(*recW) );
390 input_records_AtoW( recW, count );
391 ret = WriteConsoleInputW( handle, recW, count, written );
392 HeapFree( GetProcessHeap(), 0, recW );
397 /******************************************************************************
398 * WriteConsoleInputW [KERNEL32.@]
400 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
401 DWORD count, LPDWORD written )
405 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
407 if (written) *written = 0;
408 SERVER_START_REQ( write_console_input )
410 req->handle = console_handle_unmap(handle);
411 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
412 if ((ret = !wine_server_call_err( req )) && written)
413 *written = reply->written;
421 /***********************************************************************
422 * WriteConsoleOutputA (KERNEL32.@)
424 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
425 COORD size, COORD coord, LPSMALL_RECT region )
429 COORD new_size, new_coord;
432 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
433 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
435 if (new_size.X <= 0 || new_size.Y <= 0)
437 region->Bottom = region->Top + new_size.Y - 1;
438 region->Right = region->Left + new_size.X - 1;
442 /* only copy the useful rectangle */
443 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
445 for (y = 0; y < new_size.Y; y++)
447 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
448 new_size.X * sizeof(CHAR_INFO) );
449 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
451 new_coord.X = new_coord.Y = 0;
452 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
453 HeapFree( GetProcessHeap(), 0, ciw );
458 /***********************************************************************
459 * WriteConsoleOutputW (KERNEL32.@)
461 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
462 COORD size, COORD coord, LPSMALL_RECT region )
464 int width, height, y;
467 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
468 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
469 region->Left, region->Top, region->Right, region->Bottom);
471 width = min( region->Right - region->Left + 1, size.X - coord.X );
472 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
474 if (width > 0 && height > 0)
476 for (y = 0; y < height; y++)
478 SERVER_START_REQ( write_console_output )
480 req->handle = console_handle_unmap(hConsoleOutput);
481 req->x = region->Left;
482 req->y = region->Top + y;
483 req->mode = CHAR_INFO_MODE_TEXTATTR;
485 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
486 width * sizeof(CHAR_INFO));
487 if ((ret = !wine_server_call_err( req )))
489 width = min( width, reply->width - region->Left );
490 height = min( height, reply->height - region->Top );
497 region->Bottom = region->Top + height - 1;
498 region->Right = region->Left + width - 1;
503 /******************************************************************************
504 * WriteConsoleOutputCharacterA [KERNEL32.@]
506 * See WriteConsoleOutputCharacterW.
508 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
509 COORD coord, LPDWORD lpNumCharsWritten )
515 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
516 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
518 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
520 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
522 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
523 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
525 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
526 HeapFree( GetProcessHeap(), 0, strW );
531 /******************************************************************************
532 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
533 * the console screen buffer
536 * hConsoleOutput [I] Handle to screen buffer
537 * attr [I] Pointer to buffer with write attributes
538 * length [I] Number of cells to write to
539 * coord [I] Coords of first cell
540 * lpNumAttrsWritten [O] Pointer to number of cells written
547 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
548 COORD coord, LPDWORD lpNumAttrsWritten )
552 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
554 SERVER_START_REQ( write_console_output )
556 req->handle = console_handle_unmap(hConsoleOutput);
559 req->mode = CHAR_INFO_MODE_ATTR;
561 wine_server_add_data( req, attr, length * sizeof(WORD) );
562 if ((ret = !wine_server_call_err( req )))
564 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
572 /******************************************************************************
573 * FillConsoleOutputCharacterA [KERNEL32.@]
575 * See FillConsoleOutputCharacterW.
577 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
578 COORD coord, LPDWORD lpNumCharsWritten )
582 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
583 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
587 /******************************************************************************
588 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
591 * hConsoleOutput [I] Handle to screen buffer
592 * ch [I] Character to write
593 * length [I] Number of cells to write to
594 * coord [I] Coords of first cell
595 * lpNumCharsWritten [O] Pointer to number of cells written
601 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
602 COORD coord, LPDWORD lpNumCharsWritten)
606 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
607 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
609 SERVER_START_REQ( fill_console_output )
611 req->handle = console_handle_unmap(hConsoleOutput);
614 req->mode = CHAR_INFO_MODE_TEXT;
618 if ((ret = !wine_server_call_err( req )))
620 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
628 /******************************************************************************
629 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
632 * hConsoleOutput [I] Handle to screen buffer
633 * attr [I] Color attribute to write
634 * length [I] Number of cells to write to
635 * coord [I] Coords of first cell
636 * lpNumAttrsWritten [O] Pointer to number of cells written
642 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
643 COORD coord, LPDWORD lpNumAttrsWritten )
647 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
648 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
650 SERVER_START_REQ( fill_console_output )
652 req->handle = console_handle_unmap(hConsoleOutput);
655 req->mode = CHAR_INFO_MODE_ATTR;
657 req->data.attr = attr;
659 if ((ret = !wine_server_call_err( req )))
661 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
669 /******************************************************************************
670 * ReadConsoleOutputCharacterA [KERNEL32.@]
673 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
674 COORD coord, LPDWORD read_count)
678 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
680 if (read_count) *read_count = 0;
681 if (!wptr) return FALSE;
683 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
685 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
686 if (read_count) *read_count = read;
688 HeapFree( GetProcessHeap(), 0, wptr );
693 /******************************************************************************
694 * ReadConsoleOutputCharacterW [KERNEL32.@]
697 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
698 COORD coord, LPDWORD read_count )
702 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
704 SERVER_START_REQ( read_console_output )
706 req->handle = console_handle_unmap(hConsoleOutput);
709 req->mode = CHAR_INFO_MODE_TEXT;
711 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
712 if ((ret = !wine_server_call_err( req )))
714 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
722 /******************************************************************************
723 * ReadConsoleOutputAttribute [KERNEL32.@]
725 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
726 COORD coord, LPDWORD read_count)
730 TRACE("(%p,%p,%d,%dx%d,%p)\n",
731 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
733 SERVER_START_REQ( read_console_output )
735 req->handle = console_handle_unmap(hConsoleOutput);
738 req->mode = CHAR_INFO_MODE_ATTR;
740 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
741 if ((ret = !wine_server_call_err( req )))
743 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
751 /******************************************************************************
752 * ReadConsoleOutputA [KERNEL32.@]
755 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
756 COORD coord, LPSMALL_RECT region )
761 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
762 if (ret && region->Right >= region->Left)
764 for (y = 0; y <= region->Bottom - region->Top; y++)
766 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
767 region->Right - region->Left + 1 );
774 /******************************************************************************
775 * ReadConsoleOutputW [KERNEL32.@]
777 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
778 * think we need to be *that* compatible. -- AJ
780 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
781 COORD coord, LPSMALL_RECT region )
783 int width, height, y;
786 width = min( region->Right - region->Left + 1, size.X - coord.X );
787 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
789 if (width > 0 && height > 0)
791 for (y = 0; y < height; y++)
793 SERVER_START_REQ( read_console_output )
795 req->handle = console_handle_unmap(hConsoleOutput);
796 req->x = region->Left;
797 req->y = region->Top + y;
798 req->mode = CHAR_INFO_MODE_TEXTATTR;
800 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
801 width * sizeof(CHAR_INFO) );
802 if ((ret = !wine_server_call_err( req )))
804 width = min( width, reply->width - region->Left );
805 height = min( height, reply->height - region->Top );
812 region->Bottom = region->Top + height - 1;
813 region->Right = region->Left + width - 1;
818 /******************************************************************************
819 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
822 * handle [I] Handle to console input buffer
823 * buffer [O] Address of buffer for read data
824 * count [I] Number of records to read
825 * pRead [O] Address of number of records read
831 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
835 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
836 input_records_WtoA( buffer, read );
837 if (pRead) *pRead = read;
842 /***********************************************************************
843 * PeekConsoleInputA (KERNEL32.@)
845 * Gets 'count' first events (or less) from input queue.
847 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
851 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
852 input_records_WtoA( buffer, read );
853 if (pRead) *pRead = read;
858 /***********************************************************************
859 * PeekConsoleInputW (KERNEL32.@)
861 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
864 SERVER_START_REQ( read_console_input )
866 req->handle = console_handle_unmap(handle);
868 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
869 if ((ret = !wine_server_call_err( req )))
871 if (read) *read = count ? reply->read : 0;
879 /***********************************************************************
880 * GetNumberOfConsoleInputEvents (KERNEL32.@)
882 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
885 SERVER_START_REQ( read_console_input )
887 req->handle = console_handle_unmap(handle);
889 if ((ret = !wine_server_call_err( req )))
891 if (nrofevents) *nrofevents = reply->read;
899 /******************************************************************************
902 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
905 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
907 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
908 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
910 enum read_console_input_return ret;
912 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
914 SERVER_START_REQ( read_console_input )
916 req->handle = console_handle_unmap(handle);
918 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
919 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
920 else ret = rci_gotone;
928 /***********************************************************************
929 * FlushConsoleInputBuffer (KERNEL32.@)
931 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
933 enum read_console_input_return last;
936 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
938 return last == rci_timeout;
942 /***********************************************************************
943 * SetConsoleTitleA (KERNEL32.@)
945 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
950 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
951 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
952 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
953 ret = SetConsoleTitleW(titleW);
954 HeapFree(GetProcessHeap(), 0, titleW);
959 /***********************************************************************
960 * GetConsoleTitleA (KERNEL32.@)
962 * See GetConsoleTitleW.
964 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
966 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
970 ret = GetConsoleTitleW( ptr, size );
973 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
976 HeapFree(GetProcessHeap(), 0, ptr);
981 /******************************************************************************
982 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
985 * title [O] Address of buffer for title
986 * size [I] Size of buffer
989 * Success: Length of string copied
992 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
996 SERVER_START_REQ( get_console_input_info )
999 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1000 if (!wine_server_call_err( req ))
1002 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1011 /***********************************************************************
1012 * GetLargestConsoleWindowSize (KERNEL32.@)
1015 * This should return a COORD, but calling convention for returning
1016 * structures is different between Windows and gcc on i386.
1021 #undef GetLargestConsoleWindowSize
1022 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1030 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1033 #endif /* defined(__i386__) */
1036 /***********************************************************************
1037 * GetLargestConsoleWindowSize (KERNEL32.@)
1040 * This should return a COORD, but calling convention for returning
1041 * structures is different between Windows and gcc on i386.
1046 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1051 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1054 #endif /* defined(__i386__) */
1056 static WCHAR* S_EditString /* = NULL */;
1057 static unsigned S_EditStrPos /* = 0 */;
1059 /***********************************************************************
1060 * FreeConsole (KERNEL32.@)
1062 BOOL WINAPI FreeConsole(VOID)
1066 SERVER_START_REQ(free_console)
1068 ret = !wine_server_call_err( req );
1074 /******************************************************************
1075 * start_console_renderer
1077 * helper for AllocConsole
1078 * starts the renderer process
1080 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1085 PROCESS_INFORMATION pi;
1087 /* FIXME: use dynamic allocation for most of the buffers below */
1088 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1089 if ((ret > -1) && (ret < sizeof(buffer)) &&
1090 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1091 NULL, NULL, si, &pi))
1093 if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
1095 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1096 pi.dwProcessId, pi.dwThreadId);
1103 static BOOL start_console_renderer(STARTUPINFOA* si)
1107 OBJECT_ATTRIBUTES attr;
1110 attr.Length = sizeof(attr);
1111 attr.RootDirectory = 0;
1112 attr.Attributes = OBJ_INHERIT;
1113 attr.ObjectName = NULL;
1114 attr.SecurityDescriptor = NULL;
1115 attr.SecurityQualityOfService = NULL;
1117 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
1118 if (!hEvent) return FALSE;
1120 /* first try environment variable */
1121 if ((p = getenv("WINECONSOLE")) != NULL)
1123 ret = start_console_renderer_helper(p, si, hEvent);
1125 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1126 "trying default access\n", p);
1129 /* then try the regular PATH */
1131 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1133 CloseHandle(hEvent);
1137 /***********************************************************************
1138 * AllocConsole (KERNEL32.@)
1140 * creates an xterm with a pty to our program
1142 BOOL WINAPI AllocConsole(void)
1144 HANDLE handle_in = INVALID_HANDLE_VALUE;
1145 HANDLE handle_out = INVALID_HANDLE_VALUE;
1146 HANDLE handle_err = INVALID_HANDLE_VALUE;
1147 STARTUPINFOA siCurrent;
1148 STARTUPINFOA siConsole;
1153 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1154 FALSE, OPEN_EXISTING );
1156 if (VerifyConsoleIoHandle(handle_in))
1158 /* we already have a console opened on this process, don't create a new one */
1159 CloseHandle(handle_in);
1162 /* happens when we're running on a Unix console */
1163 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1165 GetStartupInfoA(&siCurrent);
1167 memset(&siConsole, 0, sizeof(siConsole));
1168 siConsole.cb = sizeof(siConsole);
1169 /* setup a view arguments for wineconsole (it'll use them as default values) */
1170 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1172 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1173 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1174 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1176 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1178 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1179 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1181 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1183 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1184 siConsole.wShowWindow = siCurrent.wShowWindow;
1186 /* FIXME (should pass the unicode form) */
1187 if (siCurrent.lpTitle)
1188 siConsole.lpTitle = siCurrent.lpTitle;
1189 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1191 buffer[sizeof(buffer) - 1] = '\0';
1192 siConsole.lpTitle = buffer;
1195 if (!start_console_renderer(&siConsole))
1198 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1199 /* all std I/O handles are inheritable by default */
1200 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1201 TRUE, OPEN_EXISTING );
1202 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1204 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1205 TRUE, OPEN_EXISTING );
1206 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1208 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1209 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1212 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1213 handle_in = siCurrent.hStdInput;
1214 handle_out = siCurrent.hStdOutput;
1215 handle_err = siCurrent.hStdError;
1218 /* NT resets the STD_*_HANDLEs on console alloc */
1219 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1220 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1221 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1223 SetLastError(ERROR_SUCCESS);
1228 ERR("Can't allocate console\n");
1229 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1230 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1231 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1237 /***********************************************************************
1238 * ReadConsoleA (KERNEL32.@)
1240 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1241 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1243 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1247 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1248 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1250 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1251 HeapFree(GetProcessHeap(), 0, ptr);
1256 /***********************************************************************
1257 * ReadConsoleW (KERNEL32.@)
1259 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1260 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1263 LPWSTR xbuf = (LPWSTR)lpBuffer;
1266 TRACE("(%p,%p,%d,%p,%p)\n",
1267 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1269 if (!GetConsoleMode(hConsoleInput, &mode))
1272 if (mode & ENABLE_LINE_INPUT)
1274 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1276 HeapFree(GetProcessHeap(), 0, S_EditString);
1277 if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1281 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1282 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1283 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1284 S_EditStrPos += charsread;
1289 DWORD timeout = INFINITE;
1291 /* FIXME: should we read at least 1 char? The SDK does not say */
1292 /* wait for at least one available input record (it doesn't mean we'll have
1293 * chars stored in xbuf...)
1298 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1300 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1301 ir.Event.KeyEvent.uChar.UnicodeChar &&
1302 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
1304 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1306 } while (charsread < nNumberOfCharsToRead);
1307 /* nothing has been read */
1308 if (timeout == INFINITE) return FALSE;
1311 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1317 /***********************************************************************
1318 * ReadConsoleInputW (KERNEL32.@)
1320 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1321 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1324 DWORD timeout = INFINITE;
1328 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1332 /* loop until we get at least one event */
1333 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1337 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1342 /******************************************************************************
1343 * WriteConsoleOutputCharacterW [KERNEL32.@]
1345 * Copy character to consecutive cells in the console screen buffer.
1348 * hConsoleOutput [I] Handle to screen buffer
1349 * str [I] Pointer to buffer with chars to write
1350 * length [I] Number of cells to write to
1351 * coord [I] Coords of first cell
1352 * lpNumCharsWritten [O] Pointer to number of cells written
1359 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1360 COORD coord, LPDWORD lpNumCharsWritten )
1364 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1365 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1367 SERVER_START_REQ( write_console_output )
1369 req->handle = console_handle_unmap(hConsoleOutput);
1372 req->mode = CHAR_INFO_MODE_TEXT;
1374 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1375 if ((ret = !wine_server_call_err( req )))
1377 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1385 /******************************************************************************
1386 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1389 * title [I] Address of new title
1395 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1399 TRACE("(%s)\n", debugstr_w(title));
1400 SERVER_START_REQ( set_console_input_info )
1403 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1404 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1405 ret = !wine_server_call_err( req );
1412 /***********************************************************************
1413 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1415 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1417 FIXME("(%p): stub\n", nrofbuttons);
1422 /******************************************************************************
1423 * SetConsoleInputExeNameW [KERNEL32.@]
1428 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1430 FIXME("(%s): stub!\n", debugstr_w(name));
1432 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1436 /******************************************************************************
1437 * SetConsoleInputExeNameA [KERNEL32.@]
1442 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1444 int len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1445 LPWSTR xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1448 if (!xptr) return FALSE;
1450 MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
1451 ret = SetConsoleInputExeNameW(xptr);
1452 HeapFree(GetProcessHeap(), 0, xptr);
1457 /******************************************************************
1458 * CONSOLE_DefaultHandler
1460 * Final control event handler
1462 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1464 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1466 /* should never go here */
1470 /******************************************************************************
1471 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1474 * func [I] Address of handler function
1475 * add [I] Handler to add or remove
1482 struct ConsoleHandler
1484 PHANDLER_ROUTINE handler;
1485 struct ConsoleHandler* next;
1488 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1489 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1491 static CRITICAL_SECTION CONSOLE_CritSect;
1492 static CRITICAL_SECTION_DEBUG critsect_debug =
1494 0, 0, &CONSOLE_CritSect,
1495 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
1496 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
1498 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
1500 /*****************************************************************************/
1502 /******************************************************************
1503 * SetConsoleCtrlHandler (KERNEL32.@)
1505 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1509 TRACE("(%p,%i)\n", func, add);
1513 RtlEnterCriticalSection(&CONSOLE_CritSect);
1515 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1517 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1518 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1522 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1524 if (!ch) return FALSE;
1526 RtlEnterCriticalSection(&CONSOLE_CritSect);
1527 ch->next = CONSOLE_Handlers;
1528 CONSOLE_Handlers = ch;
1529 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1533 struct ConsoleHandler** ch;
1534 RtlEnterCriticalSection(&CONSOLE_CritSect);
1535 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1537 if ((*ch)->handler == func) break;
1541 struct ConsoleHandler* rch = *ch;
1544 if (rch == &CONSOLE_DefaultConsoleHandler)
1546 ERR("Who's trying to remove default handler???\n");
1547 SetLastError(ERROR_INVALID_PARAMETER);
1553 HeapFree(GetProcessHeap(), 0, rch);
1558 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1559 SetLastError(ERROR_INVALID_PARAMETER);
1562 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1567 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
1569 TRACE("(%x)\n", GetExceptionCode());
1570 return EXCEPTION_EXECUTE_HANDLER;
1573 /******************************************************************
1574 * CONSOLE_SendEventThread
1576 * Internal helper to pass an event to the list on installed handlers
1578 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1580 DWORD_PTR event = (DWORD_PTR)pmt;
1581 struct ConsoleHandler* ch;
1583 if (event == CTRL_C_EVENT)
1585 BOOL caught_by_dbg = TRUE;
1586 /* First, try to pass the ctrl-C event to the debugger (if any)
1587 * If it continues, there's nothing more to do
1588 * Otherwise, we need to send the ctrl-C event to the handlers
1592 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1594 __EXCEPT(CONSOLE_CtrlEventHandler)
1596 caught_by_dbg = FALSE;
1599 if (caught_by_dbg) return 0;
1600 /* the debugger didn't continue... so, pass to ctrl handlers */
1602 RtlEnterCriticalSection(&CONSOLE_CritSect);
1603 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1605 if (ch->handler(event)) break;
1607 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1611 /******************************************************************
1612 * CONSOLE_HandleCtrlC
1614 * Check whether the shall manipulate CtrlC events
1616 int CONSOLE_HandleCtrlC(unsigned sig)
1618 /* FIXME: better test whether a console is attached to this process ??? */
1619 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1620 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1622 /* check if we have to ignore ctrl-C events */
1623 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1625 /* Create a separate thread to signal all the events.
1626 * This is needed because:
1627 * - this function can be called in an Unix signal handler (hence on an
1628 * different stack than the thread that's running). This breaks the
1629 * Win32 exception mechanisms (where the thread's stack is checked).
1630 * - since the current thread, while processing the signal, can hold the
1631 * console critical section, we need another execution environment where
1632 * we can wait on this critical section
1634 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1639 /******************************************************************************
1640 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1643 * dwCtrlEvent [I] Type of event
1644 * dwProcessGroupID [I] Process group ID to send event to
1648 * Failure: False (and *should* [but doesn't] set LastError)
1650 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1651 DWORD dwProcessGroupID)
1655 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
1657 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1659 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
1663 SERVER_START_REQ( send_console_signal )
1665 req->signal = dwCtrlEvent;
1666 req->group_id = dwProcessGroupID;
1667 ret = !wine_server_call_err( req );
1671 /* FIXME: shall this function be synchronous, ie only return when all events
1672 * have been handled by all processes in the given group ?
1673 * As of today, we don't wait...
1679 /******************************************************************************
1680 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
1683 * dwDesiredAccess [I] Access flag
1684 * dwShareMode [I] Buffer share mode
1685 * sa [I] Security attributes
1686 * dwFlags [I] Type of buffer to create
1687 * lpScreenBufferData [I] Reserved
1690 * Should call SetLastError
1693 * Success: Handle to new console screen buffer
1694 * Failure: INVALID_HANDLE_VALUE
1696 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1697 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1698 LPVOID lpScreenBufferData)
1700 HANDLE ret = INVALID_HANDLE_VALUE;
1702 TRACE("(%d,%d,%p,%d,%p)\n",
1703 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1705 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1707 SetLastError(ERROR_INVALID_PARAMETER);
1708 return INVALID_HANDLE_VALUE;
1711 SERVER_START_REQ(create_console_output)
1714 req->access = dwDesiredAccess;
1715 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
1716 req->share = dwShareMode;
1717 if (!wine_server_call_err( req )) ret = reply->handle_out;
1725 /***********************************************************************
1726 * GetConsoleScreenBufferInfo (KERNEL32.@)
1728 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1732 SERVER_START_REQ(get_console_output_info)
1734 req->handle = console_handle_unmap(hConsoleOutput);
1735 if ((ret = !wine_server_call_err( req )))
1737 csbi->dwSize.X = reply->width;
1738 csbi->dwSize.Y = reply->height;
1739 csbi->dwCursorPosition.X = reply->cursor_x;
1740 csbi->dwCursorPosition.Y = reply->cursor_y;
1741 csbi->wAttributes = reply->attr;
1742 csbi->srWindow.Left = reply->win_left;
1743 csbi->srWindow.Right = reply->win_right;
1744 csbi->srWindow.Top = reply->win_top;
1745 csbi->srWindow.Bottom = reply->win_bottom;
1746 csbi->dwMaximumWindowSize.X = reply->max_width;
1747 csbi->dwMaximumWindowSize.Y = reply->max_height;
1752 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
1753 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1754 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1756 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1757 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1763 /******************************************************************************
1764 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
1770 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1774 TRACE("(%p)\n", hConsoleOutput);
1776 SERVER_START_REQ( set_console_input_info )
1779 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1780 req->active_sb = hConsoleOutput;
1781 ret = !wine_server_call_err( req );
1788 /***********************************************************************
1789 * GetConsoleMode (KERNEL32.@)
1791 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1795 SERVER_START_REQ(get_console_mode)
1797 req->handle = console_handle_unmap(hcon);
1798 ret = !wine_server_call_err( req );
1799 if (ret && mode) *mode = reply->mode;
1806 /******************************************************************************
1807 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
1810 * hcon [I] Handle to console input or screen buffer
1811 * mode [I] Input or output mode to set
1818 * ENABLE_PROCESSED_INPUT 0x01
1819 * ENABLE_LINE_INPUT 0x02
1820 * ENABLE_ECHO_INPUT 0x04
1821 * ENABLE_WINDOW_INPUT 0x08
1822 * ENABLE_MOUSE_INPUT 0x10
1824 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1828 SERVER_START_REQ(set_console_mode)
1830 req->handle = console_handle_unmap(hcon);
1832 ret = !wine_server_call_err( req );
1835 /* FIXME: when resetting a console input to editline mode, I think we should
1836 * empty the S_EditString buffer
1839 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
1845 /******************************************************************
1846 * CONSOLE_WriteChars
1848 * WriteConsoleOutput helper: hides server call semantics
1849 * writes a string at a given pos with standard attribute
1851 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1857 SERVER_START_REQ( write_console_output )
1859 req->handle = console_handle_unmap(hCon);
1862 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1864 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1865 if (!wine_server_call_err( req )) written = reply->written;
1869 if (written > 0) pos->X += written;
1873 /******************************************************************
1876 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1879 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1885 csbi->dwCursorPosition.X = 0;
1886 csbi->dwCursorPosition.Y++;
1888 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1891 src.Bottom = csbi->dwSize.Y - 1;
1893 src.Right = csbi->dwSize.X - 1;
1898 ci.Attributes = csbi->wAttributes;
1899 ci.Char.UnicodeChar = ' ';
1901 csbi->dwCursorPosition.Y--;
1902 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1907 /******************************************************************
1910 * WriteConsoleOutput helper: writes a block of non special characters
1911 * Block can spread on several lines, and wrapping, if needed, is
1915 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1916 DWORD mode, LPCWSTR ptr, int len)
1918 int blk; /* number of chars to write on current line */
1919 int done; /* number of chars already written */
1921 if (len <= 0) return 1;
1923 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1925 for (done = 0; done < len; done += blk)
1927 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1929 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1931 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
1937 int pos = csbi->dwCursorPosition.X;
1938 /* FIXME: we could reduce the number of loops
1939 * but, in most cases we wouldn't gain lots of time (it would only
1940 * happen if we're asked to overwrite more than twice the part of the line,
1943 for (blk = done = 0; done < len; done += blk)
1945 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1947 csbi->dwCursorPosition.X = pos;
1948 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1956 /***********************************************************************
1957 * WriteConsoleW (KERNEL32.@)
1959 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1960 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1964 const WCHAR* psz = lpBuffer;
1965 CONSOLE_SCREEN_BUFFER_INFO csbi;
1968 TRACE("%p %s %d %p %p\n",
1969 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
1970 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
1972 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1974 if (!GetConsoleMode(hConsoleOutput, &mode) ||
1975 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1978 if (mode & ENABLE_PROCESSED_OUTPUT)
1982 for (i = 0; i < nNumberOfCharsToWrite; i++)
1986 case '\b': case '\t': case '\n': case '\a': case '\r':
1987 /* don't handle here the i-th char... done below */
1988 if ((k = i - first) > 0)
1990 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2000 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2004 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2006 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2007 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2012 next_line(hConsoleOutput, &csbi);
2018 csbi.dwCursorPosition.X = 0;
2026 /* write the remaining block (if any) if processed output is enabled, or the
2027 * entire buffer otherwise
2029 if ((k = nNumberOfCharsToWrite - first) > 0)
2031 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2037 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2038 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2043 /***********************************************************************
2044 * WriteConsoleA (KERNEL32.@)
2046 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2047 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2053 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2055 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2056 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2057 if (!xstring) return 0;
2059 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2061 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2063 HeapFree(GetProcessHeap(), 0, xstring);
2068 /******************************************************************************
2069 * SetConsoleCursorPosition [KERNEL32.@]
2070 * Sets the cursor position in console
2073 * hConsoleOutput [I] Handle of console screen buffer
2074 * dwCursorPosition [I] New cursor position coordinates
2080 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2083 CONSOLE_SCREEN_BUFFER_INFO csbi;
2087 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2089 SERVER_START_REQ(set_console_output_info)
2091 req->handle = console_handle_unmap(hcon);
2092 req->cursor_x = pos.X;
2093 req->cursor_y = pos.Y;
2094 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2095 ret = !wine_server_call_err( req );
2099 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2102 /* if cursor is no longer visible, scroll the visible window... */
2103 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2104 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2105 if (pos.X < csbi.srWindow.Left)
2107 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2110 else if (pos.X > csbi.srWindow.Right)
2112 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2115 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2117 if (pos.Y < csbi.srWindow.Top)
2119 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2122 else if (pos.Y > csbi.srWindow.Bottom)
2124 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2127 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2129 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2134 /******************************************************************************
2135 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2138 * hcon [I] Handle to console screen buffer
2139 * cinfo [O] Address of cursor information
2145 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2149 SERVER_START_REQ(get_console_output_info)
2151 req->handle = console_handle_unmap(hCon);
2152 ret = !wine_server_call_err( req );
2155 cinfo->dwSize = reply->cursor_size;
2156 cinfo->bVisible = reply->cursor_visible;
2161 TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2166 /******************************************************************************
2167 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2170 * hcon [I] Handle to console screen buffer
2171 * cinfo [I] Address of cursor information
2176 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2180 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2181 SERVER_START_REQ(set_console_output_info)
2183 req->handle = console_handle_unmap(hCon);
2184 req->cursor_size = cinfo->dwSize;
2185 req->cursor_visible = cinfo->bVisible;
2186 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2187 ret = !wine_server_call_err( req );
2194 /******************************************************************************
2195 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2198 * hcon [I] Handle to console screen buffer
2199 * bAbsolute [I] Coordinate type flag
2200 * window [I] Address of new window rectangle
2205 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2207 SMALL_RECT p = *window;
2210 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2214 CONSOLE_SCREEN_BUFFER_INFO csbi;
2216 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2218 p.Left += csbi.srWindow.Left;
2219 p.Top += csbi.srWindow.Top;
2220 p.Right += csbi.srWindow.Right;
2221 p.Bottom += csbi.srWindow.Bottom;
2223 SERVER_START_REQ(set_console_output_info)
2225 req->handle = console_handle_unmap(hCon);
2226 req->win_left = p.Left;
2227 req->win_top = p.Top;
2228 req->win_right = p.Right;
2229 req->win_bottom = p.Bottom;
2230 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2231 ret = !wine_server_call_err( req );
2239 /******************************************************************************
2240 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2242 * Sets the foreground and background color attributes of characters
2243 * written to the screen buffer.
2249 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2253 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2254 SERVER_START_REQ(set_console_output_info)
2256 req->handle = console_handle_unmap(hConsoleOutput);
2258 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2259 ret = !wine_server_call_err( req );
2266 /******************************************************************************
2267 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2270 * hConsoleOutput [I] Handle to console screen buffer
2271 * dwSize [I] New size in character rows and cols
2277 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2281 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2282 SERVER_START_REQ(set_console_output_info)
2284 req->handle = console_handle_unmap(hConsoleOutput);
2285 req->width = dwSize.X;
2286 req->height = dwSize.Y;
2287 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2288 ret = !wine_server_call_err( req );
2295 /******************************************************************************
2296 * ScrollConsoleScreenBufferA [KERNEL32.@]
2299 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2300 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2305 ciw.Attributes = lpFill->Attributes;
2306 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2308 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2309 dwDestOrigin, &ciw);
2312 /******************************************************************
2313 * CONSOLE_FillLineUniform
2315 * Helper function for ScrollConsoleScreenBufferW
2316 * Fills a part of a line with a constant character info
2318 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2320 SERVER_START_REQ( fill_console_output )
2322 req->handle = console_handle_unmap(hConsoleOutput);
2323 req->mode = CHAR_INFO_MODE_TEXTATTR;
2328 req->data.ch = lpFill->Char.UnicodeChar;
2329 req->data.attr = lpFill->Attributes;
2330 wine_server_call_err( req );
2335 /******************************************************************************
2336 * ScrollConsoleScreenBufferW [KERNEL32.@]
2340 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2341 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2349 CONSOLE_SCREEN_BUFFER_INFO csbi;
2354 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2355 lpScrollRect->Left, lpScrollRect->Top,
2356 lpScrollRect->Right, lpScrollRect->Bottom,
2357 lpClipRect->Left, lpClipRect->Top,
2358 lpClipRect->Right, lpClipRect->Bottom,
2359 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2361 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2362 lpScrollRect->Left, lpScrollRect->Top,
2363 lpScrollRect->Right, lpScrollRect->Bottom,
2364 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2366 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2369 src.X = lpScrollRect->Left;
2370 src.Y = lpScrollRect->Top;
2372 /* step 1: get dst rect */
2373 dst.Left = dwDestOrigin.X;
2374 dst.Top = dwDestOrigin.Y;
2375 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2376 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2378 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2381 clip.Left = max(0, lpClipRect->Left);
2382 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2383 clip.Top = max(0, lpClipRect->Top);
2384 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2389 clip.Right = csbi.dwSize.X - 1;
2391 clip.Bottom = csbi.dwSize.Y - 1;
2393 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2395 /* step 2b: clip dst rect */
2396 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2397 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2398 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2399 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2401 /* step 3: transfer the bits */
2402 SERVER_START_REQ(move_console_output)
2404 req->handle = console_handle_unmap(hConsoleOutput);
2407 req->x_dst = dst.Left;
2408 req->y_dst = dst.Top;
2409 req->w = dst.Right - dst.Left + 1;
2410 req->h = dst.Bottom - dst.Top + 1;
2411 ret = !wine_server_call_err( req );
2415 if (!ret) return FALSE;
2417 /* step 4: clean out the exposed part */
2419 /* have to write cell [i,j] if it is not in dst rect (because it has already
2420 * been written to by the scroll) and is in clip (we shall not write
2423 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2425 inside = dst.Top <= j && j <= dst.Bottom;
2427 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2429 if (inside && dst.Left <= i && i <= dst.Right)
2433 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2439 if (start == -1) start = i;
2443 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2449 /******************************************************************
2450 * AttachConsole (KERNEL32.@)
2452 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2454 FIXME("stub %x\n",dwProcessId);
2459 /* ====================================================================
2461 * Console manipulation functions
2463 * ====================================================================*/
2465 /* some missing functions...
2466 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2467 * should get the right API and implement them
2468 * GetConsoleCommandHistory[AW] (dword dword dword)
2469 * GetConsoleCommandHistoryLength[AW]
2470 * SetConsoleCommandHistoryMode
2471 * SetConsoleNumberOfCommands[AW]
2473 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2477 SERVER_START_REQ( get_console_input_history )
2481 if (buf && buf_len > 1)
2483 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2485 if (!wine_server_call_err( req ))
2487 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2488 len = reply->total / sizeof(WCHAR) + 1;
2495 /******************************************************************
2496 * CONSOLE_AppendHistory
2500 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2502 size_t len = strlenW(ptr);
2505 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2507 SERVER_START_REQ( append_console_input_history )
2510 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2511 ret = !wine_server_call_err( req );
2517 /******************************************************************
2518 * CONSOLE_GetNumHistoryEntries
2522 unsigned CONSOLE_GetNumHistoryEntries(void)
2525 SERVER_START_REQ(get_console_input_info)
2528 if (!wine_server_call_err( req )) ret = reply->history_index;
2534 /******************************************************************
2535 * CONSOLE_GetEditionMode
2539 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2541 unsigned ret = FALSE;
2542 SERVER_START_REQ(get_console_input_info)
2544 req->handle = console_handle_unmap(hConIn);
2545 if ((ret = !wine_server_call_err( req )))
2546 *mode = reply->edition_mode;