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) console_input_codepage = GetOEMCP();
129 return console_input_codepage;
133 /******************************************************************************
134 * SetConsoleCP [KERNEL32.@]
136 BOOL WINAPI SetConsoleCP(UINT cp)
138 if (!IsValidCodePage( cp )) return FALSE;
139 console_input_codepage = cp;
144 /***********************************************************************
145 * GetConsoleOutputCP (KERNEL32.@)
147 UINT WINAPI GetConsoleOutputCP(VOID)
149 if (!console_output_codepage) console_output_codepage = GetOEMCP();
150 return console_output_codepage;
154 /******************************************************************************
155 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
158 * cp [I] code page to set
164 BOOL WINAPI SetConsoleOutputCP(UINT cp)
166 if (!IsValidCodePage( cp )) return FALSE;
167 console_output_codepage = cp;
172 /***********************************************************************
175 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
177 static const char beep = '\a';
178 /* dwFreq and dwDur are ignored by Win95 */
179 if (isatty(2)) write( 2, &beep, 1 );
184 /******************************************************************
185 * OpenConsoleW (KERNEL32.@)
188 * Open a handle to the current process console.
189 * Returns INVALID_HANDLE_VALUE on failure.
191 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
193 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
194 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
198 if (strcmpiW(coninW, name) == 0)
200 else if (strcmpiW(conoutW, name) == 0)
204 SetLastError(ERROR_INVALID_NAME);
205 return INVALID_HANDLE_VALUE;
207 if (creation != OPEN_EXISTING)
209 SetLastError(ERROR_INVALID_PARAMETER);
210 return INVALID_HANDLE_VALUE;
213 SERVER_START_REQ( open_console )
216 req->access = access;
217 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
218 req->inherit = inherit;
220 wine_server_call_err( req );
224 return ret ? console_handle_map(ret) : INVALID_HANDLE_VALUE;
227 /******************************************************************
228 * VerifyConsoleIoHandle (KERNEL32.@)
232 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
236 if (!is_console_handle(handle)) return FALSE;
237 SERVER_START_REQ(get_console_mode)
239 req->handle = console_handle_unmap(handle);
240 ret = !wine_server_call_err( req );
246 /******************************************************************
247 * DuplicateConsoleHandle (KERNEL32.@)
251 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
256 if (!is_console_handle(handle) ||
257 !DuplicateHandle(GetCurrentProcess(), console_handle_unmap(handle),
258 GetCurrentProcess(), &ret, access, inherit, options))
259 return INVALID_HANDLE_VALUE;
260 return console_handle_map(ret);
263 /******************************************************************
264 * CloseConsoleHandle (KERNEL32.@)
268 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
270 if (!is_console_handle(handle))
272 SetLastError(ERROR_INVALID_PARAMETER);
275 return CloseHandle(console_handle_unmap(handle));
278 /******************************************************************
279 * GetConsoleInputWaitHandle (KERNEL32.@)
283 HANDLE WINAPI GetConsoleInputWaitHandle(void)
285 static HANDLE console_wait_event;
287 /* FIXME: this is not thread safe */
288 if (!console_wait_event)
290 SERVER_START_REQ(get_console_wait_event)
292 if (!wine_server_call_err( req )) console_wait_event = reply->handle;
296 return console_wait_event;
300 /******************************************************************************
301 * WriteConsoleInputA [KERNEL32.@]
303 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
304 DWORD count, LPDWORD written )
309 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
310 memcpy( recW, buffer, count*sizeof(*recW) );
311 input_records_AtoW( recW, count );
312 ret = WriteConsoleInputW( handle, recW, count, written );
313 HeapFree( GetProcessHeap(), 0, recW );
318 /******************************************************************************
319 * WriteConsoleInputW [KERNEL32.@]
321 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
322 DWORD count, LPDWORD written )
326 TRACE("(%p,%p,%ld,%p)\n", handle, buffer, count, written);
328 if (written) *written = 0;
329 SERVER_START_REQ( write_console_input )
331 req->handle = console_handle_unmap(handle);
332 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
333 if ((ret = !wine_server_call_err( req )) && written)
334 *written = reply->written;
342 /***********************************************************************
343 * WriteConsoleOutputA (KERNEL32.@)
345 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
346 COORD size, COORD coord, LPSMALL_RECT region )
350 COORD new_size, new_coord;
353 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
354 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
356 if (new_size.X <= 0 || new_size.Y <= 0)
358 region->Bottom = region->Top + new_size.Y - 1;
359 region->Right = region->Left + new_size.X - 1;
363 /* only copy the useful rectangle */
364 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
366 for (y = 0; y < new_size.Y; y++)
368 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
369 new_size.X * sizeof(CHAR_INFO) );
370 char_info_AtoW( ciw, new_size.X );
372 new_coord.X = new_coord.Y = 0;
373 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
374 if (ciw) HeapFree( GetProcessHeap(), 0, ciw );
379 /***********************************************************************
380 * WriteConsoleOutputW (KERNEL32.@)
382 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
383 COORD size, COORD coord, LPSMALL_RECT region )
385 int width, height, y;
388 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
389 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
390 region->Left, region->Top, region->Right, region->Bottom);
392 width = min( region->Right - region->Left + 1, size.X - coord.X );
393 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
395 if (width > 0 && height > 0)
397 for (y = 0; y < height; y++)
399 SERVER_START_REQ( write_console_output )
401 req->handle = console_handle_unmap(hConsoleOutput);
402 req->x = region->Left;
403 req->y = region->Top + y;
404 req->mode = CHAR_INFO_MODE_TEXTATTR;
406 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
407 width * sizeof(CHAR_INFO));
408 if ((ret = !wine_server_call_err( req )))
410 width = min( width, reply->width - region->Left );
411 height = min( height, reply->height - region->Top );
418 region->Bottom = region->Top + height - 1;
419 region->Right = region->Left + width - 1;
424 /******************************************************************************
425 * WriteConsoleOutputCharacterA [KERNEL32.@] Copies character to consecutive
426 * cells in the console screen buffer
429 * hConsoleOutput [I] Handle to screen buffer
430 * str [I] Pointer to buffer with chars to write
431 * length [I] Number of cells to write to
432 * coord [I] Coords of first cell
433 * lpNumCharsWritten [O] Pointer to number of cells written
435 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
436 COORD coord, LPDWORD lpNumCharsWritten )
442 TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
443 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
445 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
447 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
449 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
450 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
452 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
453 HeapFree( GetProcessHeap(), 0, strW );
458 /******************************************************************************
459 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
460 * the console screen buffer
463 * hConsoleOutput [I] Handle to screen buffer
464 * attr [I] Pointer to buffer with write attributes
465 * length [I] Number of cells to write to
466 * coord [I] Coords of first cell
467 * lpNumAttrsWritten [O] Pointer to number of cells written
474 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
475 COORD coord, LPDWORD lpNumAttrsWritten )
479 TRACE("(%p,%p,%ld,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
481 SERVER_START_REQ( write_console_output )
483 req->handle = console_handle_unmap(hConsoleOutput);
486 req->mode = CHAR_INFO_MODE_ATTR;
488 wine_server_add_data( req, attr, length * sizeof(WORD) );
489 if ((ret = !wine_server_call_err( req )))
491 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
499 /******************************************************************************
500 * FillConsoleOutputCharacterA [KERNEL32.@]
503 * hConsoleOutput [I] Handle to screen buffer
504 * ch [I] Character to write
505 * length [I] Number of cells to write to
506 * coord [I] Coords of first cell
507 * lpNumCharsWritten [O] Pointer to number of cells written
513 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
514 COORD coord, LPDWORD lpNumCharsWritten )
518 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
519 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
523 /******************************************************************************
524 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
527 * hConsoleOutput [I] Handle to screen buffer
528 * ch [I] Character to write
529 * length [I] Number of cells to write to
530 * coord [I] Coords of first cell
531 * lpNumCharsWritten [O] Pointer to number of cells written
537 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
538 COORD coord, LPDWORD lpNumCharsWritten)
542 TRACE("(%p,%s,%ld,(%dx%d),%p)\n",
543 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
545 SERVER_START_REQ( fill_console_output )
547 req->handle = console_handle_unmap(hConsoleOutput);
550 req->mode = CHAR_INFO_MODE_TEXT;
554 if ((ret = !wine_server_call_err( req )))
556 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
564 /******************************************************************************
565 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
568 * hConsoleOutput [I] Handle to screen buffer
569 * attr [I] Color attribute to write
570 * length [I] Number of cells to write to
571 * coord [I] Coords of first cell
572 * lpNumAttrsWritten [O] Pointer to number of cells written
578 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
579 COORD coord, LPDWORD lpNumAttrsWritten )
583 TRACE("(%p,%d,%ld,(%dx%d),%p)\n",
584 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
586 SERVER_START_REQ( fill_console_output )
588 req->handle = console_handle_unmap(hConsoleOutput);
591 req->mode = CHAR_INFO_MODE_ATTR;
593 req->data.attr = attr;
595 if ((ret = !wine_server_call_err( req )))
597 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
605 /******************************************************************************
606 * ReadConsoleOutputCharacterA [KERNEL32.@]
609 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
610 COORD coord, LPDWORD read_count)
614 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
616 if (read_count) *read_count = 0;
617 if (!wptr) return FALSE;
619 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
621 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
622 if (read_count) *read_count = read;
624 HeapFree( GetProcessHeap(), 0, wptr );
629 /******************************************************************************
630 * ReadConsoleOutputCharacterW [KERNEL32.@]
633 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
634 COORD coord, LPDWORD read_count )
638 TRACE( "(%p,%p,%ld,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
640 SERVER_START_REQ( read_console_output )
642 req->handle = console_handle_unmap(hConsoleOutput);
645 req->mode = CHAR_INFO_MODE_TEXT;
647 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
648 if ((ret = !wine_server_call_err( req )))
650 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
658 /******************************************************************************
659 * ReadConsoleOutputAttribute [KERNEL32.@]
661 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
662 COORD coord, LPDWORD read_count)
666 TRACE("(%p,%p,%ld,%dx%d,%p)\n",
667 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
669 SERVER_START_REQ( read_console_output )
671 req->handle = console_handle_unmap(hConsoleOutput);
674 req->mode = CHAR_INFO_MODE_ATTR;
676 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
677 if ((ret = !wine_server_call_err( req )))
679 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
687 /******************************************************************************
688 * ReadConsoleOutputA [KERNEL32.@]
691 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
692 COORD coord, LPSMALL_RECT region )
697 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
698 if (ret && region->Right >= region->Left)
700 for (y = 0; y <= region->Bottom - region->Top; y++)
702 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
703 region->Right - region->Left + 1 );
710 /******************************************************************************
711 * ReadConsoleOutputW [KERNEL32.@]
713 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
714 * think we need to be *that* compatible. -- AJ
716 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
717 COORD coord, LPSMALL_RECT region )
719 int width, height, y;
722 width = min( region->Right - region->Left + 1, size.X - coord.X );
723 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
725 if (width > 0 && height > 0)
727 for (y = 0; y < height; y++)
729 SERVER_START_REQ( read_console_output )
731 req->handle = console_handle_unmap(hConsoleOutput);
732 req->x = region->Left;
733 req->y = region->Top + y;
734 req->mode = CHAR_INFO_MODE_TEXTATTR;
736 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
737 width * sizeof(CHAR_INFO) );
738 if ((ret = !wine_server_call_err( req )))
740 width = min( width, reply->width - region->Left );
741 height = min( height, reply->height - region->Top );
748 region->Bottom = region->Top + height - 1;
749 region->Right = region->Left + width - 1;
754 /******************************************************************************
755 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
758 * handle [I] Handle to console input buffer
759 * buffer [O] Address of buffer for read data
760 * count [I] Number of records to read
761 * pRead [O] Address of number of records read
767 BOOL WINAPI ReadConsoleInputA( HANDLE handle, LPINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
771 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
772 input_records_WtoA( buffer, read );
773 if (pRead) *pRead = read;
778 /***********************************************************************
779 * PeekConsoleInputA (KERNEL32.@)
781 * Gets 'count' first events (or less) from input queue.
783 BOOL WINAPI PeekConsoleInputA( HANDLE handle, LPINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
787 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
788 input_records_WtoA( buffer, read );
789 if (pRead) *pRead = read;
794 /***********************************************************************
795 * PeekConsoleInputW (KERNEL32.@)
797 BOOL WINAPI PeekConsoleInputW( HANDLE handle, LPINPUT_RECORD buffer, DWORD count, LPDWORD read )
800 SERVER_START_REQ( read_console_input )
802 req->handle = console_handle_unmap(handle);
804 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
805 if ((ret = !wine_server_call_err( req )))
807 if (read) *read = count ? reply->read : 0;
815 /***********************************************************************
816 * GetNumberOfConsoleInputEvents (KERNEL32.@)
818 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
821 SERVER_START_REQ( read_console_input )
823 req->handle = console_handle_unmap(handle);
825 if ((ret = !wine_server_call_err( req )))
827 if (nrofevents) *nrofevents = reply->read;
835 /******************************************************************************
838 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
841 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
843 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
844 static enum read_console_input_return read_console_input(HANDLE handle, LPINPUT_RECORD ir, DWORD timeout)
846 enum read_console_input_return ret;
848 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
850 SERVER_START_REQ( read_console_input )
852 req->handle = console_handle_unmap(handle);
854 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
855 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
856 else ret = rci_gotone;
864 /***********************************************************************
865 * FlushConsoleInputBuffer (KERNEL32.@)
867 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
869 enum read_console_input_return last;
872 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
874 return last == rci_timeout;
878 /***********************************************************************
879 * SetConsoleTitleA (KERNEL32.@)
881 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
886 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
887 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
888 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
889 ret = SetConsoleTitleW(titleW);
890 HeapFree(GetProcessHeap(), 0, titleW);
895 /***********************************************************************
896 * GetConsoleTitleA (KERNEL32.@)
898 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
900 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
904 ret = GetConsoleTitleW( ptr, size );
907 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
910 HeapFree(GetProcessHeap(), 0, ptr);
915 /******************************************************************************
916 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
919 * title [O] Address of buffer for title
920 * size [I] Size of buffer
923 * Success: Length of string copied
926 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
930 SERVER_START_REQ( get_console_input_info )
933 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
934 if (!wine_server_call_err( req ))
936 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
945 /***********************************************************************
946 * GetLargestConsoleWindowSize (KERNEL32.@)
949 * This should return a COORD, but calling convention for returning
950 * structures is different between Windows and gcc on i386.
955 #undef GetLargestConsoleWindowSize
956 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
966 #endif /* defined(__i386__) */
969 /***********************************************************************
970 * GetLargestConsoleWindowSize (KERNEL32.@)
973 * This should return a COORD, but calling convention for returning
974 * structures is different between Windows and gcc on i386.
979 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
986 #endif /* defined(__i386__) */
988 static WCHAR* S_EditString /* = NULL */;
989 static unsigned S_EditStrPos /* = 0 */;
991 /***********************************************************************
992 * FreeConsole (KERNEL32.@)
994 BOOL WINAPI FreeConsole(VOID)
998 SERVER_START_REQ(free_console)
1000 ret = !wine_server_call_err( req );
1006 /******************************************************************
1007 * start_console_renderer
1009 * helper for AllocConsole
1010 * starts the renderer process
1012 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1017 PROCESS_INFORMATION pi;
1019 /* FIXME: use dynamic allocation for most of the buffers below */
1020 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%d", appname, (INT)hEvent);
1021 if ((ret > -1) && (ret < sizeof(buffer)) &&
1022 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1023 NULL, NULL, si, &pi))
1025 if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
1027 TRACE("Started wineconsole pid=%08lx tid=%08lx\n",
1028 pi.dwProcessId, pi.dwThreadId);
1035 static BOOL start_console_renderer(STARTUPINFOA* si)
1039 OBJECT_ATTRIBUTES attr;
1042 attr.Length = sizeof(attr);
1043 attr.RootDirectory = 0;
1044 attr.Attributes = OBJ_INHERIT;
1045 attr.ObjectName = NULL;
1046 attr.SecurityDescriptor = NULL;
1047 attr.SecurityQualityOfService = NULL;
1049 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
1050 if (!hEvent) return FALSE;
1052 /* first try environment variable */
1053 if ((p = getenv("WINECONSOLE")) != NULL)
1055 ret = start_console_renderer_helper(p, si, hEvent);
1057 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1058 "trying default access\n", p);
1061 /* then try the regular PATH */
1063 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1065 CloseHandle(hEvent);
1069 /***********************************************************************
1070 * AllocConsole (KERNEL32.@)
1072 * creates an xterm with a pty to our program
1074 BOOL WINAPI AllocConsole(void)
1076 HANDLE handle_in = INVALID_HANDLE_VALUE;
1077 HANDLE handle_out = INVALID_HANDLE_VALUE;
1078 HANDLE handle_err = INVALID_HANDLE_VALUE;
1079 STARTUPINFOA siCurrent;
1080 STARTUPINFOA siConsole;
1082 SECURITY_ATTRIBUTES sa;
1086 handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1087 0, NULL, OPEN_EXISTING, 0, 0 );
1089 if (handle_in != INVALID_HANDLE_VALUE)
1091 /* we already have a console opened on this process, don't create a new one */
1092 CloseHandle(handle_in);
1096 GetStartupInfoA(&siCurrent);
1098 memset(&siConsole, 0, sizeof(siConsole));
1099 siConsole.cb = sizeof(siConsole);
1100 /* setup a view arguments for wineconsole (it'll use them as default values) */
1101 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1103 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1104 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1105 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1107 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1109 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1110 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1112 /* FIXME (should pass the unicode form) */
1113 if (siCurrent.lpTitle)
1114 siConsole.lpTitle = siCurrent.lpTitle;
1115 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1116 siConsole.lpTitle = buffer;
1118 if (!start_console_renderer(&siConsole))
1121 /* all std I/O handles are inheritable by default */
1122 sa.nLength = sizeof(sa);
1123 sa.lpSecurityDescriptor = NULL;
1124 sa.bInheritHandle = TRUE;
1126 handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1127 0, &sa, OPEN_EXISTING, 0, 0 );
1128 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1130 handle_out = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE,
1131 0, &sa, OPEN_EXISTING, 0, 0 );
1132 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1134 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(), &handle_err,
1135 0, TRUE, DUPLICATE_SAME_ACCESS))
1138 /* NT resets the STD_*_HANDLEs on console alloc */
1139 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1140 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1141 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1143 SetLastError(ERROR_SUCCESS);
1148 ERR("Can't allocate console\n");
1149 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1150 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1151 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1157 /***********************************************************************
1158 * ReadConsoleA (KERNEL32.@)
1160 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1161 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1163 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1167 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1168 ncr = WideCharToMultiByte(CP_ACP, 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1170 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1171 HeapFree(GetProcessHeap(), 0, ptr);
1176 /***********************************************************************
1177 * ReadConsoleW (KERNEL32.@)
1179 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1180 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1183 LPWSTR xbuf = (LPWSTR)lpBuffer;
1186 TRACE("(%p,%p,%ld,%p,%p)\n",
1187 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1189 if (!GetConsoleMode(hConsoleInput, &mode))
1192 if (mode & ENABLE_LINE_INPUT)
1194 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1196 if (S_EditString) HeapFree(GetProcessHeap(), 0, S_EditString);
1197 if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1201 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1202 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1203 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1204 S_EditStrPos += charsread;
1209 DWORD timeout = INFINITE;
1211 /* FIXME: should we read at least 1 char? The SDK does not say */
1212 /* wait for at least one available input record (it doesn't mean we'll have
1213 * chars stored in xbuf...)
1218 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1220 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1221 ir.Event.KeyEvent.uChar.UnicodeChar &&
1222 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
1224 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1226 } while (charsread < nNumberOfCharsToRead);
1227 /* nothing has been read */
1228 if (timeout == INFINITE) return FALSE;
1231 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1237 /***********************************************************************
1238 * ReadConsoleInputW (KERNEL32.@)
1240 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, LPINPUT_RECORD lpBuffer,
1241 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1244 DWORD timeout = INFINITE;
1248 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1252 /* loop until we get at least one event */
1253 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1257 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1262 /******************************************************************************
1263 * WriteConsoleOutputCharacterW [KERNEL32.@] Copies character to consecutive
1264 * cells in the console screen buffer
1267 * hConsoleOutput [I] Handle to screen buffer
1268 * str [I] Pointer to buffer with chars to write
1269 * length [I] Number of cells to write to
1270 * coord [I] Coords of first cell
1271 * lpNumCharsWritten [O] Pointer to number of cells written
1278 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1279 COORD coord, LPDWORD lpNumCharsWritten )
1283 TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
1284 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1286 SERVER_START_REQ( write_console_output )
1288 req->handle = console_handle_unmap(hConsoleOutput);
1291 req->mode = CHAR_INFO_MODE_TEXT;
1293 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1294 if ((ret = !wine_server_call_err( req )))
1296 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1304 /******************************************************************************
1305 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1308 * title [I] Address of new title
1314 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1318 SERVER_START_REQ( set_console_input_info )
1321 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1322 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1323 ret = !wine_server_call_err( req );
1330 /***********************************************************************
1331 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1333 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1335 FIXME("(%p): stub\n", nrofbuttons);
1340 /******************************************************************************
1341 * SetConsoleInputExeNameW [KERNEL32.@]
1346 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1348 FIXME("(%s): stub!\n", debugstr_w(name));
1350 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1354 /******************************************************************************
1355 * SetConsoleInputExeNameA [KERNEL32.@]
1360 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1362 int len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1363 LPWSTR xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1366 if (!xptr) return FALSE;
1368 MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
1369 ret = SetConsoleInputExeNameW(xptr);
1370 HeapFree(GetProcessHeap(), 0, xptr);
1375 /******************************************************************
1376 * CONSOLE_DefaultHandler
1378 * Final control event handler
1380 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1382 FIXME("Terminating process %lx on event %lx\n", GetCurrentProcessId(), dwCtrlType);
1384 /* should never go here */
1388 /******************************************************************************
1389 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1392 * func [I] Address of handler function
1393 * add [I] Handler to add or remove
1400 * James Sutherland (JamesSutherland@gmx.de)
1401 * Added global variables console_ignore_ctrl_c and handlers[]
1402 * Does not yet do any error checking, or set LastError if failed.
1403 * This doesn't yet matter, since these handlers are not yet called...!
1406 struct ConsoleHandler {
1407 PHANDLER_ROUTINE handler;
1408 struct ConsoleHandler* next;
1411 static unsigned int CONSOLE_IgnoreCtrlC = 0; /* FIXME: this should be inherited somehow */
1412 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1413 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1415 static CRITICAL_SECTION CONSOLE_CritSect;
1416 static CRITICAL_SECTION_DEBUG critsect_debug =
1418 0, 0, &CONSOLE_CritSect,
1419 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
1420 0, 0, { 0, (DWORD)(__FILE__ ": CONSOLE_CritSect") }
1422 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
1424 /*****************************************************************************/
1426 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1430 FIXME("(%p,%i) - no error checking or testing yet\n", func, add);
1434 CONSOLE_IgnoreCtrlC = add;
1438 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1440 if (!ch) return FALSE;
1442 RtlEnterCriticalSection(&CONSOLE_CritSect);
1443 ch->next = CONSOLE_Handlers;
1444 CONSOLE_Handlers = ch;
1445 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1449 struct ConsoleHandler** ch;
1450 RtlEnterCriticalSection(&CONSOLE_CritSect);
1451 for (ch = &CONSOLE_Handlers; *ch; *ch = (*ch)->next)
1453 if ((*ch)->handler == func) break;
1457 struct ConsoleHandler* rch = *ch;
1460 if (rch == &CONSOLE_DefaultConsoleHandler)
1462 ERR("Who's trying to remove default handler???\n");
1469 HeapFree(GetProcessHeap(), 0, rch);
1474 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1477 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1482 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
1484 TRACE("(%lx)\n", GetExceptionCode());
1485 return EXCEPTION_EXECUTE_HANDLER;
1488 static DWORD WINAPI CONSOLE_HandleCtrlCEntry(void* pmt)
1490 struct ConsoleHandler* ch;
1492 RtlEnterCriticalSection(&CONSOLE_CritSect);
1493 /* the debugger didn't continue... so, pass to ctrl handlers */
1494 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1496 if (ch->handler((DWORD)pmt)) break;
1498 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1502 /******************************************************************
1503 * CONSOLE_HandleCtrlC
1505 * Check whether the shall manipulate CtrlC events
1507 int CONSOLE_HandleCtrlC(unsigned sig)
1509 /* FIXME: better test whether a console is attached to this process ??? */
1510 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1511 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1512 if (CONSOLE_IgnoreCtrlC) return 1;
1514 /* try to pass the exception to the debugger
1515 * if it continues, there's nothing more to do
1516 * otherwise, we need to send the ctrl-event to the handlers
1520 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1522 __EXCEPT(CONSOLE_CtrlEventHandler)
1524 /* Create a separate thread to signal all the events. This would allow to
1525 * synchronize between setting the handlers and actually calling them
1527 CreateThread(NULL, 0, CONSOLE_HandleCtrlCEntry, (void*)CTRL_C_EVENT, 0, NULL);
1533 /******************************************************************************
1534 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1537 * dwCtrlEvent [I] Type of event
1538 * dwProcessGroupID [I] Process group ID to send event to
1542 * Failure: False (and *should* [but doesn't] set LastError)
1544 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1545 DWORD dwProcessGroupID)
1549 TRACE("(%ld, %ld)\n", dwCtrlEvent, dwProcessGroupID);
1551 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1553 ERR("Invalid event %ld for PGID %ld\n", dwCtrlEvent, dwProcessGroupID);
1557 SERVER_START_REQ( send_console_signal )
1559 req->signal = dwCtrlEvent;
1560 req->group_id = dwProcessGroupID;
1561 ret = !wine_server_call_err( req );
1569 /******************************************************************************
1570 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
1573 * dwDesiredAccess [I] Access flag
1574 * dwShareMode [I] Buffer share mode
1575 * sa [I] Security attributes
1576 * dwFlags [I] Type of buffer to create
1577 * lpScreenBufferData [I] Reserved
1580 * Should call SetLastError
1583 * Success: Handle to new console screen buffer
1584 * Failure: INVALID_HANDLE_VALUE
1586 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1587 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1588 LPVOID lpScreenBufferData)
1590 HANDLE ret = INVALID_HANDLE_VALUE;
1592 TRACE("(%ld,%ld,%p,%ld,%p)\n",
1593 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1595 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1597 SetLastError(ERROR_INVALID_PARAMETER);
1598 return INVALID_HANDLE_VALUE;
1601 SERVER_START_REQ(create_console_output)
1604 req->access = dwDesiredAccess;
1605 req->share = dwShareMode;
1606 req->inherit = (sa && sa->bInheritHandle);
1607 if (!wine_server_call_err( req )) ret = reply->handle_out;
1615 /***********************************************************************
1616 * GetConsoleScreenBufferInfo (KERNEL32.@)
1618 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1622 SERVER_START_REQ(get_console_output_info)
1624 req->handle = console_handle_unmap(hConsoleOutput);
1625 if ((ret = !wine_server_call_err( req )))
1627 csbi->dwSize.X = reply->width;
1628 csbi->dwSize.Y = reply->height;
1629 csbi->dwCursorPosition.X = reply->cursor_x;
1630 csbi->dwCursorPosition.Y = reply->cursor_y;
1631 csbi->wAttributes = reply->attr;
1632 csbi->srWindow.Left = reply->win_left;
1633 csbi->srWindow.Right = reply->win_right;
1634 csbi->srWindow.Top = reply->win_top;
1635 csbi->srWindow.Bottom = reply->win_bottom;
1636 csbi->dwMaximumWindowSize.X = reply->max_width;
1637 csbi->dwMaximumWindowSize.Y = reply->max_height;
1646 /******************************************************************************
1647 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
1653 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1657 TRACE("(%p)\n", hConsoleOutput);
1659 SERVER_START_REQ( set_console_input_info )
1662 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1663 req->active_sb = hConsoleOutput;
1664 ret = !wine_server_call_err( req );
1671 /***********************************************************************
1672 * GetConsoleMode (KERNEL32.@)
1674 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1678 SERVER_START_REQ(get_console_mode)
1680 req->handle = console_handle_unmap(hcon);
1681 ret = !wine_server_call_err( req );
1682 if (ret && mode) *mode = reply->mode;
1689 /******************************************************************************
1690 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
1693 * hcon [I] Handle to console input or screen buffer
1694 * mode [I] Input or output mode to set
1701 * ENABLE_PROCESSED_INPUT 0x01
1702 * ENABLE_LINE_INPUT 0x02
1703 * ENABLE_ECHO_INPUT 0x04
1704 * ENABLE_WINDOW_INPUT 0x08
1705 * ENABLE_MOUSE_INPUT 0x10
1707 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1711 SERVER_START_REQ(set_console_mode)
1713 req->handle = console_handle_unmap(hcon);
1715 ret = !wine_server_call_err( req );
1718 /* FIXME: when resetting a console input to editline mode, I think we should
1719 * empty the S_EditString buffer
1722 TRACE("(%p,%lx) retval == %d\n", hcon, mode, ret);
1728 /******************************************************************
1729 * CONSOLE_WriteChars
1731 * WriteConsoleOutput helper: hides server call semantics
1732 * writes a string at a given pos with standard attribute
1734 int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1740 SERVER_START_REQ( write_console_output )
1742 req->handle = console_handle_unmap(hCon);
1745 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1747 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1748 if (!wine_server_call_err( req )) written = reply->written;
1752 if (written > 0) pos->X += written;
1756 /******************************************************************
1759 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1762 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1768 csbi->dwCursorPosition.X = 0;
1769 csbi->dwCursorPosition.Y++;
1771 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1774 src.Bottom = csbi->dwSize.Y - 1;
1776 src.Right = csbi->dwSize.X - 1;
1781 ci.Attributes = csbi->wAttributes;
1782 ci.Char.UnicodeChar = ' ';
1784 csbi->dwCursorPosition.Y--;
1785 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1790 /******************************************************************
1793 * WriteConsoleOutput helper: writes a block of non special characters
1794 * Block can spread on several lines, and wrapping, if needed, is
1798 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1799 DWORD mode, LPWSTR ptr, int len)
1801 int blk; /* number of chars to write on current line */
1802 int done; /* number of chars already written */
1804 if (len <= 0) return 1;
1806 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1808 for (done = 0; done < len; done += blk)
1810 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1812 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1814 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
1820 int pos = csbi->dwCursorPosition.X;
1821 /* FIXME: we could reduce the number of loops
1822 * but, in most cases we wouldn't gain lots of time (it would only
1823 * happen if we're asked to overwrite more than twice the part of the line,
1826 for (blk = done = 0; done < len; done += blk)
1828 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1830 csbi->dwCursorPosition.X = pos;
1831 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1839 /***********************************************************************
1840 * WriteConsoleW (KERNEL32.@)
1842 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1843 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1847 WCHAR* psz = (WCHAR*)lpBuffer;
1848 CONSOLE_SCREEN_BUFFER_INFO csbi;
1851 TRACE("%p %s %ld %p %p\n",
1852 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
1853 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
1855 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1857 if (!GetConsoleMode(hConsoleOutput, &mode) ||
1858 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1861 if (mode & ENABLE_PROCESSED_OUTPUT)
1865 for (i = 0; i < nNumberOfCharsToWrite; i++)
1869 case '\b': case '\t': case '\n': case '\a': case '\r':
1870 /* don't handle here the i-th char... done below */
1871 if ((k = i - first) > 0)
1873 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1883 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
1887 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
1889 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
1890 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
1895 next_line(hConsoleOutput, &csbi);
1901 csbi.dwCursorPosition.X = 0;
1909 /* write the remaining block (if any) if processed output is enabled, or the
1910 * entire buffer otherwise
1912 if ((k = nNumberOfCharsToWrite - first) > 0)
1914 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1920 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
1921 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
1926 /***********************************************************************
1927 * WriteConsoleA (KERNEL32.@)
1929 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1930 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1936 n = MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
1938 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1939 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
1940 if (!xstring) return 0;
1942 MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
1944 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
1946 HeapFree(GetProcessHeap(), 0, xstring);
1951 /******************************************************************************
1952 * SetConsoleCursorPosition [KERNEL32.@]
1953 * Sets the cursor position in console
1956 * hConsoleOutput [I] Handle of console screen buffer
1957 * dwCursorPosition [I] New cursor position coordinates
1961 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
1964 CONSOLE_SCREEN_BUFFER_INFO csbi;
1968 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
1970 SERVER_START_REQ(set_console_output_info)
1972 req->handle = console_handle_unmap(hcon);
1973 req->cursor_x = pos.X;
1974 req->cursor_y = pos.Y;
1975 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
1976 ret = !wine_server_call_err( req );
1980 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
1983 /* if cursor is no longer visible, scroll the visible window... */
1984 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
1985 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1986 if (pos.X < csbi.srWindow.Left)
1988 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
1991 else if (pos.X > csbi.srWindow.Right)
1993 csbi.srWindow.Left = max(pos.X, w) - w + 1;
1996 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
1998 if (pos.Y < csbi.srWindow.Top)
2000 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2003 else if (pos.Y > csbi.srWindow.Bottom)
2005 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2008 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2010 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2015 /******************************************************************************
2016 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2019 * hcon [I] Handle to console screen buffer
2020 * cinfo [O] Address of cursor information
2026 BOOL WINAPI GetConsoleCursorInfo(HANDLE hcon, LPCONSOLE_CURSOR_INFO cinfo)
2030 SERVER_START_REQ(get_console_output_info)
2032 req->handle = console_handle_unmap(hcon);
2033 ret = !wine_server_call_err( req );
2036 cinfo->dwSize = reply->cursor_size;
2037 cinfo->bVisible = reply->cursor_visible;
2045 /******************************************************************************
2046 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2049 * hcon [I] Handle to console screen buffer
2050 * cinfo [I] Address of cursor information
2055 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2059 SERVER_START_REQ(set_console_output_info)
2061 req->handle = console_handle_unmap(hCon);
2062 req->cursor_size = cinfo->dwSize;
2063 req->cursor_visible = cinfo->bVisible;
2064 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2065 ret = !wine_server_call_err( req );
2072 /******************************************************************************
2073 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2076 * hcon [I] Handle to console screen buffer
2077 * bAbsolute [I] Coordinate type flag
2078 * window [I] Address of new window rectangle
2083 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2085 SMALL_RECT p = *window;
2090 CONSOLE_SCREEN_BUFFER_INFO csbi;
2091 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2093 p.Left += csbi.srWindow.Left;
2094 p.Top += csbi.srWindow.Top;
2095 p.Right += csbi.srWindow.Left;
2096 p.Bottom += csbi.srWindow.Top;
2098 SERVER_START_REQ(set_console_output_info)
2100 req->handle = console_handle_unmap(hCon);
2101 req->win_left = p.Left;
2102 req->win_top = p.Top;
2103 req->win_right = p.Right;
2104 req->win_bottom = p.Bottom;
2105 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2106 ret = !wine_server_call_err( req );
2114 /******************************************************************************
2115 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2117 * Sets the foreground and background color attributes of characters
2118 * written to the screen buffer.
2124 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2128 SERVER_START_REQ(set_console_output_info)
2130 req->handle = console_handle_unmap(hConsoleOutput);
2132 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2133 ret = !wine_server_call_err( req );
2140 /******************************************************************************
2141 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2144 * hConsoleOutput [I] Handle to console screen buffer
2145 * dwSize [I] New size in character rows and cols
2151 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2155 SERVER_START_REQ(set_console_output_info)
2157 req->handle = console_handle_unmap(hConsoleOutput);
2158 req->width = dwSize.X;
2159 req->height = dwSize.Y;
2160 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2161 ret = !wine_server_call_err( req );
2168 /******************************************************************************
2169 * ScrollConsoleScreenBufferA [KERNEL32.@]
2172 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2173 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2178 ciw.Attributes = lpFill->Attributes;
2179 MultiByteToWideChar(CP_ACP, 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2181 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2182 dwDestOrigin, &ciw);
2185 /******************************************************************
2186 * CONSOLE_FillLineUniform
2188 * Helper function for ScrollConsoleScreenBufferW
2189 * Fills a part of a line with a constant character info
2191 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2193 SERVER_START_REQ( fill_console_output )
2195 req->handle = console_handle_unmap(hConsoleOutput);
2196 req->mode = CHAR_INFO_MODE_TEXTATTR;
2201 req->data.ch = lpFill->Char.UnicodeChar;
2202 req->data.attr = lpFill->Attributes;
2203 wine_server_call_err( req );
2208 /******************************************************************************
2209 * ScrollConsoleScreenBufferW [KERNEL32.@]
2213 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2214 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2222 CONSOLE_SCREEN_BUFFER_INFO csbi;
2226 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2227 lpScrollRect->Left, lpScrollRect->Top,
2228 lpScrollRect->Right, lpScrollRect->Bottom,
2229 lpClipRect->Left, lpClipRect->Top,
2230 lpClipRect->Right, lpClipRect->Bottom,
2231 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2233 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2234 lpScrollRect->Left, lpScrollRect->Top,
2235 lpScrollRect->Right, lpScrollRect->Bottom,
2236 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2238 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2241 /* step 1: get dst rect */
2242 dst.Left = dwDestOrigin.X;
2243 dst.Top = dwDestOrigin.Y;
2244 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2245 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2247 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2250 clip.Left = max(0, lpClipRect->Left);
2251 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2252 clip.Top = max(0, lpClipRect->Top);
2253 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2258 clip.Right = csbi.dwSize.X - 1;
2260 clip.Bottom = csbi.dwSize.Y - 1;
2262 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2264 /* step 2b: clip dst rect */
2265 if (dst.Left < clip.Left ) dst.Left = clip.Left;
2266 if (dst.Top < clip.Top ) dst.Top = clip.Top;
2267 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2268 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2270 /* step 3: transfer the bits */
2271 SERVER_START_REQ(move_console_output)
2273 req->handle = console_handle_unmap(hConsoleOutput);
2274 req->x_src = lpScrollRect->Left;
2275 req->y_src = lpScrollRect->Top;
2276 req->x_dst = dst.Left;
2277 req->y_dst = dst.Top;
2278 req->w = dst.Right - dst.Left + 1;
2279 req->h = dst.Bottom - dst.Top + 1;
2280 ret = !wine_server_call_err( req );
2284 if (!ret) return FALSE;
2286 /* step 4: clean out the exposed part */
2288 /* have to write cell [i,j] if it is not in dst rect (because it has already
2289 * been written to by the scroll) and is in clip (we shall not write
2292 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2294 inside = dst.Top <= j && j <= dst.Bottom;
2296 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2298 if (inside && dst.Left <= i && i <= dst.Right)
2302 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2308 if (start == -1) start = i;
2312 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2319 /* ====================================================================
2321 * Console manipulation functions
2323 * ====================================================================*/
2325 /* some missing functions...
2326 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2327 * should get the right API and implement them
2328 * GetConsoleCommandHistory[AW] (dword dword dword)
2329 * GetConsoleCommandHistoryLength[AW]
2330 * SetConsoleCommandHistoryMode
2331 * SetConsoleNumberOfCommands[AW]
2333 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2337 SERVER_START_REQ( get_console_input_history )
2341 if (buf && buf_len > 1)
2343 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2345 if (!wine_server_call_err( req ))
2347 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2348 len = reply->total / sizeof(WCHAR) + 1;
2355 /******************************************************************
2356 * CONSOLE_AppendHistory
2360 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2362 size_t len = strlenW(ptr);
2365 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2367 SERVER_START_REQ( append_console_input_history )
2370 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2371 ret = !wine_server_call_err( req );
2377 /******************************************************************
2378 * CONSOLE_GetNumHistoryEntries
2382 unsigned CONSOLE_GetNumHistoryEntries(void)
2385 SERVER_START_REQ(get_console_input_info)
2388 if (!wine_server_call_err( req )) ret = reply->history_index;
2394 /******************************************************************
2395 * CONSOLE_GetEditionMode
2399 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2401 unsigned ret = FALSE;
2402 SERVER_START_REQ(get_console_input_info)
2404 req->handle = console_handle_unmap(hConIn);
2405 if ((ret = !wine_server_call_err( req )))
2406 *mode = reply->edition_mode;