2 * Win32 kernel 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 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;
62 /* map input records to ASCII */
63 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
68 for (i = 0; i < count; i++)
70 if (buffer[i].EventType != KEY_EVENT) continue;
71 WideCharToMultiByte( GetConsoleCP(), 0,
72 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
73 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
77 /* map input records to Unicode */
78 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
83 for (i = 0; i < count; i++)
85 if (buffer[i].EventType != KEY_EVENT) continue;
86 MultiByteToWideChar( GetConsoleCP(), 0,
87 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
88 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
92 /* map char infos to ASCII */
93 static void char_info_WtoA( CHAR_INFO *buffer, int count )
99 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
100 &ch, 1, NULL, NULL );
101 buffer->Char.AsciiChar = ch;
106 /* map char infos to Unicode */
107 static void char_info_AtoW( CHAR_INFO *buffer, int count )
113 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
114 buffer->Char.UnicodeChar = ch;
120 /******************************************************************************
121 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
126 UINT WINAPI GetConsoleCP(VOID)
128 if (!console_input_codepage)
130 console_input_codepage = GetOEMCP();
131 TRACE("%u\n", console_input_codepage);
133 return console_input_codepage;
137 /******************************************************************************
138 * SetConsoleCP [KERNEL32.@]
140 BOOL WINAPI SetConsoleCP(UINT cp)
142 if (!IsValidCodePage( cp )) return FALSE;
143 console_input_codepage = cp;
148 /***********************************************************************
149 * GetConsoleOutputCP (KERNEL32.@)
151 UINT WINAPI GetConsoleOutputCP(VOID)
153 if (!console_output_codepage)
155 console_output_codepage = GetOEMCP();
156 TRACE("%u\n", console_output_codepage);
158 return console_output_codepage;
162 /******************************************************************************
163 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
166 * cp [I] code page to set
172 BOOL WINAPI SetConsoleOutputCP(UINT cp)
174 if (!IsValidCodePage( cp )) return FALSE;
175 console_output_codepage = cp;
180 /***********************************************************************
183 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
185 static const char beep = '\a';
186 /* dwFreq and dwDur are ignored by Win95 */
187 if (isatty(2)) write( 2, &beep, 1 );
192 /******************************************************************
193 * OpenConsoleW (KERNEL32.@)
196 * Open a handle to the current process console.
197 * Returns INVALID_HANDLE_VALUE on failure.
199 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
201 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
202 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
206 if (strcmpiW(coninW, name) == 0)
208 else if (strcmpiW(conoutW, name) == 0)
212 SetLastError(ERROR_INVALID_NAME);
213 return INVALID_HANDLE_VALUE;
215 if (creation != OPEN_EXISTING)
217 SetLastError(ERROR_INVALID_PARAMETER);
218 return INVALID_HANDLE_VALUE;
221 SERVER_START_REQ( open_console )
224 req->access = access;
225 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
226 req->inherit = inherit;
228 wine_server_call_err( req );
232 return ret ? console_handle_map(ret) : INVALID_HANDLE_VALUE;
235 /******************************************************************
236 * VerifyConsoleIoHandle (KERNEL32.@)
240 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
244 if (!is_console_handle(handle)) return FALSE;
245 SERVER_START_REQ(get_console_mode)
247 req->handle = console_handle_unmap(handle);
248 ret = !wine_server_call_err( req );
254 /******************************************************************
255 * DuplicateConsoleHandle (KERNEL32.@)
259 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
264 if (!is_console_handle(handle) ||
265 !DuplicateHandle(GetCurrentProcess(), console_handle_unmap(handle),
266 GetCurrentProcess(), &ret, access, inherit, options))
267 return INVALID_HANDLE_VALUE;
268 return console_handle_map(ret);
271 /******************************************************************
272 * CloseConsoleHandle (KERNEL32.@)
276 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
278 if (!is_console_handle(handle))
280 SetLastError(ERROR_INVALID_PARAMETER);
283 return CloseHandle(console_handle_unmap(handle));
286 /******************************************************************
287 * GetConsoleInputWaitHandle (KERNEL32.@)
291 HANDLE WINAPI GetConsoleInputWaitHandle(void)
293 static HANDLE console_wait_event;
295 /* FIXME: this is not thread safe */
296 if (!console_wait_event)
298 SERVER_START_REQ(get_console_wait_event)
300 if (!wine_server_call_err( req )) console_wait_event = reply->handle;
304 return console_wait_event;
308 /******************************************************************************
309 * WriteConsoleInputA [KERNEL32.@]
311 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
312 DWORD count, LPDWORD written )
317 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
318 memcpy( recW, buffer, count*sizeof(*recW) );
319 input_records_AtoW( recW, count );
320 ret = WriteConsoleInputW( handle, recW, count, written );
321 HeapFree( GetProcessHeap(), 0, recW );
326 /******************************************************************************
327 * WriteConsoleInputW [KERNEL32.@]
329 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
330 DWORD count, LPDWORD written )
334 TRACE("(%p,%p,%ld,%p)\n", handle, buffer, count, written);
336 if (written) *written = 0;
337 SERVER_START_REQ( write_console_input )
339 req->handle = console_handle_unmap(handle);
340 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
341 if ((ret = !wine_server_call_err( req )) && written)
342 *written = reply->written;
350 /***********************************************************************
351 * WriteConsoleOutputA (KERNEL32.@)
353 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
354 COORD size, COORD coord, LPSMALL_RECT region )
358 COORD new_size, new_coord;
361 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
362 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
364 if (new_size.X <= 0 || new_size.Y <= 0)
366 region->Bottom = region->Top + new_size.Y - 1;
367 region->Right = region->Left + new_size.X - 1;
371 /* only copy the useful rectangle */
372 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
374 for (y = 0; y < new_size.Y; y++)
376 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
377 new_size.X * sizeof(CHAR_INFO) );
378 char_info_AtoW( ciw, new_size.X );
380 new_coord.X = new_coord.Y = 0;
381 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
382 if (ciw) HeapFree( GetProcessHeap(), 0, ciw );
387 /***********************************************************************
388 * WriteConsoleOutputW (KERNEL32.@)
390 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
391 COORD size, COORD coord, LPSMALL_RECT region )
393 int width, height, y;
396 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
397 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
398 region->Left, region->Top, region->Right, region->Bottom);
400 width = min( region->Right - region->Left + 1, size.X - coord.X );
401 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
403 if (width > 0 && height > 0)
405 for (y = 0; y < height; y++)
407 SERVER_START_REQ( write_console_output )
409 req->handle = console_handle_unmap(hConsoleOutput);
410 req->x = region->Left;
411 req->y = region->Top + y;
412 req->mode = CHAR_INFO_MODE_TEXTATTR;
414 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
415 width * sizeof(CHAR_INFO));
416 if ((ret = !wine_server_call_err( req )))
418 width = min( width, reply->width - region->Left );
419 height = min( height, reply->height - region->Top );
426 region->Bottom = region->Top + height - 1;
427 region->Right = region->Left + width - 1;
432 /******************************************************************************
433 * WriteConsoleOutputCharacterA [KERNEL32.@] Copies character to consecutive
434 * cells in the console screen buffer
437 * hConsoleOutput [I] Handle to screen buffer
438 * str [I] Pointer to buffer with chars to write
439 * length [I] Number of cells to write to
440 * coord [I] Coords of first cell
441 * lpNumCharsWritten [O] Pointer to number of cells written
443 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
444 COORD coord, LPDWORD lpNumCharsWritten )
450 TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
451 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
453 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
455 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
457 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
458 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
460 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
461 HeapFree( GetProcessHeap(), 0, strW );
466 /******************************************************************************
467 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
468 * the console screen buffer
471 * hConsoleOutput [I] Handle to screen buffer
472 * attr [I] Pointer to buffer with write attributes
473 * length [I] Number of cells to write to
474 * coord [I] Coords of first cell
475 * lpNumAttrsWritten [O] Pointer to number of cells written
482 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
483 COORD coord, LPDWORD lpNumAttrsWritten )
487 TRACE("(%p,%p,%ld,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
489 SERVER_START_REQ( write_console_output )
491 req->handle = console_handle_unmap(hConsoleOutput);
494 req->mode = CHAR_INFO_MODE_ATTR;
496 wine_server_add_data( req, attr, length * sizeof(WORD) );
497 if ((ret = !wine_server_call_err( req )))
499 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
507 /******************************************************************************
508 * FillConsoleOutputCharacterA [KERNEL32.@]
511 * hConsoleOutput [I] Handle to screen buffer
512 * ch [I] Character to write
513 * length [I] Number of cells to write to
514 * coord [I] Coords of first cell
515 * lpNumCharsWritten [O] Pointer to number of cells written
521 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
522 COORD coord, LPDWORD lpNumCharsWritten )
526 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
527 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
531 /******************************************************************************
532 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
535 * hConsoleOutput [I] Handle to screen buffer
536 * ch [I] Character to write
537 * length [I] Number of cells to write to
538 * coord [I] Coords of first cell
539 * lpNumCharsWritten [O] Pointer to number of cells written
545 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
546 COORD coord, LPDWORD lpNumCharsWritten)
550 TRACE("(%p,%s,%ld,(%dx%d),%p)\n",
551 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
553 SERVER_START_REQ( fill_console_output )
555 req->handle = console_handle_unmap(hConsoleOutput);
558 req->mode = CHAR_INFO_MODE_TEXT;
562 if ((ret = !wine_server_call_err( req )))
564 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
572 /******************************************************************************
573 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
576 * hConsoleOutput [I] Handle to screen buffer
577 * attr [I] Color attribute to write
578 * length [I] Number of cells to write to
579 * coord [I] Coords of first cell
580 * lpNumAttrsWritten [O] Pointer to number of cells written
586 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
587 COORD coord, LPDWORD lpNumAttrsWritten )
591 TRACE("(%p,%d,%ld,(%dx%d),%p)\n",
592 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
594 SERVER_START_REQ( fill_console_output )
596 req->handle = console_handle_unmap(hConsoleOutput);
599 req->mode = CHAR_INFO_MODE_ATTR;
601 req->data.attr = attr;
603 if ((ret = !wine_server_call_err( req )))
605 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
613 /******************************************************************************
614 * ReadConsoleOutputCharacterA [KERNEL32.@]
617 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
618 COORD coord, LPDWORD read_count)
622 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
624 if (read_count) *read_count = 0;
625 if (!wptr) return FALSE;
627 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
629 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
630 if (read_count) *read_count = read;
632 HeapFree( GetProcessHeap(), 0, wptr );
637 /******************************************************************************
638 * ReadConsoleOutputCharacterW [KERNEL32.@]
641 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
642 COORD coord, LPDWORD read_count )
646 TRACE( "(%p,%p,%ld,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
648 SERVER_START_REQ( read_console_output )
650 req->handle = console_handle_unmap(hConsoleOutput);
653 req->mode = CHAR_INFO_MODE_TEXT;
655 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
656 if ((ret = !wine_server_call_err( req )))
658 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
666 /******************************************************************************
667 * ReadConsoleOutputAttribute [KERNEL32.@]
669 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
670 COORD coord, LPDWORD read_count)
674 TRACE("(%p,%p,%ld,%dx%d,%p)\n",
675 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
677 SERVER_START_REQ( read_console_output )
679 req->handle = console_handle_unmap(hConsoleOutput);
682 req->mode = CHAR_INFO_MODE_ATTR;
684 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
685 if ((ret = !wine_server_call_err( req )))
687 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
695 /******************************************************************************
696 * ReadConsoleOutputA [KERNEL32.@]
699 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
700 COORD coord, LPSMALL_RECT region )
705 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
706 if (ret && region->Right >= region->Left)
708 for (y = 0; y <= region->Bottom - region->Top; y++)
710 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
711 region->Right - region->Left + 1 );
718 /******************************************************************************
719 * ReadConsoleOutputW [KERNEL32.@]
721 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
722 * think we need to be *that* compatible. -- AJ
724 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
725 COORD coord, LPSMALL_RECT region )
727 int width, height, y;
730 width = min( region->Right - region->Left + 1, size.X - coord.X );
731 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
733 if (width > 0 && height > 0)
735 for (y = 0; y < height; y++)
737 SERVER_START_REQ( read_console_output )
739 req->handle = console_handle_unmap(hConsoleOutput);
740 req->x = region->Left;
741 req->y = region->Top + y;
742 req->mode = CHAR_INFO_MODE_TEXTATTR;
744 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
745 width * sizeof(CHAR_INFO) );
746 if ((ret = !wine_server_call_err( req )))
748 width = min( width, reply->width - region->Left );
749 height = min( height, reply->height - region->Top );
756 region->Bottom = region->Top + height - 1;
757 region->Right = region->Left + width - 1;
762 /******************************************************************************
763 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
766 * handle [I] Handle to console input buffer
767 * buffer [O] Address of buffer for read data
768 * count [I] Number of records to read
769 * pRead [O] Address of number of records read
775 BOOL WINAPI ReadConsoleInputA( HANDLE handle, LPINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
779 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
780 input_records_WtoA( buffer, read );
781 if (pRead) *pRead = read;
786 /***********************************************************************
787 * PeekConsoleInputA (KERNEL32.@)
789 * Gets 'count' first events (or less) from input queue.
791 BOOL WINAPI PeekConsoleInputA( HANDLE handle, LPINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
795 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
796 input_records_WtoA( buffer, read );
797 if (pRead) *pRead = read;
802 /***********************************************************************
803 * PeekConsoleInputW (KERNEL32.@)
805 BOOL WINAPI PeekConsoleInputW( HANDLE handle, LPINPUT_RECORD buffer, DWORD count, LPDWORD read )
808 SERVER_START_REQ( read_console_input )
810 req->handle = console_handle_unmap(handle);
812 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
813 if ((ret = !wine_server_call_err( req )))
815 if (read) *read = count ? reply->read : 0;
823 /***********************************************************************
824 * GetNumberOfConsoleInputEvents (KERNEL32.@)
826 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
829 SERVER_START_REQ( read_console_input )
831 req->handle = console_handle_unmap(handle);
833 if ((ret = !wine_server_call_err( req )))
835 if (nrofevents) *nrofevents = reply->read;
843 /******************************************************************************
846 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
849 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
851 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
852 static enum read_console_input_return read_console_input(HANDLE handle, LPINPUT_RECORD ir, DWORD timeout)
854 enum read_console_input_return ret;
856 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
858 SERVER_START_REQ( read_console_input )
860 req->handle = console_handle_unmap(handle);
862 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
863 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
864 else ret = rci_gotone;
872 /***********************************************************************
873 * FlushConsoleInputBuffer (KERNEL32.@)
875 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
877 enum read_console_input_return last;
880 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
882 return last == rci_timeout;
886 /***********************************************************************
887 * SetConsoleTitleA (KERNEL32.@)
889 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
894 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
895 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
896 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
897 ret = SetConsoleTitleW(titleW);
898 HeapFree(GetProcessHeap(), 0, titleW);
903 /***********************************************************************
904 * GetConsoleTitleA (KERNEL32.@)
906 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
908 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
912 ret = GetConsoleTitleW( ptr, size );
915 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
918 HeapFree(GetProcessHeap(), 0, ptr);
923 /******************************************************************************
924 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
927 * title [O] Address of buffer for title
928 * size [I] Size of buffer
931 * Success: Length of string copied
934 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
938 SERVER_START_REQ( get_console_input_info )
941 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
942 if (!wine_server_call_err( req ))
944 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
953 /***********************************************************************
954 * GetLargestConsoleWindowSize (KERNEL32.@)
957 * This should return a COORD, but calling convention for returning
958 * structures is different between Windows and gcc on i386.
963 #undef GetLargestConsoleWindowSize
964 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
972 TRACE("(%p), returning %dx%d (%lx)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
975 #endif /* defined(__i386__) */
978 /***********************************************************************
979 * GetLargestConsoleWindowSize (KERNEL32.@)
982 * This should return a COORD, but calling convention for returning
983 * structures is different between Windows and gcc on i386.
988 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
993 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, x.Y);
996 #endif /* defined(__i386__) */
998 static WCHAR* S_EditString /* = NULL */;
999 static unsigned S_EditStrPos /* = 0 */;
1001 /***********************************************************************
1002 * FreeConsole (KERNEL32.@)
1004 BOOL WINAPI FreeConsole(VOID)
1008 SERVER_START_REQ(free_console)
1010 ret = !wine_server_call_err( req );
1016 /******************************************************************
1017 * start_console_renderer
1019 * helper for AllocConsole
1020 * starts the renderer process
1022 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1027 PROCESS_INFORMATION pi;
1029 /* FIXME: use dynamic allocation for most of the buffers below */
1030 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%d", appname, (INT)hEvent);
1031 if ((ret > -1) && (ret < sizeof(buffer)) &&
1032 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1033 NULL, NULL, si, &pi))
1035 if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
1037 TRACE("Started wineconsole pid=%08lx tid=%08lx\n",
1038 pi.dwProcessId, pi.dwThreadId);
1045 static BOOL start_console_renderer(STARTUPINFOA* si)
1049 OBJECT_ATTRIBUTES attr;
1052 attr.Length = sizeof(attr);
1053 attr.RootDirectory = 0;
1054 attr.Attributes = OBJ_INHERIT;
1055 attr.ObjectName = NULL;
1056 attr.SecurityDescriptor = NULL;
1057 attr.SecurityQualityOfService = NULL;
1059 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
1060 if (!hEvent) return FALSE;
1062 /* first try environment variable */
1063 if ((p = getenv("WINECONSOLE")) != NULL)
1065 ret = start_console_renderer_helper(p, si, hEvent);
1067 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1068 "trying default access\n", p);
1071 /* then try the regular PATH */
1073 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1075 CloseHandle(hEvent);
1079 /***********************************************************************
1080 * AllocConsole (KERNEL32.@)
1082 * creates an xterm with a pty to our program
1084 BOOL WINAPI AllocConsole(void)
1086 HANDLE handle_in = INVALID_HANDLE_VALUE;
1087 HANDLE handle_out = INVALID_HANDLE_VALUE;
1088 HANDLE handle_err = INVALID_HANDLE_VALUE;
1089 STARTUPINFOA siCurrent;
1090 STARTUPINFOA siConsole;
1092 SECURITY_ATTRIBUTES sa;
1096 handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1097 0, NULL, OPEN_EXISTING, 0, 0 );
1099 if (handle_in != INVALID_HANDLE_VALUE)
1101 /* we already have a console opened on this process, don't create a new one */
1102 CloseHandle(handle_in);
1106 GetStartupInfoA(&siCurrent);
1108 memset(&siConsole, 0, sizeof(siConsole));
1109 siConsole.cb = sizeof(siConsole);
1110 /* setup a view arguments for wineconsole (it'll use them as default values) */
1111 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1113 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1114 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1115 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1117 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1119 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1120 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1122 /* FIXME (should pass the unicode form) */
1123 if (siCurrent.lpTitle)
1124 siConsole.lpTitle = siCurrent.lpTitle;
1125 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1126 siConsole.lpTitle = buffer;
1128 if (!start_console_renderer(&siConsole))
1131 /* all std I/O handles are inheritable by default */
1132 sa.nLength = sizeof(sa);
1133 sa.lpSecurityDescriptor = NULL;
1134 sa.bInheritHandle = TRUE;
1136 handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1137 0, &sa, OPEN_EXISTING, 0, 0 );
1138 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1140 handle_out = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE,
1141 0, &sa, OPEN_EXISTING, 0, 0 );
1142 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1144 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(), &handle_err,
1145 0, TRUE, DUPLICATE_SAME_ACCESS))
1148 /* NT resets the STD_*_HANDLEs on console alloc */
1149 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1150 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1151 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1153 SetLastError(ERROR_SUCCESS);
1158 ERR("Can't allocate console\n");
1159 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1160 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1161 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1167 /***********************************************************************
1168 * ReadConsoleA (KERNEL32.@)
1170 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1171 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1173 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1177 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1178 ncr = WideCharToMultiByte(CP_ACP, 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1180 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1181 HeapFree(GetProcessHeap(), 0, ptr);
1186 /***********************************************************************
1187 * ReadConsoleW (KERNEL32.@)
1189 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1190 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1193 LPWSTR xbuf = (LPWSTR)lpBuffer;
1196 TRACE("(%p,%p,%ld,%p,%p)\n",
1197 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1199 if (!GetConsoleMode(hConsoleInput, &mode))
1202 if (mode & ENABLE_LINE_INPUT)
1204 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1206 if (S_EditString) HeapFree(GetProcessHeap(), 0, S_EditString);
1207 if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1211 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1212 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1213 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1214 S_EditStrPos += charsread;
1219 DWORD timeout = INFINITE;
1221 /* FIXME: should we read at least 1 char? The SDK does not say */
1222 /* wait for at least one available input record (it doesn't mean we'll have
1223 * chars stored in xbuf...)
1228 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1230 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1231 ir.Event.KeyEvent.uChar.UnicodeChar &&
1232 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
1234 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1236 } while (charsread < nNumberOfCharsToRead);
1237 /* nothing has been read */
1238 if (timeout == INFINITE) return FALSE;
1241 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1247 /***********************************************************************
1248 * ReadConsoleInputW (KERNEL32.@)
1250 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, LPINPUT_RECORD lpBuffer,
1251 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1254 DWORD timeout = INFINITE;
1258 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1262 /* loop until we get at least one event */
1263 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1267 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1272 /******************************************************************************
1273 * WriteConsoleOutputCharacterW [KERNEL32.@] Copies character to consecutive
1274 * cells in the console screen buffer
1277 * hConsoleOutput [I] Handle to screen buffer
1278 * str [I] Pointer to buffer with chars to write
1279 * length [I] Number of cells to write to
1280 * coord [I] Coords of first cell
1281 * lpNumCharsWritten [O] Pointer to number of cells written
1288 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1289 COORD coord, LPDWORD lpNumCharsWritten )
1293 TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
1294 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1296 SERVER_START_REQ( write_console_output )
1298 req->handle = console_handle_unmap(hConsoleOutput);
1301 req->mode = CHAR_INFO_MODE_TEXT;
1303 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1304 if ((ret = !wine_server_call_err( req )))
1306 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1314 /******************************************************************************
1315 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1318 * title [I] Address of new title
1324 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1328 TRACE("(%s)\n", debugstr_w(title));
1329 SERVER_START_REQ( set_console_input_info )
1332 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1333 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1334 ret = !wine_server_call_err( req );
1341 /***********************************************************************
1342 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1344 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1346 FIXME("(%p): stub\n", nrofbuttons);
1351 /******************************************************************************
1352 * SetConsoleInputExeNameW [KERNEL32.@]
1357 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1359 FIXME("(%s): stub!\n", debugstr_w(name));
1361 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1365 /******************************************************************************
1366 * SetConsoleInputExeNameA [KERNEL32.@]
1371 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1373 int len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1374 LPWSTR xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1377 if (!xptr) return FALSE;
1379 MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
1380 ret = SetConsoleInputExeNameW(xptr);
1381 HeapFree(GetProcessHeap(), 0, xptr);
1386 /******************************************************************
1387 * CONSOLE_DefaultHandler
1389 * Final control event handler
1391 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1393 FIXME("Terminating process %lx on event %lx\n", GetCurrentProcessId(), dwCtrlType);
1395 /* should never go here */
1399 /******************************************************************************
1400 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1403 * func [I] Address of handler function
1404 * add [I] Handler to add or remove
1411 * James Sutherland (JamesSutherland@gmx.de)
1412 * Added global variables console_ignore_ctrl_c and handlers[]
1413 * Does not yet do any error checking, or set LastError if failed.
1414 * This doesn't yet matter, since these handlers are not yet called...!
1417 struct ConsoleHandler {
1418 PHANDLER_ROUTINE handler;
1419 struct ConsoleHandler* next;
1422 static unsigned int CONSOLE_IgnoreCtrlC = 0; /* FIXME: this should be inherited somehow */
1423 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1424 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1426 static CRITICAL_SECTION CONSOLE_CritSect;
1427 static CRITICAL_SECTION_DEBUG critsect_debug =
1429 0, 0, &CONSOLE_CritSect,
1430 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
1431 0, 0, { 0, (DWORD)(__FILE__ ": CONSOLE_CritSect") }
1433 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
1435 /*****************************************************************************/
1437 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1441 FIXME("(%p,%i) - no error checking or testing yet\n", func, add);
1445 CONSOLE_IgnoreCtrlC = add;
1449 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1451 if (!ch) return FALSE;
1453 RtlEnterCriticalSection(&CONSOLE_CritSect);
1454 ch->next = CONSOLE_Handlers;
1455 CONSOLE_Handlers = ch;
1456 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1460 struct ConsoleHandler** ch;
1461 RtlEnterCriticalSection(&CONSOLE_CritSect);
1462 for (ch = &CONSOLE_Handlers; *ch; *ch = (*ch)->next)
1464 if ((*ch)->handler == func) break;
1468 struct ConsoleHandler* rch = *ch;
1471 if (rch == &CONSOLE_DefaultConsoleHandler)
1473 ERR("Who's trying to remove default handler???\n");
1480 HeapFree(GetProcessHeap(), 0, rch);
1485 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1488 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1493 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
1495 TRACE("(%lx)\n", GetExceptionCode());
1496 return EXCEPTION_EXECUTE_HANDLER;
1499 static DWORD WINAPI CONSOLE_HandleCtrlCEntry(void* pmt)
1501 struct ConsoleHandler* ch;
1503 RtlEnterCriticalSection(&CONSOLE_CritSect);
1504 /* the debugger didn't continue... so, pass to ctrl handlers */
1505 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1507 if (ch->handler((DWORD)pmt)) break;
1509 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1513 /******************************************************************
1514 * CONSOLE_HandleCtrlC
1516 * Check whether the shall manipulate CtrlC events
1518 int CONSOLE_HandleCtrlC(unsigned sig)
1520 /* FIXME: better test whether a console is attached to this process ??? */
1521 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1522 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1523 if (CONSOLE_IgnoreCtrlC) return 1;
1525 /* try to pass the exception to the debugger
1526 * if it continues, there's nothing more to do
1527 * otherwise, we need to send the ctrl-event to the handlers
1531 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1533 __EXCEPT(CONSOLE_CtrlEventHandler)
1535 /* Create a separate thread to signal all the events. This would allow to
1536 * synchronize between setting the handlers and actually calling them
1538 CreateThread(NULL, 0, CONSOLE_HandleCtrlCEntry, (void*)CTRL_C_EVENT, 0, NULL);
1544 /******************************************************************************
1545 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1548 * dwCtrlEvent [I] Type of event
1549 * dwProcessGroupID [I] Process group ID to send event to
1553 * Failure: False (and *should* [but doesn't] set LastError)
1555 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1556 DWORD dwProcessGroupID)
1560 TRACE("(%ld, %ld)\n", dwCtrlEvent, dwProcessGroupID);
1562 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1564 ERR("Invalid event %ld for PGID %ld\n", dwCtrlEvent, dwProcessGroupID);
1568 SERVER_START_REQ( send_console_signal )
1570 req->signal = dwCtrlEvent;
1571 req->group_id = dwProcessGroupID;
1572 ret = !wine_server_call_err( req );
1580 /******************************************************************************
1581 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
1584 * dwDesiredAccess [I] Access flag
1585 * dwShareMode [I] Buffer share mode
1586 * sa [I] Security attributes
1587 * dwFlags [I] Type of buffer to create
1588 * lpScreenBufferData [I] Reserved
1591 * Should call SetLastError
1594 * Success: Handle to new console screen buffer
1595 * Failure: INVALID_HANDLE_VALUE
1597 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1598 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1599 LPVOID lpScreenBufferData)
1601 HANDLE ret = INVALID_HANDLE_VALUE;
1603 TRACE("(%ld,%ld,%p,%ld,%p)\n",
1604 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1606 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1608 SetLastError(ERROR_INVALID_PARAMETER);
1609 return INVALID_HANDLE_VALUE;
1612 SERVER_START_REQ(create_console_output)
1615 req->access = dwDesiredAccess;
1616 req->share = dwShareMode;
1617 req->inherit = (sa && sa->bInheritHandle);
1618 if (!wine_server_call_err( req )) ret = reply->handle_out;
1626 /***********************************************************************
1627 * GetConsoleScreenBufferInfo (KERNEL32.@)
1629 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1633 SERVER_START_REQ(get_console_output_info)
1635 req->handle = console_handle_unmap(hConsoleOutput);
1636 if ((ret = !wine_server_call_err( req )))
1638 csbi->dwSize.X = reply->width;
1639 csbi->dwSize.Y = reply->height;
1640 csbi->dwCursorPosition.X = reply->cursor_x;
1641 csbi->dwCursorPosition.Y = reply->cursor_y;
1642 csbi->wAttributes = reply->attr;
1643 csbi->srWindow.Left = reply->win_left;
1644 csbi->srWindow.Right = reply->win_right;
1645 csbi->srWindow.Top = reply->win_top;
1646 csbi->srWindow.Bottom = reply->win_bottom;
1647 csbi->dwMaximumWindowSize.X = reply->max_width;
1648 csbi->dwMaximumWindowSize.Y = reply->max_height;
1653 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
1654 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1655 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1657 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1658 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1664 /******************************************************************************
1665 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
1671 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1675 TRACE("(%p)\n", hConsoleOutput);
1677 SERVER_START_REQ( set_console_input_info )
1680 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1681 req->active_sb = hConsoleOutput;
1682 ret = !wine_server_call_err( req );
1689 /***********************************************************************
1690 * GetConsoleMode (KERNEL32.@)
1692 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1696 SERVER_START_REQ(get_console_mode)
1698 req->handle = console_handle_unmap(hcon);
1699 ret = !wine_server_call_err( req );
1700 if (ret && mode) *mode = reply->mode;
1707 /******************************************************************************
1708 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
1711 * hcon [I] Handle to console input or screen buffer
1712 * mode [I] Input or output mode to set
1719 * ENABLE_PROCESSED_INPUT 0x01
1720 * ENABLE_LINE_INPUT 0x02
1721 * ENABLE_ECHO_INPUT 0x04
1722 * ENABLE_WINDOW_INPUT 0x08
1723 * ENABLE_MOUSE_INPUT 0x10
1725 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1729 SERVER_START_REQ(set_console_mode)
1731 req->handle = console_handle_unmap(hcon);
1733 ret = !wine_server_call_err( req );
1736 /* FIXME: when resetting a console input to editline mode, I think we should
1737 * empty the S_EditString buffer
1740 TRACE("(%p,%lx) retval == %d\n", hcon, mode, ret);
1746 /******************************************************************
1747 * CONSOLE_WriteChars
1749 * WriteConsoleOutput helper: hides server call semantics
1750 * writes a string at a given pos with standard attribute
1752 int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1758 SERVER_START_REQ( write_console_output )
1760 req->handle = console_handle_unmap(hCon);
1763 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1765 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1766 if (!wine_server_call_err( req )) written = reply->written;
1770 if (written > 0) pos->X += written;
1774 /******************************************************************
1777 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1780 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1786 csbi->dwCursorPosition.X = 0;
1787 csbi->dwCursorPosition.Y++;
1789 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1792 src.Bottom = csbi->dwSize.Y - 1;
1794 src.Right = csbi->dwSize.X - 1;
1799 ci.Attributes = csbi->wAttributes;
1800 ci.Char.UnicodeChar = ' ';
1802 csbi->dwCursorPosition.Y--;
1803 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1808 /******************************************************************
1811 * WriteConsoleOutput helper: writes a block of non special characters
1812 * Block can spread on several lines, and wrapping, if needed, is
1816 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1817 DWORD mode, LPWSTR ptr, int len)
1819 int blk; /* number of chars to write on current line */
1820 int done; /* number of chars already written */
1822 if (len <= 0) return 1;
1824 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1826 for (done = 0; done < len; done += blk)
1828 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1830 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1832 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
1838 int pos = csbi->dwCursorPosition.X;
1839 /* FIXME: we could reduce the number of loops
1840 * but, in most cases we wouldn't gain lots of time (it would only
1841 * happen if we're asked to overwrite more than twice the part of the line,
1844 for (blk = done = 0; done < len; done += blk)
1846 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1848 csbi->dwCursorPosition.X = pos;
1849 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1857 /***********************************************************************
1858 * WriteConsoleW (KERNEL32.@)
1860 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1861 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1865 WCHAR* psz = (WCHAR*)lpBuffer;
1866 CONSOLE_SCREEN_BUFFER_INFO csbi;
1869 TRACE("%p %s %ld %p %p\n",
1870 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
1871 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
1873 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1875 if (!GetConsoleMode(hConsoleOutput, &mode) ||
1876 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1879 if (mode & ENABLE_PROCESSED_OUTPUT)
1883 for (i = 0; i < nNumberOfCharsToWrite; i++)
1887 case '\b': case '\t': case '\n': case '\a': case '\r':
1888 /* don't handle here the i-th char... done below */
1889 if ((k = i - first) > 0)
1891 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1901 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
1905 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
1907 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
1908 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
1913 next_line(hConsoleOutput, &csbi);
1919 csbi.dwCursorPosition.X = 0;
1927 /* write the remaining block (if any) if processed output is enabled, or the
1928 * entire buffer otherwise
1930 if ((k = nNumberOfCharsToWrite - first) > 0)
1932 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1938 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
1939 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
1944 /***********************************************************************
1945 * WriteConsoleA (KERNEL32.@)
1947 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1948 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1954 n = MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
1956 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1957 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
1958 if (!xstring) return 0;
1960 MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
1962 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
1964 HeapFree(GetProcessHeap(), 0, xstring);
1969 /******************************************************************************
1970 * SetConsoleCursorPosition [KERNEL32.@]
1971 * Sets the cursor position in console
1974 * hConsoleOutput [I] Handle of console screen buffer
1975 * dwCursorPosition [I] New cursor position coordinates
1979 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
1982 CONSOLE_SCREEN_BUFFER_INFO csbi;
1986 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
1988 SERVER_START_REQ(set_console_output_info)
1990 req->handle = console_handle_unmap(hcon);
1991 req->cursor_x = pos.X;
1992 req->cursor_y = pos.Y;
1993 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
1994 ret = !wine_server_call_err( req );
1998 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2001 /* if cursor is no longer visible, scroll the visible window... */
2002 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2003 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2004 if (pos.X < csbi.srWindow.Left)
2006 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2009 else if (pos.X > csbi.srWindow.Right)
2011 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2014 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2016 if (pos.Y < csbi.srWindow.Top)
2018 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2021 else if (pos.Y > csbi.srWindow.Bottom)
2023 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2026 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2028 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2033 /******************************************************************************
2034 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2037 * hcon [I] Handle to console screen buffer
2038 * cinfo [O] Address of cursor information
2044 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2048 SERVER_START_REQ(get_console_output_info)
2050 req->handle = console_handle_unmap(hCon);
2051 ret = !wine_server_call_err( req );
2054 cinfo->dwSize = reply->cursor_size;
2055 cinfo->bVisible = reply->cursor_visible;
2060 TRACE("(%p) returning (%ld,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2065 /******************************************************************************
2066 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2069 * hcon [I] Handle to console screen buffer
2070 * cinfo [I] Address of cursor information
2075 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2079 TRACE("(%p,%ld,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2080 SERVER_START_REQ(set_console_output_info)
2082 req->handle = console_handle_unmap(hCon);
2083 req->cursor_size = cinfo->dwSize;
2084 req->cursor_visible = cinfo->bVisible;
2085 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2086 ret = !wine_server_call_err( req );
2093 /******************************************************************************
2094 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2097 * hcon [I] Handle to console screen buffer
2098 * bAbsolute [I] Coordinate type flag
2099 * window [I] Address of new window rectangle
2104 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2106 SMALL_RECT p = *window;
2109 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2113 CONSOLE_SCREEN_BUFFER_INFO csbi;
2115 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2117 p.Left += csbi.srWindow.Left;
2118 p.Top += csbi.srWindow.Top;
2119 p.Right += csbi.srWindow.Right;
2120 p.Bottom += csbi.srWindow.Bottom;
2122 SERVER_START_REQ(set_console_output_info)
2124 req->handle = console_handle_unmap(hCon);
2125 req->win_left = p.Left;
2126 req->win_top = p.Top;
2127 req->win_right = p.Right;
2128 req->win_bottom = p.Bottom;
2129 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2130 ret = !wine_server_call_err( req );
2138 /******************************************************************************
2139 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2141 * Sets the foreground and background color attributes of characters
2142 * written to the screen buffer.
2148 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2152 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2153 SERVER_START_REQ(set_console_output_info)
2155 req->handle = console_handle_unmap(hConsoleOutput);
2157 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2158 ret = !wine_server_call_err( req );
2165 /******************************************************************************
2166 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2169 * hConsoleOutput [I] Handle to console screen buffer
2170 * dwSize [I] New size in character rows and cols
2176 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2180 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2181 SERVER_START_REQ(set_console_output_info)
2183 req->handle = console_handle_unmap(hConsoleOutput);
2184 req->width = dwSize.X;
2185 req->height = dwSize.Y;
2186 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2187 ret = !wine_server_call_err( req );
2194 /******************************************************************************
2195 * ScrollConsoleScreenBufferA [KERNEL32.@]
2198 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2199 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2204 ciw.Attributes = lpFill->Attributes;
2205 MultiByteToWideChar(CP_ACP, 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2207 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2208 dwDestOrigin, &ciw);
2211 /******************************************************************
2212 * CONSOLE_FillLineUniform
2214 * Helper function for ScrollConsoleScreenBufferW
2215 * Fills a part of a line with a constant character info
2217 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2219 SERVER_START_REQ( fill_console_output )
2221 req->handle = console_handle_unmap(hConsoleOutput);
2222 req->mode = CHAR_INFO_MODE_TEXTATTR;
2227 req->data.ch = lpFill->Char.UnicodeChar;
2228 req->data.attr = lpFill->Attributes;
2229 wine_server_call_err( req );
2234 /******************************************************************************
2235 * ScrollConsoleScreenBufferW [KERNEL32.@]
2239 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2240 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2248 CONSOLE_SCREEN_BUFFER_INFO csbi;
2252 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2253 lpScrollRect->Left, lpScrollRect->Top,
2254 lpScrollRect->Right, lpScrollRect->Bottom,
2255 lpClipRect->Left, lpClipRect->Top,
2256 lpClipRect->Right, lpClipRect->Bottom,
2257 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2259 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2260 lpScrollRect->Left, lpScrollRect->Top,
2261 lpScrollRect->Right, lpScrollRect->Bottom,
2262 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2264 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2267 /* step 1: get dst rect */
2268 dst.Left = dwDestOrigin.X;
2269 dst.Top = dwDestOrigin.Y;
2270 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2271 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2273 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2276 clip.Left = max(0, lpClipRect->Left);
2277 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2278 clip.Top = max(0, lpClipRect->Top);
2279 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2284 clip.Right = csbi.dwSize.X - 1;
2286 clip.Bottom = csbi.dwSize.Y - 1;
2288 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2290 /* step 2b: clip dst rect */
2291 if (dst.Left < clip.Left ) dst.Left = clip.Left;
2292 if (dst.Top < clip.Top ) dst.Top = clip.Top;
2293 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2294 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2296 /* step 3: transfer the bits */
2297 SERVER_START_REQ(move_console_output)
2299 req->handle = console_handle_unmap(hConsoleOutput);
2300 req->x_src = lpScrollRect->Left;
2301 req->y_src = lpScrollRect->Top;
2302 req->x_dst = dst.Left;
2303 req->y_dst = dst.Top;
2304 req->w = dst.Right - dst.Left + 1;
2305 req->h = dst.Bottom - dst.Top + 1;
2306 ret = !wine_server_call_err( req );
2310 if (!ret) return FALSE;
2312 /* step 4: clean out the exposed part */
2314 /* have to write cell [i,j] if it is not in dst rect (because it has already
2315 * been written to by the scroll) and is in clip (we shall not write
2318 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2320 inside = dst.Top <= j && j <= dst.Bottom;
2322 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2324 if (inside && dst.Left <= i && i <= dst.Right)
2328 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2334 if (start == -1) start = i;
2338 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2345 /* ====================================================================
2347 * Console manipulation functions
2349 * ====================================================================*/
2351 /* some missing functions...
2352 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2353 * should get the right API and implement them
2354 * GetConsoleCommandHistory[AW] (dword dword dword)
2355 * GetConsoleCommandHistoryLength[AW]
2356 * SetConsoleCommandHistoryMode
2357 * SetConsoleNumberOfCommands[AW]
2359 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2363 SERVER_START_REQ( get_console_input_history )
2367 if (buf && buf_len > 1)
2369 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2371 if (!wine_server_call_err( req ))
2373 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2374 len = reply->total / sizeof(WCHAR) + 1;
2381 /******************************************************************
2382 * CONSOLE_AppendHistory
2386 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2388 size_t len = strlenW(ptr);
2391 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2393 SERVER_START_REQ( append_console_input_history )
2396 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2397 ret = !wine_server_call_err( req );
2403 /******************************************************************
2404 * CONSOLE_GetNumHistoryEntries
2408 unsigned CONSOLE_GetNumHistoryEntries(void)
2411 SERVER_START_REQ(get_console_input_info)
2414 if (!wine_server_call_err( req )) ret = reply->history_index;
2420 /******************************************************************
2421 * CONSOLE_GetEditionMode
2425 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2427 unsigned ret = FALSE;
2428 SERVER_START_REQ(get_console_input_info)
2430 req->handle = console_handle_unmap(hConIn);
2431 if ((ret = !wine_server_call_err( req )))
2432 *mode = reply->edition_mode;