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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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.@]
125 HWND WINAPI GetConsoleWindow(VOID)
132 /******************************************************************************
133 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
138 UINT WINAPI GetConsoleCP(VOID)
140 if (!console_input_codepage)
142 console_input_codepage = GetOEMCP();
143 TRACE("%u\n", console_input_codepage);
145 return console_input_codepage;
149 /******************************************************************************
150 * SetConsoleCP [KERNEL32.@]
152 BOOL WINAPI SetConsoleCP(UINT cp)
154 if (!IsValidCodePage( cp )) return FALSE;
155 console_input_codepage = cp;
160 /***********************************************************************
161 * GetConsoleOutputCP (KERNEL32.@)
163 UINT WINAPI GetConsoleOutputCP(VOID)
165 if (!console_output_codepage)
167 console_output_codepage = GetOEMCP();
168 TRACE("%u\n", console_output_codepage);
170 return console_output_codepage;
174 /******************************************************************************
175 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
178 * cp [I] code page to set
184 BOOL WINAPI SetConsoleOutputCP(UINT cp)
186 if (!IsValidCodePage( cp )) return FALSE;
187 console_output_codepage = cp;
192 /***********************************************************************
195 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
197 static const char beep = '\a';
198 /* dwFreq and dwDur are ignored by Win95 */
199 if (isatty(2)) write( 2, &beep, 1 );
204 /******************************************************************
205 * OpenConsoleW (KERNEL32.@)
208 * Open a handle to the current process console.
209 * Returns INVALID_HANDLE_VALUE on failure.
211 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
216 if (strcmpiW(coninW, name) == 0)
218 else if (strcmpiW(conoutW, name) == 0)
222 SetLastError(ERROR_INVALID_NAME);
223 return INVALID_HANDLE_VALUE;
225 if (creation != OPEN_EXISTING)
227 SetLastError(ERROR_INVALID_PARAMETER);
228 return INVALID_HANDLE_VALUE;
231 SERVER_START_REQ( open_console )
234 req->access = access;
235 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
236 req->inherit = inherit;
238 wine_server_call_err( req );
243 ret = console_handle_map(ret);
246 /* likely, we're not attached to wineconsole
247 * let's try to return a handle to the unix-console
249 int fd = open("/dev/tty", output ? O_WRONLY : O_RDONLY);
250 ret = INVALID_HANDLE_VALUE;
253 DWORD attr = (output ? GENERIC_WRITE : GENERIC_READ) | SYNCHRONIZE;
254 wine_server_fd_to_handle(fd, attr, inherit, &ret);
261 /******************************************************************
262 * VerifyConsoleIoHandle (KERNEL32.@)
266 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
270 if (!is_console_handle(handle)) return FALSE;
271 SERVER_START_REQ(get_console_mode)
273 req->handle = console_handle_unmap(handle);
274 ret = !wine_server_call_err( req );
280 /******************************************************************
281 * DuplicateConsoleHandle (KERNEL32.@)
285 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
290 if (!is_console_handle(handle) ||
291 !DuplicateHandle(GetCurrentProcess(), console_handle_unmap(handle),
292 GetCurrentProcess(), &ret, access, inherit, options))
293 return INVALID_HANDLE_VALUE;
294 return console_handle_map(ret);
297 /******************************************************************
298 * CloseConsoleHandle (KERNEL32.@)
302 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
304 if (!is_console_handle(handle))
306 SetLastError(ERROR_INVALID_PARAMETER);
309 return CloseHandle(console_handle_unmap(handle));
312 /******************************************************************
313 * GetConsoleInputWaitHandle (KERNEL32.@)
317 HANDLE WINAPI GetConsoleInputWaitHandle(void)
319 static HANDLE console_wait_event;
321 /* FIXME: this is not thread safe */
322 if (!console_wait_event)
324 SERVER_START_REQ(get_console_wait_event)
326 if (!wine_server_call_err( req )) console_wait_event = reply->handle;
330 return console_wait_event;
334 /******************************************************************************
335 * WriteConsoleInputA [KERNEL32.@]
337 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
338 DWORD count, LPDWORD written )
343 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
344 memcpy( recW, buffer, count*sizeof(*recW) );
345 input_records_AtoW( recW, count );
346 ret = WriteConsoleInputW( handle, recW, count, written );
347 HeapFree( GetProcessHeap(), 0, recW );
352 /******************************************************************************
353 * WriteConsoleInputW [KERNEL32.@]
355 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
356 DWORD count, LPDWORD written )
360 TRACE("(%p,%p,%ld,%p)\n", handle, buffer, count, written);
362 if (written) *written = 0;
363 SERVER_START_REQ( write_console_input )
365 req->handle = console_handle_unmap(handle);
366 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
367 if ((ret = !wine_server_call_err( req )) && written)
368 *written = reply->written;
376 /***********************************************************************
377 * WriteConsoleOutputA (KERNEL32.@)
379 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
380 COORD size, COORD coord, LPSMALL_RECT region )
384 COORD new_size, new_coord;
387 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
388 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
390 if (new_size.X <= 0 || new_size.Y <= 0)
392 region->Bottom = region->Top + new_size.Y - 1;
393 region->Right = region->Left + new_size.X - 1;
397 /* only copy the useful rectangle */
398 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
400 for (y = 0; y < new_size.Y; y++)
402 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
403 new_size.X * sizeof(CHAR_INFO) );
404 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
406 new_coord.X = new_coord.Y = 0;
407 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
408 HeapFree( GetProcessHeap(), 0, ciw );
413 /***********************************************************************
414 * WriteConsoleOutputW (KERNEL32.@)
416 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
417 COORD size, COORD coord, LPSMALL_RECT region )
419 int width, height, y;
422 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
423 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
424 region->Left, region->Top, region->Right, region->Bottom);
426 width = min( region->Right - region->Left + 1, size.X - coord.X );
427 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
429 if (width > 0 && height > 0)
431 for (y = 0; y < height; y++)
433 SERVER_START_REQ( write_console_output )
435 req->handle = console_handle_unmap(hConsoleOutput);
436 req->x = region->Left;
437 req->y = region->Top + y;
438 req->mode = CHAR_INFO_MODE_TEXTATTR;
440 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
441 width * sizeof(CHAR_INFO));
442 if ((ret = !wine_server_call_err( req )))
444 width = min( width, reply->width - region->Left );
445 height = min( height, reply->height - region->Top );
452 region->Bottom = region->Top + height - 1;
453 region->Right = region->Left + width - 1;
458 /******************************************************************************
459 * WriteConsoleOutputCharacterA [KERNEL32.@] Copies character to consecutive
460 * cells in the console screen buffer
463 * hConsoleOutput [I] Handle to screen buffer
464 * str [I] Pointer to buffer with chars to write
465 * length [I] Number of cells to write to
466 * coord [I] Coords of first cell
467 * lpNumCharsWritten [O] Pointer to number of cells written
469 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
470 COORD coord, LPDWORD lpNumCharsWritten )
476 TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
477 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
479 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
481 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
483 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
484 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
486 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
487 HeapFree( GetProcessHeap(), 0, strW );
492 /******************************************************************************
493 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
494 * the console screen buffer
497 * hConsoleOutput [I] Handle to screen buffer
498 * attr [I] Pointer to buffer with write attributes
499 * length [I] Number of cells to write to
500 * coord [I] Coords of first cell
501 * lpNumAttrsWritten [O] Pointer to number of cells written
508 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
509 COORD coord, LPDWORD lpNumAttrsWritten )
513 TRACE("(%p,%p,%ld,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
515 SERVER_START_REQ( write_console_output )
517 req->handle = console_handle_unmap(hConsoleOutput);
520 req->mode = CHAR_INFO_MODE_ATTR;
522 wine_server_add_data( req, attr, length * sizeof(WORD) );
523 if ((ret = !wine_server_call_err( req )))
525 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
533 /******************************************************************************
534 * FillConsoleOutputCharacterA [KERNEL32.@]
537 * hConsoleOutput [I] Handle to screen buffer
538 * ch [I] Character to write
539 * length [I] Number of cells to write to
540 * coord [I] Coords of first cell
541 * lpNumCharsWritten [O] Pointer to number of cells written
547 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
548 COORD coord, LPDWORD lpNumCharsWritten )
552 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
553 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
557 /******************************************************************************
558 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
561 * hConsoleOutput [I] Handle to screen buffer
562 * ch [I] Character to write
563 * length [I] Number of cells to write to
564 * coord [I] Coords of first cell
565 * lpNumCharsWritten [O] Pointer to number of cells written
571 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
572 COORD coord, LPDWORD lpNumCharsWritten)
576 TRACE("(%p,%s,%ld,(%dx%d),%p)\n",
577 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
579 SERVER_START_REQ( fill_console_output )
581 req->handle = console_handle_unmap(hConsoleOutput);
584 req->mode = CHAR_INFO_MODE_TEXT;
588 if ((ret = !wine_server_call_err( req )))
590 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
598 /******************************************************************************
599 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
602 * hConsoleOutput [I] Handle to screen buffer
603 * attr [I] Color attribute to write
604 * length [I] Number of cells to write to
605 * coord [I] Coords of first cell
606 * lpNumAttrsWritten [O] Pointer to number of cells written
612 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
613 COORD coord, LPDWORD lpNumAttrsWritten )
617 TRACE("(%p,%d,%ld,(%dx%d),%p)\n",
618 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
620 SERVER_START_REQ( fill_console_output )
622 req->handle = console_handle_unmap(hConsoleOutput);
625 req->mode = CHAR_INFO_MODE_ATTR;
627 req->data.attr = attr;
629 if ((ret = !wine_server_call_err( req )))
631 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
639 /******************************************************************************
640 * ReadConsoleOutputCharacterA [KERNEL32.@]
643 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
644 COORD coord, LPDWORD read_count)
648 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
650 if (read_count) *read_count = 0;
651 if (!wptr) return FALSE;
653 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
655 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
656 if (read_count) *read_count = read;
658 HeapFree( GetProcessHeap(), 0, wptr );
663 /******************************************************************************
664 * ReadConsoleOutputCharacterW [KERNEL32.@]
667 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
668 COORD coord, LPDWORD read_count )
672 TRACE( "(%p,%p,%ld,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
674 SERVER_START_REQ( read_console_output )
676 req->handle = console_handle_unmap(hConsoleOutput);
679 req->mode = CHAR_INFO_MODE_TEXT;
681 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
682 if ((ret = !wine_server_call_err( req )))
684 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
692 /******************************************************************************
693 * ReadConsoleOutputAttribute [KERNEL32.@]
695 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
696 COORD coord, LPDWORD read_count)
700 TRACE("(%p,%p,%ld,%dx%d,%p)\n",
701 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
703 SERVER_START_REQ( read_console_output )
705 req->handle = console_handle_unmap(hConsoleOutput);
708 req->mode = CHAR_INFO_MODE_ATTR;
710 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
711 if ((ret = !wine_server_call_err( req )))
713 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
721 /******************************************************************************
722 * ReadConsoleOutputA [KERNEL32.@]
725 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
726 COORD coord, LPSMALL_RECT region )
731 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
732 if (ret && region->Right >= region->Left)
734 for (y = 0; y <= region->Bottom - region->Top; y++)
736 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
737 region->Right - region->Left + 1 );
744 /******************************************************************************
745 * ReadConsoleOutputW [KERNEL32.@]
747 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
748 * think we need to be *that* compatible. -- AJ
750 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
751 COORD coord, LPSMALL_RECT region )
753 int width, height, y;
756 width = min( region->Right - region->Left + 1, size.X - coord.X );
757 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
759 if (width > 0 && height > 0)
761 for (y = 0; y < height; y++)
763 SERVER_START_REQ( read_console_output )
765 req->handle = console_handle_unmap(hConsoleOutput);
766 req->x = region->Left;
767 req->y = region->Top + y;
768 req->mode = CHAR_INFO_MODE_TEXTATTR;
770 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
771 width * sizeof(CHAR_INFO) );
772 if ((ret = !wine_server_call_err( req )))
774 width = min( width, reply->width - region->Left );
775 height = min( height, reply->height - region->Top );
782 region->Bottom = region->Top + height - 1;
783 region->Right = region->Left + width - 1;
788 /******************************************************************************
789 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
792 * handle [I] Handle to console input buffer
793 * buffer [O] Address of buffer for read data
794 * count [I] Number of records to read
795 * pRead [O] Address of number of records read
801 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
805 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
806 input_records_WtoA( buffer, read );
807 if (pRead) *pRead = read;
812 /***********************************************************************
813 * PeekConsoleInputA (KERNEL32.@)
815 * Gets 'count' first events (or less) from input queue.
817 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
821 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
822 input_records_WtoA( buffer, read );
823 if (pRead) *pRead = read;
828 /***********************************************************************
829 * PeekConsoleInputW (KERNEL32.@)
831 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
834 SERVER_START_REQ( read_console_input )
836 req->handle = console_handle_unmap(handle);
838 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
839 if ((ret = !wine_server_call_err( req )))
841 if (read) *read = count ? reply->read : 0;
849 /***********************************************************************
850 * GetNumberOfConsoleInputEvents (KERNEL32.@)
852 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
855 SERVER_START_REQ( read_console_input )
857 req->handle = console_handle_unmap(handle);
859 if ((ret = !wine_server_call_err( req )))
861 if (nrofevents) *nrofevents = reply->read;
869 /******************************************************************************
872 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
875 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
877 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
878 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
880 enum read_console_input_return ret;
882 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
884 SERVER_START_REQ( read_console_input )
886 req->handle = console_handle_unmap(handle);
888 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
889 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
890 else ret = rci_gotone;
898 /***********************************************************************
899 * FlushConsoleInputBuffer (KERNEL32.@)
901 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
903 enum read_console_input_return last;
906 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
908 return last == rci_timeout;
912 /***********************************************************************
913 * SetConsoleTitleA (KERNEL32.@)
915 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
920 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
921 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
922 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
923 ret = SetConsoleTitleW(titleW);
924 HeapFree(GetProcessHeap(), 0, titleW);
929 /***********************************************************************
930 * GetConsoleTitleA (KERNEL32.@)
932 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
934 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
938 ret = GetConsoleTitleW( ptr, size );
941 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
944 HeapFree(GetProcessHeap(), 0, ptr);
949 /******************************************************************************
950 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
953 * title [O] Address of buffer for title
954 * size [I] Size of buffer
957 * Success: Length of string copied
960 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
964 SERVER_START_REQ( get_console_input_info )
967 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
968 if (!wine_server_call_err( req ))
970 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
979 /***********************************************************************
980 * GetLargestConsoleWindowSize (KERNEL32.@)
983 * This should return a COORD, but calling convention for returning
984 * structures is different between Windows and gcc on i386.
989 #undef GetLargestConsoleWindowSize
990 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
998 TRACE("(%p), returning %dx%d (%lx)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1001 #endif /* defined(__i386__) */
1004 /***********************************************************************
1005 * GetLargestConsoleWindowSize (KERNEL32.@)
1008 * This should return a COORD, but calling convention for returning
1009 * structures is different between Windows and gcc on i386.
1014 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1019 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1022 #endif /* defined(__i386__) */
1024 static WCHAR* S_EditString /* = NULL */;
1025 static unsigned S_EditStrPos /* = 0 */;
1027 /***********************************************************************
1028 * FreeConsole (KERNEL32.@)
1030 BOOL WINAPI FreeConsole(VOID)
1034 SERVER_START_REQ(free_console)
1036 ret = !wine_server_call_err( req );
1042 /******************************************************************
1043 * start_console_renderer
1045 * helper for AllocConsole
1046 * starts the renderer process
1048 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1053 PROCESS_INFORMATION pi;
1055 /* FIXME: use dynamic allocation for most of the buffers below */
1056 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%d", appname, (INT)hEvent);
1057 if ((ret > -1) && (ret < sizeof(buffer)) &&
1058 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1059 NULL, NULL, si, &pi))
1061 if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
1063 TRACE("Started wineconsole pid=%08lx tid=%08lx\n",
1064 pi.dwProcessId, pi.dwThreadId);
1071 static BOOL start_console_renderer(STARTUPINFOA* si)
1075 OBJECT_ATTRIBUTES attr;
1078 attr.Length = sizeof(attr);
1079 attr.RootDirectory = 0;
1080 attr.Attributes = OBJ_INHERIT;
1081 attr.ObjectName = NULL;
1082 attr.SecurityDescriptor = NULL;
1083 attr.SecurityQualityOfService = NULL;
1085 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
1086 if (!hEvent) return FALSE;
1088 /* first try environment variable */
1089 if ((p = getenv("WINECONSOLE")) != NULL)
1091 ret = start_console_renderer_helper(p, si, hEvent);
1093 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1094 "trying default access\n", p);
1097 /* then try the regular PATH */
1099 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1101 CloseHandle(hEvent);
1105 /***********************************************************************
1106 * AllocConsole (KERNEL32.@)
1108 * creates an xterm with a pty to our program
1110 BOOL WINAPI AllocConsole(void)
1112 HANDLE handle_in = INVALID_HANDLE_VALUE;
1113 HANDLE handle_out = INVALID_HANDLE_VALUE;
1114 HANDLE handle_err = INVALID_HANDLE_VALUE;
1115 STARTUPINFOA siCurrent;
1116 STARTUPINFOA siConsole;
1121 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1122 FALSE, OPEN_EXISTING );
1124 if (VerifyConsoleIoHandle(handle_in))
1126 /* we already have a console opened on this process, don't create a new one */
1127 CloseHandle(handle_in);
1130 /* happens when we're running on a Unix console */
1131 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1133 GetStartupInfoA(&siCurrent);
1135 memset(&siConsole, 0, sizeof(siConsole));
1136 siConsole.cb = sizeof(siConsole);
1137 /* setup a view arguments for wineconsole (it'll use them as default values) */
1138 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1140 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1141 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1142 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1144 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1146 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1147 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1149 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1151 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1152 siConsole.wShowWindow = siCurrent.wShowWindow;
1154 /* FIXME (should pass the unicode form) */
1155 if (siCurrent.lpTitle)
1156 siConsole.lpTitle = siCurrent.lpTitle;
1157 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1159 buffer[sizeof(buffer) - 1] = '\0';
1160 siConsole.lpTitle = buffer;
1163 if (!start_console_renderer(&siConsole))
1166 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1167 /* all std I/O handles are inheritable by default */
1168 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1169 TRUE, OPEN_EXISTING );
1170 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1172 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1173 TRUE, OPEN_EXISTING );
1174 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1176 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1177 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1180 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1181 handle_in = siCurrent.hStdInput;
1182 handle_out = siCurrent.hStdOutput;
1183 handle_err = siCurrent.hStdError;
1186 /* NT resets the STD_*_HANDLEs on console alloc */
1187 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1188 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1189 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1191 SetLastError(ERROR_SUCCESS);
1196 ERR("Can't allocate console\n");
1197 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1198 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1199 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1205 /***********************************************************************
1206 * ReadConsoleA (KERNEL32.@)
1208 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1209 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1211 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1215 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1216 ncr = WideCharToMultiByte(CP_ACP, 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1218 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1219 HeapFree(GetProcessHeap(), 0, ptr);
1224 /***********************************************************************
1225 * ReadConsoleW (KERNEL32.@)
1227 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1228 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1231 LPWSTR xbuf = (LPWSTR)lpBuffer;
1234 TRACE("(%p,%p,%ld,%p,%p)\n",
1235 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1237 if (!GetConsoleMode(hConsoleInput, &mode))
1240 if (mode & ENABLE_LINE_INPUT)
1242 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1244 HeapFree(GetProcessHeap(), 0, S_EditString);
1245 if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1249 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1250 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1251 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1252 S_EditStrPos += charsread;
1257 DWORD timeout = INFINITE;
1259 /* FIXME: should we read at least 1 char? The SDK does not say */
1260 /* wait for at least one available input record (it doesn't mean we'll have
1261 * chars stored in xbuf...)
1266 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1268 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1269 ir.Event.KeyEvent.uChar.UnicodeChar &&
1270 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
1272 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1274 } while (charsread < nNumberOfCharsToRead);
1275 /* nothing has been read */
1276 if (timeout == INFINITE) return FALSE;
1279 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1285 /***********************************************************************
1286 * ReadConsoleInputW (KERNEL32.@)
1288 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1289 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1292 DWORD timeout = INFINITE;
1296 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1300 /* loop until we get at least one event */
1301 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1305 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1310 /******************************************************************************
1311 * WriteConsoleOutputCharacterW [KERNEL32.@] Copies character to consecutive
1312 * cells in the console screen buffer
1315 * hConsoleOutput [I] Handle to screen buffer
1316 * str [I] Pointer to buffer with chars to write
1317 * length [I] Number of cells to write to
1318 * coord [I] Coords of first cell
1319 * lpNumCharsWritten [O] Pointer to number of cells written
1326 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1327 COORD coord, LPDWORD lpNumCharsWritten )
1331 TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
1332 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1334 SERVER_START_REQ( write_console_output )
1336 req->handle = console_handle_unmap(hConsoleOutput);
1339 req->mode = CHAR_INFO_MODE_TEXT;
1341 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1342 if ((ret = !wine_server_call_err( req )))
1344 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1352 /******************************************************************************
1353 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1356 * title [I] Address of new title
1362 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1366 TRACE("(%s)\n", debugstr_w(title));
1367 SERVER_START_REQ( set_console_input_info )
1370 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1371 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1372 ret = !wine_server_call_err( req );
1379 /***********************************************************************
1380 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1382 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1384 FIXME("(%p): stub\n", nrofbuttons);
1389 /******************************************************************************
1390 * SetConsoleInputExeNameW [KERNEL32.@]
1395 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1397 FIXME("(%s): stub!\n", debugstr_w(name));
1399 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1403 /******************************************************************************
1404 * SetConsoleInputExeNameA [KERNEL32.@]
1409 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1411 int len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1412 LPWSTR xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1415 if (!xptr) return FALSE;
1417 MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
1418 ret = SetConsoleInputExeNameW(xptr);
1419 HeapFree(GetProcessHeap(), 0, xptr);
1424 /******************************************************************
1425 * CONSOLE_DefaultHandler
1427 * Final control event handler
1429 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1431 FIXME("Terminating process %lx on event %lx\n", GetCurrentProcessId(), dwCtrlType);
1433 /* should never go here */
1437 /******************************************************************************
1438 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1441 * func [I] Address of handler function
1442 * add [I] Handler to add or remove
1449 struct ConsoleHandler
1451 PHANDLER_ROUTINE handler;
1452 struct ConsoleHandler* next;
1455 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1456 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1458 static CRITICAL_SECTION CONSOLE_CritSect;
1459 static CRITICAL_SECTION_DEBUG critsect_debug =
1461 0, 0, &CONSOLE_CritSect,
1462 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
1463 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
1465 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
1467 /*****************************************************************************/
1469 /******************************************************************
1470 * SetConsoleCtrlHandler (KERNEL32.@)
1472 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1476 TRACE("(%p,%i)\n", func, add);
1480 RtlEnterCriticalSection(&CONSOLE_CritSect);
1482 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1484 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1485 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1489 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1491 if (!ch) return FALSE;
1493 RtlEnterCriticalSection(&CONSOLE_CritSect);
1494 ch->next = CONSOLE_Handlers;
1495 CONSOLE_Handlers = ch;
1496 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1500 struct ConsoleHandler** ch;
1501 RtlEnterCriticalSection(&CONSOLE_CritSect);
1502 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1504 if ((*ch)->handler == func) break;
1508 struct ConsoleHandler* rch = *ch;
1511 if (rch == &CONSOLE_DefaultConsoleHandler)
1513 ERR("Who's trying to remove default handler???\n");
1514 SetLastError(ERROR_INVALID_PARAMETER);
1520 HeapFree(GetProcessHeap(), 0, rch);
1525 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1526 SetLastError(ERROR_INVALID_PARAMETER);
1529 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1534 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
1536 TRACE("(%lx)\n", GetExceptionCode());
1537 return EXCEPTION_EXECUTE_HANDLER;
1540 /******************************************************************
1541 * CONSOLE_SendEventThread
1543 * Internal helper to pass an event to the list on installed handlers
1545 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1547 DWORD event = (DWORD)pmt;
1548 struct ConsoleHandler* ch;
1550 if (event == CTRL_C_EVENT)
1552 BOOL caught_by_dbg = TRUE;
1553 /* First, try to pass the ctrl-C event to the debugger (if any)
1554 * If it continues, there's nothing more to do
1555 * Otherwise, we need to send the ctrl-C event to the handlers
1559 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1561 __EXCEPT(CONSOLE_CtrlEventHandler)
1563 caught_by_dbg = FALSE;
1566 if (caught_by_dbg) return 0;
1567 /* the debugger didn't continue... so, pass to ctrl handlers */
1569 RtlEnterCriticalSection(&CONSOLE_CritSect);
1570 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1572 if (ch->handler(event)) break;
1574 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1578 /******************************************************************
1579 * CONSOLE_HandleCtrlC
1581 * Check whether the shall manipulate CtrlC events
1583 int CONSOLE_HandleCtrlC(unsigned sig)
1585 /* FIXME: better test whether a console is attached to this process ??? */
1586 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1587 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1589 /* check if we have to ignore ctrl-C events */
1590 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1592 /* Create a separate thread to signal all the events.
1593 * This is needed because:
1594 * - this function can be called in an Unix signal handler (hence on an
1595 * different stack than the thread that's running). This breaks the
1596 * Win32 exception mechanisms (where the thread's stack is checked).
1597 * - since the current thread, while processing the signal, can hold the
1598 * console critical section, we need another execution environment where
1599 * we can wait on this critical section
1601 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1606 /******************************************************************************
1607 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1610 * dwCtrlEvent [I] Type of event
1611 * dwProcessGroupID [I] Process group ID to send event to
1615 * Failure: False (and *should* [but doesn't] set LastError)
1617 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1618 DWORD dwProcessGroupID)
1622 TRACE("(%ld, %ld)\n", dwCtrlEvent, dwProcessGroupID);
1624 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1626 ERR("Invalid event %ld for PGID %ld\n", dwCtrlEvent, dwProcessGroupID);
1630 SERVER_START_REQ( send_console_signal )
1632 req->signal = dwCtrlEvent;
1633 req->group_id = dwProcessGroupID;
1634 ret = !wine_server_call_err( req );
1638 /* FIXME: shall this function be synchronous, ie only return when all events
1639 * have been handled by all processes in the given group ?
1640 * As of today, we don't wait...
1646 /******************************************************************************
1647 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
1650 * dwDesiredAccess [I] Access flag
1651 * dwShareMode [I] Buffer share mode
1652 * sa [I] Security attributes
1653 * dwFlags [I] Type of buffer to create
1654 * lpScreenBufferData [I] Reserved
1657 * Should call SetLastError
1660 * Success: Handle to new console screen buffer
1661 * Failure: INVALID_HANDLE_VALUE
1663 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1664 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1665 LPVOID lpScreenBufferData)
1667 HANDLE ret = INVALID_HANDLE_VALUE;
1669 TRACE("(%ld,%ld,%p,%ld,%p)\n",
1670 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1672 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1674 SetLastError(ERROR_INVALID_PARAMETER);
1675 return INVALID_HANDLE_VALUE;
1678 SERVER_START_REQ(create_console_output)
1681 req->access = dwDesiredAccess;
1682 req->share = dwShareMode;
1683 req->inherit = (sa && sa->bInheritHandle);
1684 if (!wine_server_call_err( req )) ret = reply->handle_out;
1692 /***********************************************************************
1693 * GetConsoleScreenBufferInfo (KERNEL32.@)
1695 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1699 SERVER_START_REQ(get_console_output_info)
1701 req->handle = console_handle_unmap(hConsoleOutput);
1702 if ((ret = !wine_server_call_err( req )))
1704 csbi->dwSize.X = reply->width;
1705 csbi->dwSize.Y = reply->height;
1706 csbi->dwCursorPosition.X = reply->cursor_x;
1707 csbi->dwCursorPosition.Y = reply->cursor_y;
1708 csbi->wAttributes = reply->attr;
1709 csbi->srWindow.Left = reply->win_left;
1710 csbi->srWindow.Right = reply->win_right;
1711 csbi->srWindow.Top = reply->win_top;
1712 csbi->srWindow.Bottom = reply->win_bottom;
1713 csbi->dwMaximumWindowSize.X = reply->max_width;
1714 csbi->dwMaximumWindowSize.Y = reply->max_height;
1719 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
1720 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1721 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1723 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1724 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1730 /******************************************************************************
1731 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
1737 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1741 TRACE("(%p)\n", hConsoleOutput);
1743 SERVER_START_REQ( set_console_input_info )
1746 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1747 req->active_sb = hConsoleOutput;
1748 ret = !wine_server_call_err( req );
1755 /***********************************************************************
1756 * GetConsoleMode (KERNEL32.@)
1758 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1762 SERVER_START_REQ(get_console_mode)
1764 req->handle = console_handle_unmap(hcon);
1765 ret = !wine_server_call_err( req );
1766 if (ret && mode) *mode = reply->mode;
1773 /******************************************************************************
1774 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
1777 * hcon [I] Handle to console input or screen buffer
1778 * mode [I] Input or output mode to set
1785 * ENABLE_PROCESSED_INPUT 0x01
1786 * ENABLE_LINE_INPUT 0x02
1787 * ENABLE_ECHO_INPUT 0x04
1788 * ENABLE_WINDOW_INPUT 0x08
1789 * ENABLE_MOUSE_INPUT 0x10
1791 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1795 SERVER_START_REQ(set_console_mode)
1797 req->handle = console_handle_unmap(hcon);
1799 ret = !wine_server_call_err( req );
1802 /* FIXME: when resetting a console input to editline mode, I think we should
1803 * empty the S_EditString buffer
1806 TRACE("(%p,%lx) retval == %d\n", hcon, mode, ret);
1812 /******************************************************************
1813 * CONSOLE_WriteChars
1815 * WriteConsoleOutput helper: hides server call semantics
1816 * writes a string at a given pos with standard attribute
1818 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1824 SERVER_START_REQ( write_console_output )
1826 req->handle = console_handle_unmap(hCon);
1829 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1831 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1832 if (!wine_server_call_err( req )) written = reply->written;
1836 if (written > 0) pos->X += written;
1840 /******************************************************************
1843 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1846 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1852 csbi->dwCursorPosition.X = 0;
1853 csbi->dwCursorPosition.Y++;
1855 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1858 src.Bottom = csbi->dwSize.Y - 1;
1860 src.Right = csbi->dwSize.X - 1;
1865 ci.Attributes = csbi->wAttributes;
1866 ci.Char.UnicodeChar = ' ';
1868 csbi->dwCursorPosition.Y--;
1869 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1874 /******************************************************************
1877 * WriteConsoleOutput helper: writes a block of non special characters
1878 * Block can spread on several lines, and wrapping, if needed, is
1882 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1883 DWORD mode, LPCWSTR ptr, int len)
1885 int blk; /* number of chars to write on current line */
1886 int done; /* number of chars already written */
1888 if (len <= 0) return 1;
1890 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1892 for (done = 0; done < len; done += blk)
1894 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1896 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1898 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
1904 int pos = csbi->dwCursorPosition.X;
1905 /* FIXME: we could reduce the number of loops
1906 * but, in most cases we wouldn't gain lots of time (it would only
1907 * happen if we're asked to overwrite more than twice the part of the line,
1910 for (blk = done = 0; done < len; done += blk)
1912 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1914 csbi->dwCursorPosition.X = pos;
1915 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1923 /***********************************************************************
1924 * WriteConsoleW (KERNEL32.@)
1926 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1927 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1931 const WCHAR* psz = lpBuffer;
1932 CONSOLE_SCREEN_BUFFER_INFO csbi;
1935 TRACE("%p %s %ld %p %p\n",
1936 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
1937 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
1939 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1941 if (!GetConsoleMode(hConsoleOutput, &mode) ||
1942 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1945 if (mode & ENABLE_PROCESSED_OUTPUT)
1949 for (i = 0; i < nNumberOfCharsToWrite; i++)
1953 case '\b': case '\t': case '\n': case '\a': case '\r':
1954 /* don't handle here the i-th char... done below */
1955 if ((k = i - first) > 0)
1957 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1967 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
1971 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
1973 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
1974 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
1979 next_line(hConsoleOutput, &csbi);
1985 csbi.dwCursorPosition.X = 0;
1993 /* write the remaining block (if any) if processed output is enabled, or the
1994 * entire buffer otherwise
1996 if ((k = nNumberOfCharsToWrite - first) > 0)
1998 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2004 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2005 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2010 /***********************************************************************
2011 * WriteConsoleA (KERNEL32.@)
2013 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2014 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2020 n = MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2022 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2023 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2024 if (!xstring) return 0;
2026 MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2028 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2030 HeapFree(GetProcessHeap(), 0, xstring);
2035 /******************************************************************************
2036 * SetConsoleCursorPosition [KERNEL32.@]
2037 * Sets the cursor position in console
2040 * hConsoleOutput [I] Handle of console screen buffer
2041 * dwCursorPosition [I] New cursor position coordinates
2045 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2048 CONSOLE_SCREEN_BUFFER_INFO csbi;
2052 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2054 SERVER_START_REQ(set_console_output_info)
2056 req->handle = console_handle_unmap(hcon);
2057 req->cursor_x = pos.X;
2058 req->cursor_y = pos.Y;
2059 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2060 ret = !wine_server_call_err( req );
2064 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2067 /* if cursor is no longer visible, scroll the visible window... */
2068 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2069 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2070 if (pos.X < csbi.srWindow.Left)
2072 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2075 else if (pos.X > csbi.srWindow.Right)
2077 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2080 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2082 if (pos.Y < csbi.srWindow.Top)
2084 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2087 else if (pos.Y > csbi.srWindow.Bottom)
2089 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2092 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2094 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2099 /******************************************************************************
2100 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2103 * hcon [I] Handle to console screen buffer
2104 * cinfo [O] Address of cursor information
2110 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2114 SERVER_START_REQ(get_console_output_info)
2116 req->handle = console_handle_unmap(hCon);
2117 ret = !wine_server_call_err( req );
2120 cinfo->dwSize = reply->cursor_size;
2121 cinfo->bVisible = reply->cursor_visible;
2126 TRACE("(%p) returning (%ld,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2131 /******************************************************************************
2132 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2135 * hcon [I] Handle to console screen buffer
2136 * cinfo [I] Address of cursor information
2141 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2145 TRACE("(%p,%ld,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2146 SERVER_START_REQ(set_console_output_info)
2148 req->handle = console_handle_unmap(hCon);
2149 req->cursor_size = cinfo->dwSize;
2150 req->cursor_visible = cinfo->bVisible;
2151 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2152 ret = !wine_server_call_err( req );
2159 /******************************************************************************
2160 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2163 * hcon [I] Handle to console screen buffer
2164 * bAbsolute [I] Coordinate type flag
2165 * window [I] Address of new window rectangle
2170 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2172 SMALL_RECT p = *window;
2175 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2179 CONSOLE_SCREEN_BUFFER_INFO csbi;
2181 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2183 p.Left += csbi.srWindow.Left;
2184 p.Top += csbi.srWindow.Top;
2185 p.Right += csbi.srWindow.Right;
2186 p.Bottom += csbi.srWindow.Bottom;
2188 SERVER_START_REQ(set_console_output_info)
2190 req->handle = console_handle_unmap(hCon);
2191 req->win_left = p.Left;
2192 req->win_top = p.Top;
2193 req->win_right = p.Right;
2194 req->win_bottom = p.Bottom;
2195 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2196 ret = !wine_server_call_err( req );
2204 /******************************************************************************
2205 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2207 * Sets the foreground and background color attributes of characters
2208 * written to the screen buffer.
2214 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2218 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2219 SERVER_START_REQ(set_console_output_info)
2221 req->handle = console_handle_unmap(hConsoleOutput);
2223 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2224 ret = !wine_server_call_err( req );
2231 /******************************************************************************
2232 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2235 * hConsoleOutput [I] Handle to console screen buffer
2236 * dwSize [I] New size in character rows and cols
2242 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2246 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2247 SERVER_START_REQ(set_console_output_info)
2249 req->handle = console_handle_unmap(hConsoleOutput);
2250 req->width = dwSize.X;
2251 req->height = dwSize.Y;
2252 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2253 ret = !wine_server_call_err( req );
2260 /******************************************************************************
2261 * ScrollConsoleScreenBufferA [KERNEL32.@]
2264 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2265 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2270 ciw.Attributes = lpFill->Attributes;
2271 MultiByteToWideChar(CP_ACP, 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2273 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2274 dwDestOrigin, &ciw);
2277 /******************************************************************
2278 * CONSOLE_FillLineUniform
2280 * Helper function for ScrollConsoleScreenBufferW
2281 * Fills a part of a line with a constant character info
2283 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2285 SERVER_START_REQ( fill_console_output )
2287 req->handle = console_handle_unmap(hConsoleOutput);
2288 req->mode = CHAR_INFO_MODE_TEXTATTR;
2293 req->data.ch = lpFill->Char.UnicodeChar;
2294 req->data.attr = lpFill->Attributes;
2295 wine_server_call_err( req );
2300 /******************************************************************************
2301 * ScrollConsoleScreenBufferW [KERNEL32.@]
2305 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2306 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2314 CONSOLE_SCREEN_BUFFER_INFO csbi;
2319 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2320 lpScrollRect->Left, lpScrollRect->Top,
2321 lpScrollRect->Right, lpScrollRect->Bottom,
2322 lpClipRect->Left, lpClipRect->Top,
2323 lpClipRect->Right, lpClipRect->Bottom,
2324 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2326 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2327 lpScrollRect->Left, lpScrollRect->Top,
2328 lpScrollRect->Right, lpScrollRect->Bottom,
2329 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2331 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2334 src.X = lpScrollRect->Left;
2335 src.Y = lpScrollRect->Top;
2337 /* step 1: get dst rect */
2338 dst.Left = dwDestOrigin.X;
2339 dst.Top = dwDestOrigin.Y;
2340 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2341 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2343 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2346 clip.Left = max(0, lpClipRect->Left);
2347 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2348 clip.Top = max(0, lpClipRect->Top);
2349 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2354 clip.Right = csbi.dwSize.X - 1;
2356 clip.Bottom = csbi.dwSize.Y - 1;
2358 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2360 /* step 2b: clip dst rect */
2361 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2362 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2363 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2364 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2366 /* step 3: transfer the bits */
2367 SERVER_START_REQ(move_console_output)
2369 req->handle = console_handle_unmap(hConsoleOutput);
2372 req->x_dst = dst.Left;
2373 req->y_dst = dst.Top;
2374 req->w = dst.Right - dst.Left + 1;
2375 req->h = dst.Bottom - dst.Top + 1;
2376 ret = !wine_server_call_err( req );
2380 if (!ret) return FALSE;
2382 /* step 4: clean out the exposed part */
2384 /* have to write cell [i,j] if it is not in dst rect (because it has already
2385 * been written to by the scroll) and is in clip (we shall not write
2388 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2390 inside = dst.Top <= j && j <= dst.Bottom;
2392 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2394 if (inside && dst.Left <= i && i <= dst.Right)
2398 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2404 if (start == -1) start = i;
2408 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2415 /* ====================================================================
2417 * Console manipulation functions
2419 * ====================================================================*/
2421 /* some missing functions...
2422 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2423 * should get the right API and implement them
2424 * GetConsoleCommandHistory[AW] (dword dword dword)
2425 * GetConsoleCommandHistoryLength[AW]
2426 * SetConsoleCommandHistoryMode
2427 * SetConsoleNumberOfCommands[AW]
2429 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2433 SERVER_START_REQ( get_console_input_history )
2437 if (buf && buf_len > 1)
2439 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2441 if (!wine_server_call_err( req ))
2443 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2444 len = reply->total / sizeof(WCHAR) + 1;
2451 /******************************************************************
2452 * CONSOLE_AppendHistory
2456 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2458 size_t len = strlenW(ptr);
2461 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2463 SERVER_START_REQ( append_console_input_history )
2466 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2467 ret = !wine_server_call_err( req );
2473 /******************************************************************
2474 * CONSOLE_GetNumHistoryEntries
2478 unsigned CONSOLE_GetNumHistoryEntries(void)
2481 SERVER_START_REQ(get_console_input_info)
2484 if (!wine_server_call_err( req )) ret = reply->history_index;
2490 /******************************************************************
2491 * CONSOLE_GetEditionMode
2495 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2497 unsigned ret = FALSE;
2498 SERVER_START_REQ(get_console_input_info)
2500 req->handle = console_handle_unmap(hConIn);
2501 if ((ret = !wine_server_call_err( req )))
2502 *mode = reply->edition_mode;