2 * Win32 console functions
4 * Copyright 1995 Martin von Loewis and Cameron Heide
5 * Copyright 1997 Karl Garrison
6 * Copyright 1998 John Richardson
7 * Copyright 1998 Marcus Meissner
8 * Copyright 2001,2002,2004,2005 Eric Pouech
9 * Copyright 2001 Alexandre Julliard
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 /* Reference applications:
27 * - IDA (interactive disassembler) full version 3.75. Works.
28 * - LYNX/W32. Works mostly, some keys crash it.
32 #include "wine/port.h"
46 #define WIN32_NO_STATUS
52 #include "wine/server.h"
53 #include "wine/exception.h"
54 #include "wine/unicode.h"
55 #include "wine/debug.h"
57 #include "console_private.h"
58 #include "kernel_private.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(console);
62 static CRITICAL_SECTION CONSOLE_CritSect;
63 static CRITICAL_SECTION_DEBUG critsect_debug =
65 0, 0, &CONSOLE_CritSect,
66 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
67 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
69 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
71 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
72 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
74 /* FIXME: this is not thread safe */
75 static HANDLE console_wait_event;
77 /* map input records to ASCII */
78 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
83 for (i = 0; i < count; i++)
85 if (buffer[i].EventType != KEY_EVENT) continue;
86 WideCharToMultiByte( GetConsoleCP(), 0,
87 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
88 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
92 /* map input records to Unicode */
93 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
98 for (i = 0; i < count; i++)
100 if (buffer[i].EventType != KEY_EVENT) continue;
101 MultiByteToWideChar( GetConsoleCP(), 0,
102 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
103 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
107 /* map char infos to ASCII */
108 static void char_info_WtoA( CHAR_INFO *buffer, int count )
114 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
115 &ch, 1, NULL, NULL );
116 buffer->Char.AsciiChar = ch;
121 /* map char infos to Unicode */
122 static void char_info_AtoW( CHAR_INFO *buffer, int count )
128 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
129 buffer->Char.UnicodeChar = ch;
134 static BOOL get_console_mode(HANDLE conin, DWORD* mode, BOOL* bare)
138 SERVER_START_REQ( get_console_mode )
140 req->handle = console_handle_unmap(conin);
141 if ((ret = !wine_server_call_err( req )))
143 if (mode) *mode = reply->mode;
144 if (bare) *bare = reply->is_bare;
151 static struct termios S_termios; /* saved termios for bare consoles */
152 static BOOL S_termios_raw /* = FALSE */;
154 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
155 * - a bare console is created for all CUI programs started from command line (without
156 * wineconsole) (let's call those PS)
157 * - of course, every child of a PS which requires console inheritance will get it
158 * - the console termios attributes are saved at the start of program which is attached to be
160 * - if any program attached to a bare console requests input from console, the console is
161 * turned into raw mode
162 * - when the program which created the bare console (the program started from command line)
163 * exits, it will restore the console termios attributes it saved at startup (this
164 * will put back the console into cooked mode if it had been put in raw mode)
165 * - if any other program attached to this bare console is still alive, the Unix shell will put
166 * it in the background, hence forbidding access to the console. Therefore, reading console
167 * input will not be available when the bare console creator has died.
168 * FIXME: This is a limitation of current implementation
171 /* returns the fd for a bare console (-1 otherwise) */
172 static int get_console_bare_fd(HANDLE hin)
177 if (get_console_mode(hin, NULL, &is_bare) && is_bare &&
178 wine_server_handle_to_fd(hin, 0, &fd, NULL) == STATUS_SUCCESS)
183 static BOOL save_console_mode(HANDLE hin)
188 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
189 ret = tcgetattr(fd, &S_termios) >= 0;
194 static BOOL put_console_into_raw_mode(HANDLE hin)
198 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
200 RtlEnterCriticalSection(&CONSOLE_CritSect);
203 struct termios term = S_termios;
205 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
206 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
207 term.c_cflag &= ~(CSIZE | PARENB);
209 /* FIXME: we should actually disable output processing here
210 * and let kernel32/console.c do the job (with support of enable/disable of
213 /* term.c_oflag &= ~(OPOST); */
215 term.c_cc[VTIME] = 0;
216 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
218 RtlLeaveCriticalSection(&CONSOLE_CritSect);
221 return S_termios_raw;
224 /* put back the console in cooked mode iff we're the process which created the bare console
225 * we don't test if thie process has set the console in raw mode as it could be one of its
228 static BOOL restore_console_mode(HANDLE hin)
233 if (RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
235 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
236 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
241 /******************************************************************************
242 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
245 * Success: hwnd of the console window.
248 HWND WINAPI GetConsoleWindow(VOID)
252 SERVER_START_REQ(get_console_input_info)
255 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
263 /******************************************************************************
264 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
269 UINT WINAPI GetConsoleCP(VOID)
272 UINT codepage = GetOEMCP(); /* default value */
274 SERVER_START_REQ(get_console_input_info)
277 ret = !wine_server_call_err(req);
278 if (ret && reply->input_cp)
279 codepage = reply->input_cp;
287 /******************************************************************************
288 * SetConsoleCP [KERNEL32.@]
290 BOOL WINAPI SetConsoleCP(UINT cp)
294 if (!IsValidCodePage(cp))
296 SetLastError(ERROR_INVALID_PARAMETER);
300 SERVER_START_REQ(set_console_input_info)
303 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
305 ret = !wine_server_call_err(req);
313 /***********************************************************************
314 * GetConsoleOutputCP (KERNEL32.@)
316 UINT WINAPI GetConsoleOutputCP(VOID)
319 UINT codepage = GetOEMCP(); /* default value */
321 SERVER_START_REQ(get_console_input_info)
324 ret = !wine_server_call_err(req);
325 if (ret && reply->output_cp)
326 codepage = reply->output_cp;
334 /******************************************************************************
335 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
338 * cp [I] code page to set
344 BOOL WINAPI SetConsoleOutputCP(UINT cp)
348 if (!IsValidCodePage(cp))
350 SetLastError(ERROR_INVALID_PARAMETER);
354 SERVER_START_REQ(set_console_input_info)
357 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
359 ret = !wine_server_call_err(req);
367 /***********************************************************************
370 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
372 static const char beep = '\a';
373 /* dwFreq and dwDur are ignored by Win95 */
374 if (isatty(2)) write( 2, &beep, 1 );
379 /******************************************************************
380 * OpenConsoleW (KERNEL32.@)
383 * Open a handle to the current process console.
384 * Returns INVALID_HANDLE_VALUE on failure.
386 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
388 HANDLE output = INVALID_HANDLE_VALUE;
391 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
395 if (strcmpiW(coninW, name) == 0)
396 output = (HANDLE) FALSE;
397 else if (strcmpiW(conoutW, name) == 0)
398 output = (HANDLE) TRUE;
401 if (output == INVALID_HANDLE_VALUE)
403 SetLastError(ERROR_INVALID_PARAMETER);
404 return INVALID_HANDLE_VALUE;
406 else if (creation != OPEN_EXISTING)
408 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
409 SetLastError(ERROR_SHARING_VIOLATION);
411 SetLastError(ERROR_INVALID_PARAMETER);
412 return INVALID_HANDLE_VALUE;
415 SERVER_START_REQ( open_console )
417 req->from = wine_server_obj_handle( output );
418 req->access = access;
419 req->attributes = inherit ? OBJ_INHERIT : 0;
420 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
421 wine_server_call_err( req );
422 ret = wine_server_ptr_handle( reply->handle );
426 ret = console_handle_map(ret);
431 /******************************************************************
432 * VerifyConsoleIoHandle (KERNEL32.@)
436 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
440 if (!is_console_handle(handle)) return FALSE;
441 SERVER_START_REQ(get_console_mode)
443 req->handle = console_handle_unmap(handle);
444 ret = !wine_server_call( req );
450 /******************************************************************
451 * DuplicateConsoleHandle (KERNEL32.@)
455 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
460 if (!is_console_handle(handle) ||
461 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
462 GetCurrentProcess(), &ret, access, inherit, options))
463 return INVALID_HANDLE_VALUE;
464 return console_handle_map(ret);
467 /******************************************************************
468 * CloseConsoleHandle (KERNEL32.@)
472 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
474 if (!is_console_handle(handle))
476 SetLastError(ERROR_INVALID_PARAMETER);
479 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
482 /******************************************************************
483 * GetConsoleInputWaitHandle (KERNEL32.@)
487 HANDLE WINAPI GetConsoleInputWaitHandle(void)
489 if (!console_wait_event)
491 SERVER_START_REQ(get_console_wait_event)
493 if (!wine_server_call_err( req ))
494 console_wait_event = wine_server_ptr_handle( reply->handle );
498 return console_wait_event;
502 /******************************************************************************
503 * WriteConsoleInputA [KERNEL32.@]
505 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
506 DWORD count, LPDWORD written )
511 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
512 memcpy( recW, buffer, count*sizeof(*recW) );
513 input_records_AtoW( recW, count );
514 ret = WriteConsoleInputW( handle, recW, count, written );
515 HeapFree( GetProcessHeap(), 0, recW );
520 /******************************************************************************
521 * WriteConsoleInputW [KERNEL32.@]
523 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
524 DWORD count, LPDWORD written )
528 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
530 if (written) *written = 0;
531 SERVER_START_REQ( write_console_input )
533 req->handle = console_handle_unmap(handle);
534 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
535 if ((ret = !wine_server_call_err( req )) && written)
536 *written = reply->written;
544 /***********************************************************************
545 * WriteConsoleOutputA (KERNEL32.@)
547 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
548 COORD size, COORD coord, LPSMALL_RECT region )
552 COORD new_size, new_coord;
555 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
556 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
558 if (new_size.X <= 0 || new_size.Y <= 0)
560 region->Bottom = region->Top + new_size.Y - 1;
561 region->Right = region->Left + new_size.X - 1;
565 /* only copy the useful rectangle */
566 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
568 for (y = 0; y < new_size.Y; y++)
570 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
571 new_size.X * sizeof(CHAR_INFO) );
572 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
574 new_coord.X = new_coord.Y = 0;
575 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
576 HeapFree( GetProcessHeap(), 0, ciw );
581 /***********************************************************************
582 * WriteConsoleOutputW (KERNEL32.@)
584 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
585 COORD size, COORD coord, LPSMALL_RECT region )
587 int width, height, y;
590 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
591 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
592 region->Left, region->Top, region->Right, region->Bottom);
594 width = min( region->Right - region->Left + 1, size.X - coord.X );
595 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
597 if (width > 0 && height > 0)
599 for (y = 0; y < height; y++)
601 SERVER_START_REQ( write_console_output )
603 req->handle = console_handle_unmap(hConsoleOutput);
604 req->x = region->Left;
605 req->y = region->Top + y;
606 req->mode = CHAR_INFO_MODE_TEXTATTR;
608 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
609 width * sizeof(CHAR_INFO));
610 if ((ret = !wine_server_call_err( req )))
612 width = min( width, reply->width - region->Left );
613 height = min( height, reply->height - region->Top );
620 region->Bottom = region->Top + height - 1;
621 region->Right = region->Left + width - 1;
626 /******************************************************************************
627 * WriteConsoleOutputCharacterA [KERNEL32.@]
629 * See WriteConsoleOutputCharacterW.
631 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
632 COORD coord, LPDWORD lpNumCharsWritten )
638 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
639 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
641 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
643 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
645 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
646 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
648 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
649 HeapFree( GetProcessHeap(), 0, strW );
654 /******************************************************************************
655 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
656 * the console screen buffer
659 * hConsoleOutput [I] Handle to screen buffer
660 * attr [I] Pointer to buffer with write attributes
661 * length [I] Number of cells to write to
662 * coord [I] Coords of first cell
663 * lpNumAttrsWritten [O] Pointer to number of cells written
670 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
671 COORD coord, LPDWORD lpNumAttrsWritten )
675 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
677 SERVER_START_REQ( write_console_output )
679 req->handle = console_handle_unmap(hConsoleOutput);
682 req->mode = CHAR_INFO_MODE_ATTR;
684 wine_server_add_data( req, attr, length * sizeof(WORD) );
685 if ((ret = !wine_server_call_err( req )))
687 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
695 /******************************************************************************
696 * FillConsoleOutputCharacterA [KERNEL32.@]
698 * See FillConsoleOutputCharacterW.
700 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
701 COORD coord, LPDWORD lpNumCharsWritten )
705 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
706 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
710 /******************************************************************************
711 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
714 * hConsoleOutput [I] Handle to screen buffer
715 * ch [I] Character to write
716 * length [I] Number of cells to write to
717 * coord [I] Coords of first cell
718 * lpNumCharsWritten [O] Pointer to number of cells written
724 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
725 COORD coord, LPDWORD lpNumCharsWritten)
729 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
730 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
732 SERVER_START_REQ( fill_console_output )
734 req->handle = console_handle_unmap(hConsoleOutput);
737 req->mode = CHAR_INFO_MODE_TEXT;
741 if ((ret = !wine_server_call_err( req )))
743 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
751 /******************************************************************************
752 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
755 * hConsoleOutput [I] Handle to screen buffer
756 * attr [I] Color attribute to write
757 * length [I] Number of cells to write to
758 * coord [I] Coords of first cell
759 * lpNumAttrsWritten [O] Pointer to number of cells written
765 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
766 COORD coord, LPDWORD lpNumAttrsWritten )
770 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
771 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
773 SERVER_START_REQ( fill_console_output )
775 req->handle = console_handle_unmap(hConsoleOutput);
778 req->mode = CHAR_INFO_MODE_ATTR;
780 req->data.attr = attr;
782 if ((ret = !wine_server_call_err( req )))
784 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
792 /******************************************************************************
793 * ReadConsoleOutputCharacterA [KERNEL32.@]
796 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
797 COORD coord, LPDWORD read_count)
801 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
803 if (read_count) *read_count = 0;
804 if (!wptr) return FALSE;
806 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
808 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
809 if (read_count) *read_count = read;
811 HeapFree( GetProcessHeap(), 0, wptr );
816 /******************************************************************************
817 * ReadConsoleOutputCharacterW [KERNEL32.@]
820 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
821 COORD coord, LPDWORD read_count )
825 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
827 SERVER_START_REQ( read_console_output )
829 req->handle = console_handle_unmap(hConsoleOutput);
832 req->mode = CHAR_INFO_MODE_TEXT;
834 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
835 if ((ret = !wine_server_call_err( req )))
837 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
845 /******************************************************************************
846 * ReadConsoleOutputAttribute [KERNEL32.@]
848 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
849 COORD coord, LPDWORD read_count)
853 TRACE("(%p,%p,%d,%dx%d,%p)\n",
854 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
856 SERVER_START_REQ( read_console_output )
858 req->handle = console_handle_unmap(hConsoleOutput);
861 req->mode = CHAR_INFO_MODE_ATTR;
863 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
864 if ((ret = !wine_server_call_err( req )))
866 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
874 /******************************************************************************
875 * ReadConsoleOutputA [KERNEL32.@]
878 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
879 COORD coord, LPSMALL_RECT region )
884 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
885 if (ret && region->Right >= region->Left)
887 for (y = 0; y <= region->Bottom - region->Top; y++)
889 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
890 region->Right - region->Left + 1 );
897 /******************************************************************************
898 * ReadConsoleOutputW [KERNEL32.@]
900 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
901 * think we need to be *that* compatible. -- AJ
903 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
904 COORD coord, LPSMALL_RECT region )
906 int width, height, y;
909 width = min( region->Right - region->Left + 1, size.X - coord.X );
910 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
912 if (width > 0 && height > 0)
914 for (y = 0; y < height; y++)
916 SERVER_START_REQ( read_console_output )
918 req->handle = console_handle_unmap(hConsoleOutput);
919 req->x = region->Left;
920 req->y = region->Top + y;
921 req->mode = CHAR_INFO_MODE_TEXTATTR;
923 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
924 width * sizeof(CHAR_INFO) );
925 if ((ret = !wine_server_call_err( req )))
927 width = min( width, reply->width - region->Left );
928 height = min( height, reply->height - region->Top );
935 region->Bottom = region->Top + height - 1;
936 region->Right = region->Left + width - 1;
941 /******************************************************************************
942 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
945 * handle [I] Handle to console input buffer
946 * buffer [O] Address of buffer for read data
947 * count [I] Number of records to read
948 * pRead [O] Address of number of records read
954 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
958 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
959 input_records_WtoA( buffer, read );
960 if (pRead) *pRead = read;
965 /***********************************************************************
966 * PeekConsoleInputA (KERNEL32.@)
968 * Gets 'count' first events (or less) from input queue.
970 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
974 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
975 input_records_WtoA( buffer, read );
976 if (pRead) *pRead = read;
981 /***********************************************************************
982 * PeekConsoleInputW (KERNEL32.@)
984 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
987 SERVER_START_REQ( read_console_input )
989 req->handle = console_handle_unmap(handle);
991 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
992 if ((ret = !wine_server_call_err( req )))
994 if (read) *read = count ? reply->read : 0;
1002 /***********************************************************************
1003 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1005 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1008 SERVER_START_REQ( read_console_input )
1010 req->handle = console_handle_unmap(handle);
1012 if ((ret = !wine_server_call_err( req )))
1014 if (nrofevents) *nrofevents = reply->read;
1022 /******************************************************************************
1023 * read_console_input
1025 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1028 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1030 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1031 static const int vkkeyscan_table[256] =
1033 0,0,0,0,0,0,0,0,8,9,0,0,0,13,0,0,0,0,0,19,145,556,0,0,0,0,0,27,0,0,0,
1034 0,32,305,478,307,308,309,311,222,313,304,312,443,188,189,190,191,48,
1035 49,50,51,52,53,54,55,56,57,442,186,444,187,446,447,306,321,322,323,
1036 324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,
1037 341,342,343,344,345,346,219,220,221,310,445,192,65,66,67,68,69,70,71,
1038 72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,475,476,477,
1039 448,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1040 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1041 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1042 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,400,0,0,0,0,0,0
1045 static const int mapvkey_0[256] =
1047 0,0,0,0,0,0,0,0,14,15,0,0,0,28,0,0,42,29,56,69,58,0,0,0,0,0,0,1,0,0,
1048 0,0,57,73,81,79,71,75,72,77,80,0,0,0,55,82,83,0,11,2,3,4,5,6,7,8,9,
1049 10,0,0,0,0,0,0,0,30,48,46,32,18,33,34,35,23,36,37,38,50,49,24,25,16,
1050 19,31,20,22,47,17,45,21,44,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,55,78,0,74,
1051 0,53,59,60,61,62,63,64,65,66,67,68,87,88,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1052 0,0,0,0,0,0,69,70,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1053 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,39,13,51,12,52,53,41,0,0,0,0,0,0,0,0,0,
1054 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,43,27,40,76,96,0,0,0,0,0,0,0,0,
1055 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
1058 static inline void init_complex_char(INPUT_RECORD* ir, BOOL down, WORD vk, WORD kc, DWORD cks)
1060 ir->EventType = KEY_EVENT;
1061 ir->Event.KeyEvent.bKeyDown = down;
1062 ir->Event.KeyEvent.wRepeatCount = 1;
1063 ir->Event.KeyEvent.wVirtualScanCode = vk;
1064 ir->Event.KeyEvent.wVirtualKeyCode = kc;
1065 ir->Event.KeyEvent.dwControlKeyState = cks;
1066 ir->Event.KeyEvent.uChar.UnicodeChar = 0;
1069 /******************************************************************
1070 * handle_simple_char
1074 static BOOL handle_simple_char(HANDLE conin, unsigned real_inchar)
1079 unsigned numEvent = 0;
1080 DWORD cks = 0, written;
1083 switch (real_inchar)
1085 case 9: inchar = real_inchar;
1086 real_inchar = 27; /* so that we don't think key is ctrl- something */
1089 case 10: inchar = '\r';
1090 real_inchar = 27; /* Fixme: so that we don't think key is ctrl- something */
1092 case 127: inchar = '\b';
1095 inchar = real_inchar;
1098 if ((inchar & ~0xFF) != 0) FIXME("What a char (%u)\n", inchar);
1099 vk = vkkeyscan_table[inchar];
1101 init_complex_char(&ir[numEvent++], 1, 0x2a, 0x10, SHIFT_PRESSED);
1102 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1103 init_complex_char(&ir[numEvent++], 1, 0x1d, 0x11, LEFT_CTRL_PRESSED);
1105 init_complex_char(&ir[numEvent++], 1, 0x38, 0x12, LEFT_ALT_PRESSED);
1107 ir[numEvent].EventType = KEY_EVENT;
1108 ir[numEvent].Event.KeyEvent.bKeyDown = 1;
1109 ir[numEvent].Event.KeyEvent.wRepeatCount = 1;
1110 ir[numEvent].Event.KeyEvent.dwControlKeyState = cks;
1112 ir[numEvent].Event.KeyEvent.dwControlKeyState |= SHIFT_PRESSED;
1113 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1114 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_CTRL_PRESSED;
1116 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_ALT_PRESSED;
1117 ir[numEvent].Event.KeyEvent.wVirtualKeyCode = vk;
1118 ir[numEvent].Event.KeyEvent.wVirtualScanCode = mapvkey_0[vk & 0x00ff]; /* VirtualKeyCodes to ScanCode */
1121 MultiByteToWideChar(CP_UNIXCP, 0, &ch, 1, &ir[numEvent].Event.KeyEvent.uChar.UnicodeChar, 1);
1122 ir[numEvent + 1] = ir[numEvent];
1123 ir[numEvent + 1].Event.KeyEvent.bKeyDown = 0;
1128 init_complex_char(&ir[numEvent++], 0, 0x38, 0x12, LEFT_ALT_PRESSED);
1129 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1130 init_complex_char(&ir[numEvent++], 0, 0x1d, 0x11, 0);
1132 init_complex_char(&ir[numEvent++], 0, 0x2a, 0x10, 0);
1134 return WriteConsoleInputW(conin, ir, numEvent, &written);
1137 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, DWORD timeout)
1140 enum read_console_input_return ret;
1143 /* get the real handle to the console object */
1144 handle = wine_server_ptr_handle(console_handle_unmap(handle));
1146 memset(&ov, 0, sizeof(ov));
1147 ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1149 if (ReadFile(handle, &ch, 1, NULL, &ov) ||
1150 (GetLastError() == ERROR_IO_PENDING &&
1151 WaitForSingleObject(ov.hEvent, timeout) == WAIT_OBJECT_0 &&
1152 GetOverlappedResult(handle, &ov, NULL, FALSE)))
1154 ret = handle_simple_char(handle, ch) ? rci_gotone : rci_error;
1158 WARN("Failed read %x\n", GetLastError());
1161 CloseHandle(ov.hEvent);
1166 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1169 enum read_console_input_return ret;
1171 if (!get_console_mode(handle, NULL, &bare)) return rci_error;
1175 put_console_into_raw_mode(handle);
1176 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1178 ret = bare_console_fetch_input(handle, timeout);
1179 if (ret != rci_gotone) return ret;
1184 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1188 SERVER_START_REQ( read_console_input )
1190 req->handle = console_handle_unmap(handle);
1192 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1193 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1194 else ret = rci_gotone;
1202 /***********************************************************************
1203 * FlushConsoleInputBuffer (KERNEL32.@)
1205 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1207 enum read_console_input_return last;
1210 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1212 return last == rci_timeout;
1216 /***********************************************************************
1217 * SetConsoleTitleA (KERNEL32.@)
1219 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1224 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1225 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1226 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1227 ret = SetConsoleTitleW(titleW);
1228 HeapFree(GetProcessHeap(), 0, titleW);
1233 /***********************************************************************
1234 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1236 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1238 FIXME( "stub %p\n", layoutName);
1242 /***********************************************************************
1243 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1245 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1247 FIXME( "stub %p\n", layoutName);
1251 static WCHAR input_exe[MAX_PATH + 1];
1253 /***********************************************************************
1254 * GetConsoleInputExeNameW (KERNEL32.@)
1256 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1258 TRACE("%u %p\n", buflen, buffer);
1260 RtlEnterCriticalSection(&CONSOLE_CritSect);
1261 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1262 else SetLastError(ERROR_BUFFER_OVERFLOW);
1263 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1268 /***********************************************************************
1269 * GetConsoleInputExeNameA (KERNEL32.@)
1271 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1273 TRACE("%u %p\n", buflen, buffer);
1275 RtlEnterCriticalSection(&CONSOLE_CritSect);
1276 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1277 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1278 else SetLastError(ERROR_BUFFER_OVERFLOW);
1279 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1284 /***********************************************************************
1285 * GetConsoleTitleA (KERNEL32.@)
1287 * See GetConsoleTitleW.
1289 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1291 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1295 ret = GetConsoleTitleW( ptr, size );
1298 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1299 ret = strlen(title);
1301 HeapFree(GetProcessHeap(), 0, ptr);
1306 /******************************************************************************
1307 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1310 * title [O] Address of buffer for title
1311 * size [I] Size of buffer
1314 * Success: Length of string copied
1317 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1321 SERVER_START_REQ( get_console_input_info )
1324 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1325 if (!wine_server_call_err( req ))
1327 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1336 /***********************************************************************
1337 * GetLargestConsoleWindowSize (KERNEL32.@)
1340 * This should return a COORD, but calling convention for returning
1341 * structures is different between Windows and gcc on i386.
1346 #undef GetLargestConsoleWindowSize
1347 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1355 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1358 #endif /* defined(__i386__) */
1361 /***********************************************************************
1362 * GetLargestConsoleWindowSize (KERNEL32.@)
1365 * This should return a COORD, but calling convention for returning
1366 * structures is different between Windows and gcc on i386.
1371 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1376 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1379 #endif /* defined(__i386__) */
1381 static WCHAR* S_EditString /* = NULL */;
1382 static unsigned S_EditStrPos /* = 0 */;
1384 /***********************************************************************
1385 * FreeConsole (KERNEL32.@)
1387 BOOL WINAPI FreeConsole(VOID)
1391 /* invalidate local copy of input event handle */
1392 console_wait_event = 0;
1394 SERVER_START_REQ(free_console)
1396 ret = !wine_server_call_err( req );
1402 /******************************************************************
1403 * start_console_renderer
1405 * helper for AllocConsole
1406 * starts the renderer process
1408 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1413 PROCESS_INFORMATION pi;
1415 /* FIXME: use dynamic allocation for most of the buffers below */
1416 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1417 if ((ret > -1) && (ret < sizeof(buffer)) &&
1418 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1419 NULL, NULL, si, &pi))
1425 wh[1] = pi.hProcess;
1426 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1428 CloseHandle(pi.hThread);
1429 CloseHandle(pi.hProcess);
1431 if (ret != WAIT_OBJECT_0) return FALSE;
1433 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1434 pi.dwProcessId, pi.dwThreadId);
1441 static BOOL start_console_renderer(STARTUPINFOA* si)
1445 OBJECT_ATTRIBUTES attr;
1448 attr.Length = sizeof(attr);
1449 attr.RootDirectory = 0;
1450 attr.Attributes = OBJ_INHERIT;
1451 attr.ObjectName = NULL;
1452 attr.SecurityDescriptor = NULL;
1453 attr.SecurityQualityOfService = NULL;
1455 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1456 if (!hEvent) return FALSE;
1458 /* first try environment variable */
1459 if ((p = getenv("WINECONSOLE")) != NULL)
1461 ret = start_console_renderer_helper(p, si, hEvent);
1463 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1464 "trying default access\n", p);
1467 /* then try the regular PATH */
1469 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1471 CloseHandle(hEvent);
1475 /***********************************************************************
1476 * AllocConsole (KERNEL32.@)
1478 * creates an xterm with a pty to our program
1480 BOOL WINAPI AllocConsole(void)
1482 HANDLE handle_in = INVALID_HANDLE_VALUE;
1483 HANDLE handle_out = INVALID_HANDLE_VALUE;
1484 HANDLE handle_err = INVALID_HANDLE_VALUE;
1485 STARTUPINFOA siCurrent;
1486 STARTUPINFOA siConsole;
1491 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1492 FALSE, OPEN_EXISTING );
1494 if (VerifyConsoleIoHandle(handle_in))
1496 /* we already have a console opened on this process, don't create a new one */
1497 CloseHandle(handle_in);
1501 /* invalidate local copy of input event handle */
1502 console_wait_event = 0;
1504 GetStartupInfoA(&siCurrent);
1506 memset(&siConsole, 0, sizeof(siConsole));
1507 siConsole.cb = sizeof(siConsole);
1508 /* setup a view arguments for wineconsole (it'll use them as default values) */
1509 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1511 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1512 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1513 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1515 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1517 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1518 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1520 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1522 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1523 siConsole.wShowWindow = siCurrent.wShowWindow;
1525 /* FIXME (should pass the unicode form) */
1526 if (siCurrent.lpTitle)
1527 siConsole.lpTitle = siCurrent.lpTitle;
1528 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1530 buffer[sizeof(buffer) - 1] = '\0';
1531 siConsole.lpTitle = buffer;
1534 if (!start_console_renderer(&siConsole))
1537 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1538 /* all std I/O handles are inheritable by default */
1539 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1540 TRUE, OPEN_EXISTING );
1541 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1543 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1544 TRUE, OPEN_EXISTING );
1545 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1547 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1548 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1551 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1552 handle_in = siCurrent.hStdInput;
1553 handle_out = siCurrent.hStdOutput;
1554 handle_err = siCurrent.hStdError;
1557 /* NT resets the STD_*_HANDLEs on console alloc */
1558 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1559 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1560 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1562 SetLastError(ERROR_SUCCESS);
1567 ERR("Can't allocate console\n");
1568 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1569 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1570 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1576 /***********************************************************************
1577 * ReadConsoleA (KERNEL32.@)
1579 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1580 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1582 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1586 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1587 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1589 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1590 HeapFree(GetProcessHeap(), 0, ptr);
1595 /***********************************************************************
1596 * ReadConsoleW (KERNEL32.@)
1598 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1599 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1602 LPWSTR xbuf = lpBuffer;
1606 TRACE("(%p,%p,%d,%p,%p)\n",
1607 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1609 if (!get_console_mode(hConsoleInput, &mode, &is_bare))
1612 if (mode & ENABLE_LINE_INPUT)
1614 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1616 HeapFree(GetProcessHeap(), 0, S_EditString);
1617 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1621 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1622 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1623 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1624 S_EditStrPos += charsread;
1629 DWORD timeout = INFINITE;
1631 /* FIXME: should we read at least 1 char? The SDK does not say */
1632 /* wait for at least one available input record (it doesn't mean we'll have
1633 * chars stored in xbuf...)
1635 * Although SDK doc keeps silence about 1 char, SDK examples assume
1636 * that we should wait for at least one character (not key). --KS
1641 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1642 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1643 ir.Event.KeyEvent.uChar.UnicodeChar)
1645 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1648 } while (charsread < nNumberOfCharsToRead);
1649 /* nothing has been read */
1650 if (timeout == INFINITE) return FALSE;
1653 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1659 /***********************************************************************
1660 * ReadConsoleInputW (KERNEL32.@)
1662 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1663 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1666 DWORD timeout = INFINITE;
1670 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1674 /* loop until we get at least one event */
1675 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1679 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1684 /******************************************************************************
1685 * WriteConsoleOutputCharacterW [KERNEL32.@]
1687 * Copy character to consecutive cells in the console screen buffer.
1690 * hConsoleOutput [I] Handle to screen buffer
1691 * str [I] Pointer to buffer with chars to write
1692 * length [I] Number of cells to write to
1693 * coord [I] Coords of first cell
1694 * lpNumCharsWritten [O] Pointer to number of cells written
1701 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1702 COORD coord, LPDWORD lpNumCharsWritten )
1706 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1707 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1709 SERVER_START_REQ( write_console_output )
1711 req->handle = console_handle_unmap(hConsoleOutput);
1714 req->mode = CHAR_INFO_MODE_TEXT;
1716 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1717 if ((ret = !wine_server_call_err( req )))
1719 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1727 /******************************************************************************
1728 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1731 * title [I] Address of new title
1737 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1741 TRACE("(%s)\n", debugstr_w(title));
1742 SERVER_START_REQ( set_console_input_info )
1745 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1746 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1747 ret = !wine_server_call_err( req );
1754 /***********************************************************************
1755 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1757 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1759 FIXME("(%p): stub\n", nrofbuttons);
1764 /******************************************************************************
1765 * SetConsoleInputExeNameW [KERNEL32.@]
1767 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1769 TRACE("(%s)\n", debugstr_w(name));
1771 if (!name || !name[0])
1773 SetLastError(ERROR_INVALID_PARAMETER);
1777 RtlEnterCriticalSection(&CONSOLE_CritSect);
1778 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1779 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1784 /******************************************************************************
1785 * SetConsoleInputExeNameA [KERNEL32.@]
1787 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1793 if (!name || !name[0])
1795 SetLastError(ERROR_INVALID_PARAMETER);
1799 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1800 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1802 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1803 ret = SetConsoleInputExeNameW(nameW);
1804 HeapFree(GetProcessHeap(), 0, nameW);
1809 /******************************************************************
1810 * CONSOLE_DefaultHandler
1812 * Final control event handler
1814 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1816 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1818 /* should never go here */
1822 /******************************************************************************
1823 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1826 * func [I] Address of handler function
1827 * add [I] Handler to add or remove
1834 struct ConsoleHandler
1836 PHANDLER_ROUTINE handler;
1837 struct ConsoleHandler* next;
1840 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1841 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1843 /*****************************************************************************/
1845 /******************************************************************
1846 * SetConsoleCtrlHandler (KERNEL32.@)
1848 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1852 TRACE("(%p,%i)\n", func, add);
1856 RtlEnterCriticalSection(&CONSOLE_CritSect);
1858 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1860 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1861 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1865 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1867 if (!ch) return FALSE;
1869 RtlEnterCriticalSection(&CONSOLE_CritSect);
1870 ch->next = CONSOLE_Handlers;
1871 CONSOLE_Handlers = ch;
1872 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1876 struct ConsoleHandler** ch;
1877 RtlEnterCriticalSection(&CONSOLE_CritSect);
1878 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1880 if ((*ch)->handler == func) break;
1884 struct ConsoleHandler* rch = *ch;
1887 if (rch == &CONSOLE_DefaultConsoleHandler)
1889 ERR("Who's trying to remove default handler???\n");
1890 SetLastError(ERROR_INVALID_PARAMETER);
1896 HeapFree(GetProcessHeap(), 0, rch);
1901 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1902 SetLastError(ERROR_INVALID_PARAMETER);
1905 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1910 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1912 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1913 return EXCEPTION_EXECUTE_HANDLER;
1916 /******************************************************************
1917 * CONSOLE_SendEventThread
1919 * Internal helper to pass an event to the list on installed handlers
1921 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1923 DWORD_PTR event = (DWORD_PTR)pmt;
1924 struct ConsoleHandler* ch;
1926 if (event == CTRL_C_EVENT)
1928 BOOL caught_by_dbg = TRUE;
1929 /* First, try to pass the ctrl-C event to the debugger (if any)
1930 * If it continues, there's nothing more to do
1931 * Otherwise, we need to send the ctrl-C event to the handlers
1935 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1937 __EXCEPT(CONSOLE_CtrlEventHandler)
1939 caught_by_dbg = FALSE;
1942 if (caught_by_dbg) return 0;
1943 /* the debugger didn't continue... so, pass to ctrl handlers */
1945 RtlEnterCriticalSection(&CONSOLE_CritSect);
1946 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1948 if (ch->handler(event)) break;
1950 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1954 /******************************************************************
1955 * CONSOLE_HandleCtrlC
1957 * Check whether the shall manipulate CtrlC events
1959 int CONSOLE_HandleCtrlC(unsigned sig)
1961 /* FIXME: better test whether a console is attached to this process ??? */
1962 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1963 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1965 /* check if we have to ignore ctrl-C events */
1966 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1968 /* Create a separate thread to signal all the events.
1969 * This is needed because:
1970 * - this function can be called in an Unix signal handler (hence on an
1971 * different stack than the thread that's running). This breaks the
1972 * Win32 exception mechanisms (where the thread's stack is checked).
1973 * - since the current thread, while processing the signal, can hold the
1974 * console critical section, we need another execution environment where
1975 * we can wait on this critical section
1977 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1982 /******************************************************************************
1983 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1986 * dwCtrlEvent [I] Type of event
1987 * dwProcessGroupID [I] Process group ID to send event to
1991 * Failure: False (and *should* [but doesn't] set LastError)
1993 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1994 DWORD dwProcessGroupID)
1998 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2000 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2002 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2006 SERVER_START_REQ( send_console_signal )
2008 req->signal = dwCtrlEvent;
2009 req->group_id = dwProcessGroupID;
2010 ret = !wine_server_call_err( req );
2014 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2015 * have been handled by all processes in the given group?
2016 * As of today, we don't wait...
2022 /******************************************************************************
2023 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2026 * dwDesiredAccess [I] Access flag
2027 * dwShareMode [I] Buffer share mode
2028 * sa [I] Security attributes
2029 * dwFlags [I] Type of buffer to create
2030 * lpScreenBufferData [I] Reserved
2033 * Should call SetLastError
2036 * Success: Handle to new console screen buffer
2037 * Failure: INVALID_HANDLE_VALUE
2039 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2040 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2041 LPVOID lpScreenBufferData)
2043 HANDLE ret = INVALID_HANDLE_VALUE;
2045 TRACE("(%d,%d,%p,%d,%p)\n",
2046 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2048 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2050 SetLastError(ERROR_INVALID_PARAMETER);
2051 return INVALID_HANDLE_VALUE;
2054 SERVER_START_REQ(create_console_output)
2057 req->access = dwDesiredAccess;
2058 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2059 req->share = dwShareMode;
2061 if (!wine_server_call_err( req ))
2062 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2070 /***********************************************************************
2071 * GetConsoleScreenBufferInfo (KERNEL32.@)
2073 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2077 SERVER_START_REQ(get_console_output_info)
2079 req->handle = console_handle_unmap(hConsoleOutput);
2080 if ((ret = !wine_server_call_err( req )))
2082 csbi->dwSize.X = reply->width;
2083 csbi->dwSize.Y = reply->height;
2084 csbi->dwCursorPosition.X = reply->cursor_x;
2085 csbi->dwCursorPosition.Y = reply->cursor_y;
2086 csbi->wAttributes = reply->attr;
2087 csbi->srWindow.Left = reply->win_left;
2088 csbi->srWindow.Right = reply->win_right;
2089 csbi->srWindow.Top = reply->win_top;
2090 csbi->srWindow.Bottom = reply->win_bottom;
2091 csbi->dwMaximumWindowSize.X = reply->max_width;
2092 csbi->dwMaximumWindowSize.Y = reply->max_height;
2097 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2098 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2099 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2101 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2102 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2108 /******************************************************************************
2109 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2115 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2119 TRACE("(%p)\n", hConsoleOutput);
2121 SERVER_START_REQ( set_console_input_info )
2124 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2125 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2126 ret = !wine_server_call_err( req );
2133 /***********************************************************************
2134 * GetConsoleMode (KERNEL32.@)
2136 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2138 return get_console_mode(hcon, mode, NULL);
2142 /******************************************************************************
2143 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2146 * hcon [I] Handle to console input or screen buffer
2147 * mode [I] Input or output mode to set
2154 * ENABLE_PROCESSED_INPUT 0x01
2155 * ENABLE_LINE_INPUT 0x02
2156 * ENABLE_ECHO_INPUT 0x04
2157 * ENABLE_WINDOW_INPUT 0x08
2158 * ENABLE_MOUSE_INPUT 0x10
2160 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2164 SERVER_START_REQ(set_console_mode)
2166 req->handle = console_handle_unmap(hcon);
2168 ret = !wine_server_call_err( req );
2171 /* FIXME: when resetting a console input to editline mode, I think we should
2172 * empty the S_EditString buffer
2175 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2181 /******************************************************************
2182 * CONSOLE_WriteChars
2184 * WriteConsoleOutput helper: hides server call semantics
2185 * writes a string at a given pos with standard attribute
2187 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2193 SERVER_START_REQ( write_console_output )
2195 req->handle = console_handle_unmap(hCon);
2198 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2200 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2201 if (!wine_server_call_err( req )) written = reply->written;
2205 if (written > 0) pos->X += written;
2209 /******************************************************************
2212 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2215 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2221 csbi->dwCursorPosition.X = 0;
2222 csbi->dwCursorPosition.Y++;
2224 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2227 src.Bottom = csbi->dwSize.Y - 1;
2229 src.Right = csbi->dwSize.X - 1;
2234 ci.Attributes = csbi->wAttributes;
2235 ci.Char.UnicodeChar = ' ';
2237 csbi->dwCursorPosition.Y--;
2238 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2243 /******************************************************************
2246 * WriteConsoleOutput helper: writes a block of non special characters
2247 * Block can spread on several lines, and wrapping, if needed, is
2251 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2252 DWORD mode, LPCWSTR ptr, int len)
2254 int blk; /* number of chars to write on current line */
2255 int done; /* number of chars already written */
2257 if (len <= 0) return 1;
2259 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2261 for (done = 0; done < len; done += blk)
2263 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2265 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2267 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2273 int pos = csbi->dwCursorPosition.X;
2274 /* FIXME: we could reduce the number of loops
2275 * but, in most cases we wouldn't gain lots of time (it would only
2276 * happen if we're asked to overwrite more than twice the part of the line,
2279 for (done = 0; done < len; done += blk)
2281 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2283 csbi->dwCursorPosition.X = pos;
2284 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2292 /***********************************************************************
2293 * WriteConsoleW (KERNEL32.@)
2295 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2296 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2300 const WCHAR* psz = lpBuffer;
2301 CONSOLE_SCREEN_BUFFER_INFO csbi;
2305 TRACE("%p %s %d %p %p\n",
2306 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2307 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2309 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2311 if (!get_console_mode(hConsoleOutput, &mode, &bare)) return FALSE;
2319 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2322 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2323 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2326 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2327 ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2328 ptr, len, lpNumberOfCharsWritten, NULL);
2329 if (ret && lpNumberOfCharsWritten)
2331 if (*lpNumberOfCharsWritten == len)
2332 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2334 FIXME("Conversion not supported yet\n");
2336 HeapFree(GetProcessHeap(), 0, ptr);
2340 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2343 if (!nNumberOfCharsToWrite) return TRUE;
2345 if (mode & ENABLE_PROCESSED_OUTPUT)
2349 for (i = 0; i < nNumberOfCharsToWrite; i++)
2353 case '\b': case '\t': case '\n': case '\a': case '\r':
2354 /* don't handle here the i-th char... done below */
2355 if ((k = i - first) > 0)
2357 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2367 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2371 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2373 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2374 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2379 next_line(hConsoleOutput, &csbi);
2385 csbi.dwCursorPosition.X = 0;
2393 /* write the remaining block (if any) if processed output is enabled, or the
2394 * entire buffer otherwise
2396 if ((k = nNumberOfCharsToWrite - first) > 0)
2398 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2404 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2405 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2410 /***********************************************************************
2411 * WriteConsoleA (KERNEL32.@)
2413 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2414 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2420 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2422 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2423 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2424 if (!xstring) return 0;
2426 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2428 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2430 HeapFree(GetProcessHeap(), 0, xstring);
2435 /******************************************************************************
2436 * SetConsoleCursorPosition [KERNEL32.@]
2437 * Sets the cursor position in console
2440 * hConsoleOutput [I] Handle of console screen buffer
2441 * dwCursorPosition [I] New cursor position coordinates
2447 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2450 CONSOLE_SCREEN_BUFFER_INFO csbi;
2454 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2456 SERVER_START_REQ(set_console_output_info)
2458 req->handle = console_handle_unmap(hcon);
2459 req->cursor_x = pos.X;
2460 req->cursor_y = pos.Y;
2461 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2462 ret = !wine_server_call_err( req );
2466 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2469 /* if cursor is no longer visible, scroll the visible window... */
2470 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2471 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2472 if (pos.X < csbi.srWindow.Left)
2474 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2477 else if (pos.X > csbi.srWindow.Right)
2479 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2482 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2484 if (pos.Y < csbi.srWindow.Top)
2486 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2489 else if (pos.Y > csbi.srWindow.Bottom)
2491 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2494 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2496 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2501 /******************************************************************************
2502 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2505 * hcon [I] Handle to console screen buffer
2506 * cinfo [O] Address of cursor information
2512 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2516 SERVER_START_REQ(get_console_output_info)
2518 req->handle = console_handle_unmap(hCon);
2519 ret = !wine_server_call_err( req );
2522 cinfo->dwSize = reply->cursor_size;
2523 cinfo->bVisible = reply->cursor_visible;
2528 if (!ret) return FALSE;
2532 SetLastError(ERROR_INVALID_ACCESS);
2535 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2541 /******************************************************************************
2542 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2545 * hcon [I] Handle to console screen buffer
2546 * cinfo [I] Address of cursor information
2551 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2555 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2556 SERVER_START_REQ(set_console_output_info)
2558 req->handle = console_handle_unmap(hCon);
2559 req->cursor_size = cinfo->dwSize;
2560 req->cursor_visible = cinfo->bVisible;
2561 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2562 ret = !wine_server_call_err( req );
2569 /******************************************************************************
2570 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2573 * hcon [I] Handle to console screen buffer
2574 * bAbsolute [I] Coordinate type flag
2575 * window [I] Address of new window rectangle
2580 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2582 SMALL_RECT p = *window;
2585 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2589 CONSOLE_SCREEN_BUFFER_INFO csbi;
2591 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2593 p.Left += csbi.srWindow.Left;
2594 p.Top += csbi.srWindow.Top;
2595 p.Right += csbi.srWindow.Right;
2596 p.Bottom += csbi.srWindow.Bottom;
2598 SERVER_START_REQ(set_console_output_info)
2600 req->handle = console_handle_unmap(hCon);
2601 req->win_left = p.Left;
2602 req->win_top = p.Top;
2603 req->win_right = p.Right;
2604 req->win_bottom = p.Bottom;
2605 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2606 ret = !wine_server_call_err( req );
2614 /******************************************************************************
2615 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2617 * Sets the foreground and background color attributes of characters
2618 * written to the screen buffer.
2624 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2628 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2629 SERVER_START_REQ(set_console_output_info)
2631 req->handle = console_handle_unmap(hConsoleOutput);
2633 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2634 ret = !wine_server_call_err( req );
2641 /******************************************************************************
2642 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2645 * hConsoleOutput [I] Handle to console screen buffer
2646 * dwSize [I] New size in character rows and cols
2652 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2656 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2657 SERVER_START_REQ(set_console_output_info)
2659 req->handle = console_handle_unmap(hConsoleOutput);
2660 req->width = dwSize.X;
2661 req->height = dwSize.Y;
2662 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2663 ret = !wine_server_call_err( req );
2670 /******************************************************************************
2671 * ScrollConsoleScreenBufferA [KERNEL32.@]
2674 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2675 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2680 ciw.Attributes = lpFill->Attributes;
2681 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2683 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2684 dwDestOrigin, &ciw);
2687 /******************************************************************
2688 * CONSOLE_FillLineUniform
2690 * Helper function for ScrollConsoleScreenBufferW
2691 * Fills a part of a line with a constant character info
2693 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2695 SERVER_START_REQ( fill_console_output )
2697 req->handle = console_handle_unmap(hConsoleOutput);
2698 req->mode = CHAR_INFO_MODE_TEXTATTR;
2703 req->data.ch = lpFill->Char.UnicodeChar;
2704 req->data.attr = lpFill->Attributes;
2705 wine_server_call_err( req );
2710 /******************************************************************************
2711 * ScrollConsoleScreenBufferW [KERNEL32.@]
2715 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2716 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2724 CONSOLE_SCREEN_BUFFER_INFO csbi;
2729 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2730 lpScrollRect->Left, lpScrollRect->Top,
2731 lpScrollRect->Right, lpScrollRect->Bottom,
2732 lpClipRect->Left, lpClipRect->Top,
2733 lpClipRect->Right, lpClipRect->Bottom,
2734 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2736 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2737 lpScrollRect->Left, lpScrollRect->Top,
2738 lpScrollRect->Right, lpScrollRect->Bottom,
2739 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2741 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2744 src.X = lpScrollRect->Left;
2745 src.Y = lpScrollRect->Top;
2747 /* step 1: get dst rect */
2748 dst.Left = dwDestOrigin.X;
2749 dst.Top = dwDestOrigin.Y;
2750 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2751 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2753 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2756 clip.Left = max(0, lpClipRect->Left);
2757 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2758 clip.Top = max(0, lpClipRect->Top);
2759 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2764 clip.Right = csbi.dwSize.X - 1;
2766 clip.Bottom = csbi.dwSize.Y - 1;
2768 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2770 /* step 2b: clip dst rect */
2771 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2772 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2773 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2774 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2776 /* step 3: transfer the bits */
2777 SERVER_START_REQ(move_console_output)
2779 req->handle = console_handle_unmap(hConsoleOutput);
2782 req->x_dst = dst.Left;
2783 req->y_dst = dst.Top;
2784 req->w = dst.Right - dst.Left + 1;
2785 req->h = dst.Bottom - dst.Top + 1;
2786 ret = !wine_server_call_err( req );
2790 if (!ret) return FALSE;
2792 /* step 4: clean out the exposed part */
2794 /* have to write cell [i,j] if it is not in dst rect (because it has already
2795 * been written to by the scroll) and is in clip (we shall not write
2798 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2800 inside = dst.Top <= j && j <= dst.Bottom;
2802 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2804 if (inside && dst.Left <= i && i <= dst.Right)
2808 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2814 if (start == -1) start = i;
2818 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2824 /******************************************************************
2825 * AttachConsole (KERNEL32.@)
2827 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2829 FIXME("stub %x\n",dwProcessId);
2833 /******************************************************************
2834 * GetConsoleDisplayMode (KERNEL32.@)
2836 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2838 TRACE("semi-stub: %p\n", lpModeFlags);
2839 /* It is safe to successfully report windowed mode */
2844 /******************************************************************
2845 * SetConsoleDisplayMode (KERNEL32.@)
2847 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2848 COORD *lpNewScreenBufferDimensions)
2850 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2851 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2854 /* We cannot switch to fullscreen */
2861 /* ====================================================================
2863 * Console manipulation functions
2865 * ====================================================================*/
2867 /* some missing functions...
2868 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2869 * should get the right API and implement them
2870 * GetConsoleCommandHistory[AW] (dword dword dword)
2871 * GetConsoleCommandHistoryLength[AW]
2872 * SetConsoleCommandHistoryMode
2873 * SetConsoleNumberOfCommands[AW]
2875 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2879 SERVER_START_REQ( get_console_input_history )
2883 if (buf && buf_len > 1)
2885 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2887 if (!wine_server_call_err( req ))
2889 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2890 len = reply->total / sizeof(WCHAR) + 1;
2897 /******************************************************************
2898 * CONSOLE_AppendHistory
2902 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2904 size_t len = strlenW(ptr);
2907 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2908 if (!len) return FALSE;
2910 SERVER_START_REQ( append_console_input_history )
2913 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2914 ret = !wine_server_call_err( req );
2920 /******************************************************************
2921 * CONSOLE_GetNumHistoryEntries
2925 unsigned CONSOLE_GetNumHistoryEntries(void)
2928 SERVER_START_REQ(get_console_input_info)
2931 if (!wine_server_call_err( req )) ret = reply->history_index;
2937 /******************************************************************
2938 * CONSOLE_GetEditionMode
2942 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2944 unsigned ret = FALSE;
2945 SERVER_START_REQ(get_console_input_info)
2947 req->handle = console_handle_unmap(hConIn);
2948 if ((ret = !wine_server_call_err( req )))
2949 *mode = reply->edition_mode;
2955 /******************************************************************
2960 * 0 if an error occurred, non-zero for success
2963 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
2964 DWORD TargetBufferLength, LPWSTR lpExename)
2966 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
2967 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2971 /******************************************************************
2972 * GetConsoleProcessList (KERNEL32.@)
2974 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
2976 FIXME("(%p,%d): stub\n", processlist, processcount);
2978 if (!processlist || processcount < 1)
2980 SetLastError(ERROR_INVALID_PARAMETER);
2987 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
2989 memset(&S_termios, 0, sizeof(S_termios));
2990 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
2994 /* FIXME: to be done even if program is a GUI ? */
2995 /* This is wine specific: we have no parent (we're started from unix)
2996 * so, create a simple console with bare handles
2998 wine_server_send_fd(0);
2999 SERVER_START_REQ( alloc_console )
3001 req->access = GENERIC_READ | GENERIC_WRITE;
3002 req->attributes = OBJ_INHERIT;
3003 req->pid = 0xffffffff;
3005 wine_server_call( req );
3006 conin = wine_server_ptr_handle( reply->handle_in );
3007 /* reply->event shouldn't be created by server */
3011 if (!params->hStdInput)
3012 params->hStdInput = conin;
3014 if (!params->hStdOutput)
3016 wine_server_send_fd(1);
3017 SERVER_START_REQ( create_console_output )
3019 req->handle_in = wine_server_obj_handle(conin);
3020 req->access = GENERIC_WRITE|GENERIC_READ;
3021 req->attributes = OBJ_INHERIT;
3022 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3024 wine_server_call(req);
3025 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3029 if (!params->hStdError)
3031 wine_server_send_fd(2);
3032 SERVER_START_REQ( create_console_output )
3034 req->handle_in = wine_server_obj_handle(conin);
3035 req->access = GENERIC_WRITE|GENERIC_READ;
3036 req->attributes = OBJ_INHERIT;
3037 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3039 wine_server_call(req);
3040 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3046 /* convert value from server:
3047 * + 0 => INVALID_HANDLE_VALUE
3048 * + console handle needs to be mapped
3050 if (!params->hStdInput)
3051 params->hStdInput = INVALID_HANDLE_VALUE;
3052 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3054 params->hStdInput = console_handle_map(params->hStdInput);
3055 save_console_mode(params->hStdInput);
3058 if (!params->hStdOutput)
3059 params->hStdOutput = INVALID_HANDLE_VALUE;
3060 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3061 params->hStdOutput = console_handle_map(params->hStdOutput);
3063 if (!params->hStdError)
3064 params->hStdError = INVALID_HANDLE_VALUE;
3065 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3066 params->hStdError = console_handle_map(params->hStdError);
3071 BOOL CONSOLE_Exit(void)
3073 /* the console is in raw mode, put it back in cooked mode */
3074 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));