ddraw/tests: Rewrite LimitTest().
[wine.git] / dlls / kernel32 / console.c
blob51061de922c50f56220b408d25fb28928151a5aa
1 /*
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,2010 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.
31 #include "config.h"
32 #include "wine/port.h"
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <limits.h>
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
41 #include <assert.h>
42 #ifdef HAVE_TERMIOS_H
43 # include <termios.h>
44 #endif
45 #ifdef HAVE_SYS_POLL_H
46 # include <sys/poll.h>
47 #endif
49 #define NONAMELESSUNION
50 #include "ntstatus.h"
51 #define WIN32_NO_STATUS
52 #include "windef.h"
53 #include "winbase.h"
54 #include "winnls.h"
55 #include "winerror.h"
56 #include "wincon.h"
57 #include "wine/server.h"
58 #include "wine/exception.h"
59 #include "wine/unicode.h"
60 #include "wine/debug.h"
61 #include "excpt.h"
62 #include "console_private.h"
63 #include "kernel_private.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(console);
67 static CRITICAL_SECTION CONSOLE_CritSect;
68 static CRITICAL_SECTION_DEBUG critsect_debug =
70 0, 0, &CONSOLE_CritSect,
71 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
72 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
74 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
76 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
77 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
79 /* FIXME: this is not thread safe */
80 static HANDLE console_wait_event;
82 /* map input records to ASCII */
83 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
85 int i;
86 char ch;
88 for (i = 0; i < count; i++)
90 if (buffer[i].EventType != KEY_EVENT) continue;
91 WideCharToMultiByte( GetConsoleCP(), 0,
92 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
93 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
97 /* map input records to Unicode */
98 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
100 int i;
101 WCHAR ch;
103 for (i = 0; i < count; i++)
105 if (buffer[i].EventType != KEY_EVENT) continue;
106 MultiByteToWideChar( GetConsoleCP(), 0,
107 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
108 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
112 /* map char infos to ASCII */
113 static void char_info_WtoA( CHAR_INFO *buffer, int count )
115 char ch;
117 while (count-- > 0)
119 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
120 &ch, 1, NULL, NULL );
121 buffer->Char.AsciiChar = ch;
122 buffer++;
126 /* map char infos to Unicode */
127 static void char_info_AtoW( CHAR_INFO *buffer, int count )
129 WCHAR ch;
131 while (count-- > 0)
133 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
134 buffer->Char.UnicodeChar = ch;
135 buffer++;
139 static struct termios S_termios; /* saved termios for bare consoles */
140 static BOOL S_termios_raw /* = FALSE */;
142 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
143 * - a bare console is created for all CUI programs started from command line (without
144 * wineconsole) (let's call those PS)
145 * - of course, every child of a PS which requires console inheritance will get it
146 * - the console termios attributes are saved at the start of program which is attached to be
147 * bare console
148 * - if any program attached to a bare console requests input from console, the console is
149 * turned into raw mode
150 * - when the program which created the bare console (the program started from command line)
151 * exits, it will restore the console termios attributes it saved at startup (this
152 * will put back the console into cooked mode if it had been put in raw mode)
153 * - if any other program attached to this bare console is still alive, the Unix shell will put
154 * it in the background, hence forbidding access to the console. Therefore, reading console
155 * input will not be available when the bare console creator has died.
156 * FIXME: This is a limitation of current implementation
159 /* returns the fd for a bare console (-1 otherwise) */
160 static int get_console_bare_fd(HANDLE hin)
162 int fd;
164 if (is_console_handle(hin) &&
165 wine_server_handle_to_fd(wine_server_ptr_handle(console_handle_unmap(hin)),
166 0, &fd, NULL) == STATUS_SUCCESS)
167 return fd;
168 return -1;
171 static BOOL save_console_mode(HANDLE hin)
173 int fd;
174 BOOL ret;
176 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
177 ret = tcgetattr(fd, &S_termios) >= 0;
178 close(fd);
179 return ret;
182 static BOOL put_console_into_raw_mode(int fd)
184 RtlEnterCriticalSection(&CONSOLE_CritSect);
185 if (!S_termios_raw)
187 struct termios term = S_termios;
189 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
190 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
191 term.c_cflag &= ~(CSIZE | PARENB);
192 term.c_cflag |= CS8;
193 /* FIXME: we should actually disable output processing here
194 * and let kernel32/console.c do the job (with support of enable/disable of
195 * processed output)
197 /* term.c_oflag &= ~(OPOST); */
198 term.c_cc[VMIN] = 1;
199 term.c_cc[VTIME] = 0;
200 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
202 RtlLeaveCriticalSection(&CONSOLE_CritSect);
204 return S_termios_raw;
207 /* put back the console in cooked mode iff we're the process which created the bare console
208 * we don't test if this process has set the console in raw mode as it could be one of its
209 * children who did it
211 static BOOL restore_console_mode(HANDLE hin)
213 int fd;
214 BOOL ret = TRUE;
216 if (S_termios_raw)
218 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
219 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
220 close(fd);
223 if (RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
224 TERM_Exit();
226 return ret;
229 /******************************************************************************
230 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
232 * RETURNS
233 * Success: hwnd of the console window.
234 * Failure: NULL
236 HWND WINAPI GetConsoleWindow(VOID)
238 HWND hWnd = NULL;
240 SERVER_START_REQ(get_console_input_info)
242 req->handle = 0;
243 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
245 SERVER_END_REQ;
247 return hWnd;
251 /******************************************************************************
252 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
254 * RETURNS
255 * Code page code
257 UINT WINAPI GetConsoleCP(VOID)
259 BOOL ret;
260 UINT codepage = GetOEMCP(); /* default value */
262 SERVER_START_REQ(get_console_input_info)
264 req->handle = 0;
265 ret = !wine_server_call_err(req);
266 if (ret && reply->input_cp)
267 codepage = reply->input_cp;
269 SERVER_END_REQ;
271 return codepage;
275 /******************************************************************************
276 * SetConsoleCP [KERNEL32.@]
278 BOOL WINAPI SetConsoleCP(UINT cp)
280 BOOL ret;
282 if (!IsValidCodePage(cp))
284 SetLastError(ERROR_INVALID_PARAMETER);
285 return FALSE;
288 SERVER_START_REQ(set_console_input_info)
290 req->handle = 0;
291 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
292 req->input_cp = cp;
293 ret = !wine_server_call_err(req);
295 SERVER_END_REQ;
297 return ret;
301 /***********************************************************************
302 * GetConsoleOutputCP (KERNEL32.@)
304 UINT WINAPI GetConsoleOutputCP(VOID)
306 BOOL ret;
307 UINT codepage = GetOEMCP(); /* default value */
309 SERVER_START_REQ(get_console_input_info)
311 req->handle = 0;
312 ret = !wine_server_call_err(req);
313 if (ret && reply->output_cp)
314 codepage = reply->output_cp;
316 SERVER_END_REQ;
318 return codepage;
322 /******************************************************************************
323 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
325 * PARAMS
326 * cp [I] code page to set
328 * RETURNS
329 * Success: TRUE
330 * Failure: FALSE
332 BOOL WINAPI SetConsoleOutputCP(UINT cp)
334 BOOL ret;
336 if (!IsValidCodePage(cp))
338 SetLastError(ERROR_INVALID_PARAMETER);
339 return FALSE;
342 SERVER_START_REQ(set_console_input_info)
344 req->handle = 0;
345 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
346 req->output_cp = cp;
347 ret = !wine_server_call_err(req);
349 SERVER_END_REQ;
351 return ret;
355 /***********************************************************************
356 * Beep (KERNEL32.@)
358 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
360 static const char beep = '\a';
361 /* dwFreq and dwDur are ignored by Win95 */
362 if (isatty(2)) write( 2, &beep, 1 );
363 return TRUE;
367 /******************************************************************
368 * OpenConsoleW (KERNEL32.@)
370 * Undocumented
371 * Open a handle to the current process console.
372 * Returns INVALID_HANDLE_VALUE on failure.
374 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
376 HANDLE output = INVALID_HANDLE_VALUE;
377 HANDLE ret;
379 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
381 if (name)
383 if (strcmpiW(coninW, name) == 0)
384 output = (HANDLE) FALSE;
385 else if (strcmpiW(conoutW, name) == 0)
386 output = (HANDLE) TRUE;
389 if (output == INVALID_HANDLE_VALUE || creation != OPEN_EXISTING)
391 SetLastError(ERROR_INVALID_PARAMETER);
392 return INVALID_HANDLE_VALUE;
395 SERVER_START_REQ( open_console )
397 req->from = wine_server_obj_handle( output );
398 req->access = access;
399 req->attributes = inherit ? OBJ_INHERIT : 0;
400 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
401 wine_server_call_err( req );
402 ret = wine_server_ptr_handle( reply->handle );
404 SERVER_END_REQ;
405 if (ret)
406 ret = console_handle_map(ret);
408 return ret;
411 /******************************************************************
412 * VerifyConsoleIoHandle (KERNEL32.@)
414 * Undocumented
416 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
418 BOOL ret;
420 if (!is_console_handle(handle)) return FALSE;
421 SERVER_START_REQ(get_console_mode)
423 req->handle = console_handle_unmap(handle);
424 ret = !wine_server_call( req );
426 SERVER_END_REQ;
427 return ret;
430 /******************************************************************
431 * DuplicateConsoleHandle (KERNEL32.@)
433 * Undocumented
435 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
436 DWORD options)
438 HANDLE ret;
440 if (!is_console_handle(handle) ||
441 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
442 GetCurrentProcess(), &ret, access, inherit, options))
443 return INVALID_HANDLE_VALUE;
444 return console_handle_map(ret);
447 /******************************************************************
448 * CloseConsoleHandle (KERNEL32.@)
450 * Undocumented
452 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
454 if (!is_console_handle(handle))
456 SetLastError(ERROR_INVALID_PARAMETER);
457 return FALSE;
459 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
462 /******************************************************************
463 * GetConsoleInputWaitHandle (KERNEL32.@)
465 * Undocumented
467 HANDLE WINAPI GetConsoleInputWaitHandle(void)
469 if (!console_wait_event)
471 SERVER_START_REQ(get_console_wait_event)
473 if (!wine_server_call_err( req ))
474 console_wait_event = wine_server_ptr_handle( reply->handle );
476 SERVER_END_REQ;
478 return console_wait_event;
482 /******************************************************************************
483 * WriteConsoleInputA [KERNEL32.@]
485 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
486 DWORD count, LPDWORD written )
488 INPUT_RECORD *recW = NULL;
489 BOOL ret;
491 if (count > 0)
493 if (!buffer)
495 SetLastError( ERROR_INVALID_ACCESS );
496 return FALSE;
499 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) )))
501 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
502 return FALSE;
505 memcpy( recW, buffer, count * sizeof(*recW) );
506 input_records_AtoW( recW, count );
509 ret = WriteConsoleInputW( handle, recW, count, written );
510 HeapFree( GetProcessHeap(), 0, recW );
511 return ret;
515 /******************************************************************************
516 * WriteConsoleInputW [KERNEL32.@]
518 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
519 DWORD count, LPDWORD written )
521 DWORD events_written = 0;
522 BOOL ret;
524 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
526 if (count > 0 && !buffer)
528 SetLastError(ERROR_INVALID_ACCESS);
529 return FALSE;
532 SERVER_START_REQ( write_console_input )
534 req->handle = console_handle_unmap(handle);
535 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
536 if ((ret = !wine_server_call_err( req )))
537 events_written = reply->written;
539 SERVER_END_REQ;
541 if (written) *written = events_written;
542 else
544 SetLastError(ERROR_INVALID_ACCESS);
545 ret = FALSE;
547 return ret;
551 /***********************************************************************
552 * WriteConsoleOutputA (KERNEL32.@)
554 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
555 COORD size, COORD coord, LPSMALL_RECT region )
557 int y;
558 BOOL ret;
559 COORD new_size, new_coord;
560 CHAR_INFO *ciw;
562 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
563 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
565 if (new_size.X <= 0 || new_size.Y <= 0)
567 region->Bottom = region->Top + new_size.Y - 1;
568 region->Right = region->Left + new_size.X - 1;
569 return TRUE;
572 /* only copy the useful rectangle */
573 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
574 return FALSE;
575 for (y = 0; y < new_size.Y; y++)
577 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
578 new_size.X * sizeof(CHAR_INFO) );
579 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
581 new_coord.X = new_coord.Y = 0;
582 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
583 HeapFree( GetProcessHeap(), 0, ciw );
584 return ret;
588 /***********************************************************************
589 * WriteConsoleOutputW (KERNEL32.@)
591 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
592 COORD size, COORD coord, LPSMALL_RECT region )
594 int width, height, y;
595 BOOL ret = TRUE;
597 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
598 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
599 region->Left, region->Top, region->Right, region->Bottom);
601 width = min( region->Right - region->Left + 1, size.X - coord.X );
602 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
604 if (width > 0 && height > 0)
606 for (y = 0; y < height; y++)
608 SERVER_START_REQ( write_console_output )
610 req->handle = console_handle_unmap(hConsoleOutput);
611 req->x = region->Left;
612 req->y = region->Top + y;
613 req->mode = CHAR_INFO_MODE_TEXTATTR;
614 req->wrap = FALSE;
615 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
616 width * sizeof(CHAR_INFO));
617 if ((ret = !wine_server_call_err( req )))
619 width = min( width, reply->width - region->Left );
620 height = min( height, reply->height - region->Top );
623 SERVER_END_REQ;
624 if (!ret) break;
627 region->Bottom = region->Top + height - 1;
628 region->Right = region->Left + width - 1;
629 return ret;
633 /******************************************************************************
634 * WriteConsoleOutputCharacterA [KERNEL32.@]
636 * See WriteConsoleOutputCharacterW.
638 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
639 COORD coord, LPDWORD lpNumCharsWritten )
641 BOOL ret;
642 LPWSTR strW = NULL;
643 DWORD lenW = 0;
645 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
646 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
648 if (length > 0)
650 if (!str)
652 SetLastError( ERROR_INVALID_ACCESS );
653 return FALSE;
656 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
658 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
660 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
661 return FALSE;
664 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
667 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
668 HeapFree( GetProcessHeap(), 0, strW );
669 return ret;
673 /******************************************************************************
674 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
675 * the console screen buffer
677 * PARAMS
678 * hConsoleOutput [I] Handle to screen buffer
679 * attr [I] Pointer to buffer with write attributes
680 * length [I] Number of cells to write to
681 * coord [I] Coords of first cell
682 * lpNumAttrsWritten [O] Pointer to number of cells written
684 * RETURNS
685 * Success: TRUE
686 * Failure: FALSE
689 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, const WORD *attr, DWORD length,
690 COORD coord, LPDWORD lpNumAttrsWritten )
692 BOOL ret;
694 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
696 if ((length > 0 && !attr) || !lpNumAttrsWritten)
698 SetLastError(ERROR_INVALID_ACCESS);
699 return FALSE;
702 *lpNumAttrsWritten = 0;
704 SERVER_START_REQ( write_console_output )
706 req->handle = console_handle_unmap(hConsoleOutput);
707 req->x = coord.X;
708 req->y = coord.Y;
709 req->mode = CHAR_INFO_MODE_ATTR;
710 req->wrap = TRUE;
711 wine_server_add_data( req, attr, length * sizeof(WORD) );
712 if ((ret = !wine_server_call_err( req )))
713 *lpNumAttrsWritten = reply->written;
715 SERVER_END_REQ;
716 return ret;
720 /******************************************************************************
721 * FillConsoleOutputCharacterA [KERNEL32.@]
723 * See FillConsoleOutputCharacterW.
725 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
726 COORD coord, LPDWORD lpNumCharsWritten )
728 WCHAR wch;
730 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
731 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
735 /******************************************************************************
736 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
738 * PARAMS
739 * hConsoleOutput [I] Handle to screen buffer
740 * ch [I] Character to write
741 * length [I] Number of cells to write to
742 * coord [I] Coords of first cell
743 * lpNumCharsWritten [O] Pointer to number of cells written
745 * RETURNS
746 * Success: TRUE
747 * Failure: FALSE
749 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
750 COORD coord, LPDWORD lpNumCharsWritten)
752 BOOL ret;
754 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
755 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
757 if (!lpNumCharsWritten)
759 SetLastError(ERROR_INVALID_ACCESS);
760 return FALSE;
763 *lpNumCharsWritten = 0;
765 SERVER_START_REQ( fill_console_output )
767 req->handle = console_handle_unmap(hConsoleOutput);
768 req->x = coord.X;
769 req->y = coord.Y;
770 req->mode = CHAR_INFO_MODE_TEXT;
771 req->wrap = TRUE;
772 req->data.ch = ch;
773 req->count = length;
774 if ((ret = !wine_server_call_err( req )))
775 *lpNumCharsWritten = reply->written;
777 SERVER_END_REQ;
778 return ret;
782 /******************************************************************************
783 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
785 * PARAMS
786 * hConsoleOutput [I] Handle to screen buffer
787 * attr [I] Color attribute to write
788 * length [I] Number of cells to write to
789 * coord [I] Coords of first cell
790 * lpNumAttrsWritten [O] Pointer to number of cells written
792 * RETURNS
793 * Success: TRUE
794 * Failure: FALSE
796 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
797 COORD coord, LPDWORD lpNumAttrsWritten )
799 BOOL ret;
801 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
802 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
804 if (!lpNumAttrsWritten)
806 SetLastError(ERROR_INVALID_ACCESS);
807 return FALSE;
810 *lpNumAttrsWritten = 0;
812 SERVER_START_REQ( fill_console_output )
814 req->handle = console_handle_unmap(hConsoleOutput);
815 req->x = coord.X;
816 req->y = coord.Y;
817 req->mode = CHAR_INFO_MODE_ATTR;
818 req->wrap = TRUE;
819 req->data.attr = attr;
820 req->count = length;
821 if ((ret = !wine_server_call_err( req )))
822 *lpNumAttrsWritten = reply->written;
824 SERVER_END_REQ;
825 return ret;
829 /******************************************************************************
830 * ReadConsoleOutputCharacterA [KERNEL32.@]
833 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
834 COORD coord, LPDWORD read_count)
836 DWORD read;
837 BOOL ret;
838 LPWSTR wptr;
840 if (!read_count)
842 SetLastError(ERROR_INVALID_ACCESS);
843 return FALSE;
846 *read_count = 0;
848 if (!(wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR))))
850 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
851 return FALSE;
854 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
856 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
857 *read_count = read;
859 HeapFree( GetProcessHeap(), 0, wptr );
860 return ret;
864 /******************************************************************************
865 * ReadConsoleOutputCharacterW [KERNEL32.@]
868 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
869 COORD coord, LPDWORD read_count )
871 BOOL ret;
873 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
875 if (!read_count)
877 SetLastError(ERROR_INVALID_ACCESS);
878 return FALSE;
881 *read_count = 0;
883 SERVER_START_REQ( read_console_output )
885 req->handle = console_handle_unmap(hConsoleOutput);
886 req->x = coord.X;
887 req->y = coord.Y;
888 req->mode = CHAR_INFO_MODE_TEXT;
889 req->wrap = TRUE;
890 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
891 if ((ret = !wine_server_call_err( req )))
892 *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
894 SERVER_END_REQ;
895 return ret;
899 /******************************************************************************
900 * ReadConsoleOutputAttribute [KERNEL32.@]
902 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
903 COORD coord, LPDWORD read_count)
905 BOOL ret;
907 TRACE("(%p,%p,%d,%dx%d,%p)\n",
908 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
910 if (!read_count)
912 SetLastError(ERROR_INVALID_ACCESS);
913 return FALSE;
916 *read_count = 0;
918 SERVER_START_REQ( read_console_output )
920 req->handle = console_handle_unmap(hConsoleOutput);
921 req->x = coord.X;
922 req->y = coord.Y;
923 req->mode = CHAR_INFO_MODE_ATTR;
924 req->wrap = TRUE;
925 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
926 if ((ret = !wine_server_call_err( req )))
927 *read_count = wine_server_reply_size(reply) / sizeof(WORD);
929 SERVER_END_REQ;
930 return ret;
934 /******************************************************************************
935 * ReadConsoleOutputA [KERNEL32.@]
938 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
939 COORD coord, LPSMALL_RECT region )
941 BOOL ret;
942 int y;
944 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
945 if (ret && region->Right >= region->Left)
947 for (y = 0; y <= region->Bottom - region->Top; y++)
949 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
950 region->Right - region->Left + 1 );
953 return ret;
957 /******************************************************************************
958 * ReadConsoleOutputW [KERNEL32.@]
960 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
961 * think we need to be *that* compatible. -- AJ
963 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
964 COORD coord, LPSMALL_RECT region )
966 int width, height, y;
967 BOOL ret = TRUE;
969 width = min( region->Right - region->Left + 1, size.X - coord.X );
970 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
972 if (width > 0 && height > 0)
974 for (y = 0; y < height; y++)
976 SERVER_START_REQ( read_console_output )
978 req->handle = console_handle_unmap(hConsoleOutput);
979 req->x = region->Left;
980 req->y = region->Top + y;
981 req->mode = CHAR_INFO_MODE_TEXTATTR;
982 req->wrap = FALSE;
983 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
984 width * sizeof(CHAR_INFO) );
985 if ((ret = !wine_server_call_err( req )))
987 width = min( width, reply->width - region->Left );
988 height = min( height, reply->height - region->Top );
991 SERVER_END_REQ;
992 if (!ret) break;
995 region->Bottom = region->Top + height - 1;
996 region->Right = region->Left + width - 1;
997 return ret;
1001 /******************************************************************************
1002 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
1004 * PARAMS
1005 * handle [I] Handle to console input buffer
1006 * buffer [O] Address of buffer for read data
1007 * count [I] Number of records to read
1008 * pRead [O] Address of number of records read
1010 * RETURNS
1011 * Success: TRUE
1012 * Failure: FALSE
1014 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1016 DWORD read;
1018 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
1019 input_records_WtoA( buffer, read );
1020 if (pRead) *pRead = read;
1021 return TRUE;
1025 /***********************************************************************
1026 * PeekConsoleInputA (KERNEL32.@)
1028 * Gets 'count' first events (or less) from input queue.
1030 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1032 DWORD read;
1034 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
1035 input_records_WtoA( buffer, read );
1036 if (pRead) *pRead = read;
1037 return TRUE;
1041 /***********************************************************************
1042 * PeekConsoleInputW (KERNEL32.@)
1044 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
1046 BOOL ret;
1047 SERVER_START_REQ( read_console_input )
1049 req->handle = console_handle_unmap(handle);
1050 req->flush = FALSE;
1051 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1052 if ((ret = !wine_server_call_err( req )))
1054 if (read) *read = count ? reply->read : 0;
1057 SERVER_END_REQ;
1058 return ret;
1062 /***********************************************************************
1063 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1065 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1067 BOOL ret;
1068 SERVER_START_REQ( read_console_input )
1070 req->handle = console_handle_unmap(handle);
1071 req->flush = FALSE;
1072 if ((ret = !wine_server_call_err( req )))
1074 if (nrofevents)
1075 *nrofevents = reply->read;
1076 else
1078 SetLastError(ERROR_INVALID_ACCESS);
1079 ret = FALSE;
1083 SERVER_END_REQ;
1084 return ret;
1088 /******************************************************************************
1089 * read_console_input
1091 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1093 * Returns
1094 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1096 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1098 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1100 enum read_console_input_return ret;
1101 char input[8];
1102 WCHAR inputw[8];
1103 int i;
1104 size_t idx = 0, idxw;
1105 unsigned numEvent;
1106 INPUT_RECORD ir[8];
1107 DWORD written;
1108 struct pollfd pollfd;
1109 BOOL locked = FALSE, next_char;
1113 if (idx == sizeof(input))
1115 FIXME("buffer too small (%s)\n", wine_dbgstr_an(input, idx));
1116 ret = rci_error;
1117 break;
1119 pollfd.fd = fd;
1120 pollfd.events = POLLIN;
1121 pollfd.revents = 0;
1122 next_char = FALSE;
1124 switch (poll(&pollfd, 1, timeout))
1126 case 1:
1127 if (!locked)
1129 RtlEnterCriticalSection(&CONSOLE_CritSect);
1130 locked = TRUE;
1132 i = read(fd, &input[idx], 1);
1133 if (i < 0)
1135 ret = rci_error;
1136 break;
1138 if (i == 0)
1140 /* actually another thread likely beat us to reading the char
1141 * return rci_gotone, while not perfect, it should work in most of the cases (as the new event
1142 * should be now in the queue, fed from the other thread)
1144 ret = rci_gotone;
1145 break;
1148 idx++;
1149 numEvent = TERM_FillInputRecord(input, idx, ir);
1150 switch (numEvent)
1152 case 0:
1153 /* we need more char(s) to tell if it matches a key-db entry. wait 1/2s for next char */
1154 timeout = 500;
1155 next_char = TRUE;
1156 break;
1157 case -1:
1158 /* we haven't found the string into key-db, push full input string into server */
1159 idxw = MultiByteToWideChar(CP_UNIXCP, 0, input, idx, inputw, sizeof(inputw) / sizeof(inputw[0]));
1161 /* we cannot translate yet... likely we need more chars (wait max 1/2s for next char) */
1162 if (idxw == 0)
1164 timeout = 500;
1165 next_char = TRUE;
1166 break;
1168 for (i = 0; i < idxw; i++)
1170 numEvent = TERM_FillSimpleChar(inputw[i], ir);
1171 WriteConsoleInputW(handle, ir, numEvent, &written);
1173 ret = rci_gotone;
1174 break;
1175 default:
1176 /* we got a transformation from key-db... push this into server */
1177 ret = WriteConsoleInputW(handle, ir, numEvent, &written) ? rci_gotone : rci_error;
1178 break;
1180 break;
1181 case 0: ret = rci_timeout; break;
1182 default: ret = rci_error; break;
1184 } while (next_char);
1185 if (locked) RtlLeaveCriticalSection(&CONSOLE_CritSect);
1187 return ret;
1190 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1192 int fd;
1193 enum read_console_input_return ret;
1195 if ((fd = get_console_bare_fd(handle)) != -1)
1197 put_console_into_raw_mode(fd);
1198 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1200 ret = bare_console_fetch_input(handle, fd, timeout);
1202 else ret = rci_gotone;
1203 close(fd);
1204 if (ret != rci_gotone) return ret;
1206 else
1208 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1210 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1211 return rci_timeout;
1214 SERVER_START_REQ( read_console_input )
1216 req->handle = console_handle_unmap(handle);
1217 req->flush = TRUE;
1218 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1219 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1220 else ret = rci_gotone;
1222 SERVER_END_REQ;
1224 return ret;
1228 /***********************************************************************
1229 * FlushConsoleInputBuffer (KERNEL32.@)
1231 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1233 enum read_console_input_return last;
1234 INPUT_RECORD ir;
1236 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1238 return last == rci_timeout;
1242 /***********************************************************************
1243 * SetConsoleTitleA (KERNEL32.@)
1245 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1247 LPWSTR titleW;
1248 BOOL ret;
1250 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1251 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1252 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1253 ret = SetConsoleTitleW(titleW);
1254 HeapFree(GetProcessHeap(), 0, titleW);
1255 return ret;
1259 /***********************************************************************
1260 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1262 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1264 FIXME( "stub %p\n", layoutName);
1265 return TRUE;
1268 /***********************************************************************
1269 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1271 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1273 static int once;
1274 if (!once++)
1275 FIXME( "stub %p\n", layoutName);
1276 return TRUE;
1279 static WCHAR input_exe[MAX_PATH + 1];
1281 /***********************************************************************
1282 * GetConsoleInputExeNameW (KERNEL32.@)
1284 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1286 TRACE("%u %p\n", buflen, buffer);
1288 RtlEnterCriticalSection(&CONSOLE_CritSect);
1289 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1290 else SetLastError(ERROR_BUFFER_OVERFLOW);
1291 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1293 return TRUE;
1296 /***********************************************************************
1297 * GetConsoleInputExeNameA (KERNEL32.@)
1299 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1301 TRACE("%u %p\n", buflen, buffer);
1303 RtlEnterCriticalSection(&CONSOLE_CritSect);
1304 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1305 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1306 else SetLastError(ERROR_BUFFER_OVERFLOW);
1307 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1309 return TRUE;
1312 /***********************************************************************
1313 * GetConsoleTitleA (KERNEL32.@)
1315 * See GetConsoleTitleW.
1317 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1319 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1320 DWORD ret;
1322 if (!ptr) return 0;
1323 ret = GetConsoleTitleW( ptr, size );
1324 if (ret)
1326 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1327 ret = strlen(title);
1329 HeapFree(GetProcessHeap(), 0, ptr);
1330 return ret;
1334 /******************************************************************************
1335 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1337 * PARAMS
1338 * title [O] Address of buffer for title
1339 * size [I] Size of buffer
1341 * RETURNS
1342 * Success: Length of string copied
1343 * Failure: 0
1345 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1347 DWORD ret = 0;
1349 SERVER_START_REQ( get_console_input_info )
1351 req->handle = 0;
1352 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1353 if (!wine_server_call_err( req ))
1355 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1356 title[ret] = 0;
1359 SERVER_END_REQ;
1360 return ret;
1363 static COORD get_largest_console_window_size(HANDLE hConsole)
1365 COORD c = {0,0};
1367 SERVER_START_REQ(get_console_output_info)
1369 req->handle = console_handle_unmap(hConsole);
1370 if (!wine_server_call_err(req))
1372 c.X = reply->max_width;
1373 c.Y = reply->max_height;
1376 SERVER_END_REQ;
1377 return c;
1380 /***********************************************************************
1381 * GetLargestConsoleWindowSize (KERNEL32.@)
1383 * NOTE
1384 * This should return a COORD, but calling convention for returning
1385 * structures is different between Windows and gcc on i386.
1387 * VERSION: [i386]
1389 #ifdef __i386__
1390 #undef GetLargestConsoleWindowSize
1391 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1393 union {
1394 COORD c;
1395 DWORD w;
1396 } x;
1397 x.c = get_largest_console_window_size(hConsoleOutput);
1398 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1399 return x.w;
1402 #else
1404 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1406 COORD c;
1407 c = get_largest_console_window_size(hConsoleOutput);
1408 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1409 return c;
1411 #endif /* !defined(__i386__) */
1413 static WCHAR* S_EditString /* = NULL */;
1414 static unsigned S_EditStrPos /* = 0 */;
1416 /***********************************************************************
1417 * FreeConsole (KERNEL32.@)
1419 BOOL WINAPI FreeConsole(VOID)
1421 BOOL ret;
1423 /* invalidate local copy of input event handle */
1424 console_wait_event = 0;
1426 SERVER_START_REQ(free_console)
1428 ret = !wine_server_call_err( req );
1430 SERVER_END_REQ;
1431 return ret;
1434 /******************************************************************
1435 * start_console_renderer
1437 * helper for AllocConsole
1438 * starts the renderer process
1440 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1441 HANDLE hEvent)
1443 char buffer[1024];
1444 int ret;
1445 PROCESS_INFORMATION pi;
1447 /* FIXME: use dynamic allocation for most of the buffers below */
1448 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1449 if ((ret > -1) && (ret < sizeof(buffer)) &&
1450 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1451 NULL, NULL, si, &pi))
1453 HANDLE wh[2];
1454 DWORD res;
1456 wh[0] = hEvent;
1457 wh[1] = pi.hProcess;
1458 res = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1460 CloseHandle(pi.hThread);
1461 CloseHandle(pi.hProcess);
1463 if (res != WAIT_OBJECT_0) return FALSE;
1465 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1466 pi.dwProcessId, pi.dwThreadId);
1468 return TRUE;
1470 return FALSE;
1473 static BOOL start_console_renderer(STARTUPINFOA* si)
1475 HANDLE hEvent = 0;
1476 LPSTR p;
1477 OBJECT_ATTRIBUTES attr;
1478 BOOL ret = FALSE;
1480 attr.Length = sizeof(attr);
1481 attr.RootDirectory = 0;
1482 attr.Attributes = OBJ_INHERIT;
1483 attr.ObjectName = NULL;
1484 attr.SecurityDescriptor = NULL;
1485 attr.SecurityQualityOfService = NULL;
1487 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1488 if (!hEvent) return FALSE;
1490 /* first try environment variable */
1491 if ((p = getenv("WINECONSOLE")) != NULL)
1493 ret = start_console_renderer_helper(p, si, hEvent);
1494 if (!ret)
1495 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1496 "trying default access\n", p);
1499 /* then try the regular PATH */
1500 if (!ret)
1501 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1503 CloseHandle(hEvent);
1504 return ret;
1507 /***********************************************************************
1508 * AllocConsole (KERNEL32.@)
1510 * creates an xterm with a pty to our program
1512 BOOL WINAPI AllocConsole(void)
1514 HANDLE handle_in = INVALID_HANDLE_VALUE;
1515 HANDLE handle_out = INVALID_HANDLE_VALUE;
1516 HANDLE handle_err = INVALID_HANDLE_VALUE;
1517 STARTUPINFOA siCurrent;
1518 STARTUPINFOA siConsole;
1519 char buffer[1024];
1521 TRACE("()\n");
1523 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1524 FALSE, OPEN_EXISTING );
1526 if (VerifyConsoleIoHandle(handle_in))
1528 /* we already have a console opened on this process, don't create a new one */
1529 CloseHandle(handle_in);
1530 return FALSE;
1533 /* invalidate local copy of input event handle */
1534 console_wait_event = 0;
1536 GetStartupInfoA(&siCurrent);
1538 memset(&siConsole, 0, sizeof(siConsole));
1539 siConsole.cb = sizeof(siConsole);
1540 /* setup a view arguments for wineconsole (it'll use them as default values) */
1541 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1543 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1544 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1545 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1547 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1549 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1550 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1552 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1554 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1555 siConsole.wShowWindow = siCurrent.wShowWindow;
1557 /* FIXME (should pass the unicode form) */
1558 if (siCurrent.lpTitle)
1559 siConsole.lpTitle = siCurrent.lpTitle;
1560 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1562 buffer[sizeof(buffer) - 1] = '\0';
1563 siConsole.lpTitle = buffer;
1566 if (!start_console_renderer(&siConsole))
1567 goto the_end;
1569 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1570 /* all std I/O handles are inheritable by default */
1571 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1572 TRUE, OPEN_EXISTING );
1573 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1575 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1576 TRUE, OPEN_EXISTING );
1577 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1579 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1580 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1581 goto the_end;
1582 } else {
1583 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1584 handle_in = siCurrent.hStdInput;
1585 handle_out = siCurrent.hStdOutput;
1586 handle_err = siCurrent.hStdError;
1589 /* NT resets the STD_*_HANDLEs on console alloc */
1590 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1591 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1592 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1594 SetLastError(ERROR_SUCCESS);
1596 return TRUE;
1598 the_end:
1599 ERR("Can't allocate console\n");
1600 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1601 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1602 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1603 FreeConsole();
1604 return FALSE;
1608 /***********************************************************************
1609 * ReadConsoleA (KERNEL32.@)
1611 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1612 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1614 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1615 DWORD ncr = 0;
1616 BOOL ret;
1618 if (!ptr)
1620 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1621 return FALSE;
1624 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1626 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1627 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1629 HeapFree(GetProcessHeap(), 0, ptr);
1631 return ret;
1634 /***********************************************************************
1635 * ReadConsoleW (KERNEL32.@)
1637 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1638 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1640 DWORD charsread;
1641 LPWSTR xbuf = lpBuffer;
1642 DWORD mode;
1643 BOOL is_bare = FALSE;
1644 int fd;
1646 TRACE("(%p,%p,%d,%p,%p)\n",
1647 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1649 if (nNumberOfCharsToRead > INT_MAX)
1651 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1652 return FALSE;
1655 if (!GetConsoleMode(hConsoleInput, &mode))
1656 return FALSE;
1657 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1659 close(fd);
1660 is_bare = TRUE;
1662 if (mode & ENABLE_LINE_INPUT)
1664 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1666 HeapFree(GetProcessHeap(), 0, S_EditString);
1667 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1668 return FALSE;
1669 S_EditStrPos = 0;
1671 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1672 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1673 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1674 S_EditStrPos += charsread;
1676 else
1678 INPUT_RECORD ir;
1679 DWORD timeout = INFINITE;
1681 /* FIXME: should we read at least 1 char? The SDK does not say */
1682 /* wait for at least one available input record (it doesn't mean we'll have
1683 * chars stored in xbuf...)
1685 * Although SDK doc keeps silence about 1 char, SDK examples assume
1686 * that we should wait for at least one character (not key). --KS
1688 charsread = 0;
1691 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1692 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1693 ir.Event.KeyEvent.uChar.UnicodeChar)
1695 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1696 timeout = 0;
1698 } while (charsread < nNumberOfCharsToRead);
1699 /* nothing has been read */
1700 if (timeout == INFINITE) return FALSE;
1703 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1705 return TRUE;
1709 /***********************************************************************
1710 * ReadConsoleInputW (KERNEL32.@)
1712 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1713 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1715 DWORD idx = 0;
1716 DWORD timeout = INFINITE;
1718 if (!nLength)
1720 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1721 return TRUE;
1724 /* loop until we get at least one event */
1725 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1726 ++idx < nLength)
1727 timeout = 0;
1729 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1730 return idx != 0;
1734 /******************************************************************************
1735 * WriteConsoleOutputCharacterW [KERNEL32.@]
1737 * Copy character to consecutive cells in the console screen buffer.
1739 * PARAMS
1740 * hConsoleOutput [I] Handle to screen buffer
1741 * str [I] Pointer to buffer with chars to write
1742 * length [I] Number of cells to write to
1743 * coord [I] Coords of first cell
1744 * lpNumCharsWritten [O] Pointer to number of cells written
1746 * RETURNS
1747 * Success: TRUE
1748 * Failure: FALSE
1751 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1752 COORD coord, LPDWORD lpNumCharsWritten )
1754 BOOL ret;
1756 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1757 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1759 if ((length > 0 && !str) || !lpNumCharsWritten)
1761 SetLastError(ERROR_INVALID_ACCESS);
1762 return FALSE;
1765 *lpNumCharsWritten = 0;
1767 SERVER_START_REQ( write_console_output )
1769 req->handle = console_handle_unmap(hConsoleOutput);
1770 req->x = coord.X;
1771 req->y = coord.Y;
1772 req->mode = CHAR_INFO_MODE_TEXT;
1773 req->wrap = TRUE;
1774 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1775 if ((ret = !wine_server_call_err( req )))
1776 *lpNumCharsWritten = reply->written;
1778 SERVER_END_REQ;
1779 return ret;
1783 /******************************************************************************
1784 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1786 * PARAMS
1787 * title [I] Address of new title
1789 * RETURNS
1790 * Success: TRUE
1791 * Failure: FALSE
1793 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1795 BOOL ret;
1797 TRACE("(%s)\n", debugstr_w(title));
1798 SERVER_START_REQ( set_console_input_info )
1800 req->handle = 0;
1801 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1802 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1803 ret = !wine_server_call_err( req );
1805 SERVER_END_REQ;
1806 return ret;
1810 /***********************************************************************
1811 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1813 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1815 FIXME("(%p): stub\n", nrofbuttons);
1816 *nrofbuttons = 2;
1817 return TRUE;
1820 /******************************************************************************
1821 * SetConsoleInputExeNameW [KERNEL32.@]
1823 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1825 TRACE("(%s)\n", debugstr_w(name));
1827 if (!name || !name[0])
1829 SetLastError(ERROR_INVALID_PARAMETER);
1830 return FALSE;
1833 RtlEnterCriticalSection(&CONSOLE_CritSect);
1834 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1835 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1837 return TRUE;
1840 /******************************************************************************
1841 * SetConsoleInputExeNameA [KERNEL32.@]
1843 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1845 int len;
1846 LPWSTR nameW;
1847 BOOL ret;
1849 if (!name || !name[0])
1851 SetLastError(ERROR_INVALID_PARAMETER);
1852 return FALSE;
1855 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1856 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1858 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1859 ret = SetConsoleInputExeNameW(nameW);
1860 HeapFree(GetProcessHeap(), 0, nameW);
1862 return ret;
1865 /******************************************************************
1866 * CONSOLE_DefaultHandler
1868 * Final control event handler
1870 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1872 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1873 ExitProcess(0);
1874 /* should never go here */
1875 return TRUE;
1878 /******************************************************************************
1879 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1881 * PARAMS
1882 * func [I] Address of handler function
1883 * add [I] Handler to add or remove
1885 * RETURNS
1886 * Success: TRUE
1887 * Failure: FALSE
1890 struct ConsoleHandler
1892 PHANDLER_ROUTINE handler;
1893 struct ConsoleHandler* next;
1896 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1897 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1899 /*****************************************************************************/
1901 /******************************************************************
1902 * SetConsoleCtrlHandler (KERNEL32.@)
1904 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1906 BOOL ret = TRUE;
1908 TRACE("(%p,%i)\n", func, add);
1910 if (!func)
1912 RtlEnterCriticalSection(&CONSOLE_CritSect);
1913 if (add)
1914 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1915 else
1916 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1917 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1919 else if (add)
1921 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1923 if (!ch) return FALSE;
1924 ch->handler = func;
1925 RtlEnterCriticalSection(&CONSOLE_CritSect);
1926 ch->next = CONSOLE_Handlers;
1927 CONSOLE_Handlers = ch;
1928 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1930 else
1932 struct ConsoleHandler** ch;
1933 RtlEnterCriticalSection(&CONSOLE_CritSect);
1934 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1936 if ((*ch)->handler == func) break;
1938 if (*ch)
1940 struct ConsoleHandler* rch = *ch;
1942 /* sanity check */
1943 if (rch == &CONSOLE_DefaultConsoleHandler)
1945 ERR("Who's trying to remove default handler???\n");
1946 SetLastError(ERROR_INVALID_PARAMETER);
1947 ret = FALSE;
1949 else
1951 *ch = rch->next;
1952 HeapFree(GetProcessHeap(), 0, rch);
1955 else
1957 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1958 SetLastError(ERROR_INVALID_PARAMETER);
1959 ret = FALSE;
1961 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1963 return ret;
1966 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1968 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1969 return EXCEPTION_EXECUTE_HANDLER;
1972 /******************************************************************
1973 * CONSOLE_SendEventThread
1975 * Internal helper to pass an event to the list on installed handlers
1977 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1979 DWORD_PTR event = (DWORD_PTR)pmt;
1980 struct ConsoleHandler* ch;
1982 if (event == CTRL_C_EVENT)
1984 BOOL caught_by_dbg = TRUE;
1985 /* First, try to pass the ctrl-C event to the debugger (if any)
1986 * If it continues, there's nothing more to do
1987 * Otherwise, we need to send the ctrl-C event to the handlers
1989 __TRY
1991 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1993 __EXCEPT(CONSOLE_CtrlEventHandler)
1995 caught_by_dbg = FALSE;
1997 __ENDTRY;
1998 if (caught_by_dbg) return 0;
1999 /* the debugger didn't continue... so, pass to ctrl handlers */
2001 RtlEnterCriticalSection(&CONSOLE_CritSect);
2002 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
2004 if (ch->handler(event)) break;
2006 RtlLeaveCriticalSection(&CONSOLE_CritSect);
2007 return 1;
2010 /******************************************************************
2011 * CONSOLE_HandleCtrlC
2013 * Check whether the shall manipulate CtrlC events
2015 int CONSOLE_HandleCtrlC(unsigned sig)
2017 HANDLE thread;
2019 /* FIXME: better test whether a console is attached to this process ??? */
2020 extern unsigned CONSOLE_GetNumHistoryEntries(void);
2021 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
2023 /* check if we have to ignore ctrl-C events */
2024 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
2026 /* Create a separate thread to signal all the events.
2027 * This is needed because:
2028 * - this function can be called in an Unix signal handler (hence on an
2029 * different stack than the thread that's running). This breaks the
2030 * Win32 exception mechanisms (where the thread's stack is checked).
2031 * - since the current thread, while processing the signal, can hold the
2032 * console critical section, we need another execution environment where
2033 * we can wait on this critical section
2035 thread = CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2036 if (thread == NULL)
2037 return 0;
2039 CloseHandle(thread);
2041 return 1;
2044 /******************************************************************************
2045 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2047 * PARAMS
2048 * dwCtrlEvent [I] Type of event
2049 * dwProcessGroupID [I] Process group ID to send event to
2051 * RETURNS
2052 * Success: True
2053 * Failure: False (and *should* [but doesn't] set LastError)
2055 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2056 DWORD dwProcessGroupID)
2058 BOOL ret;
2060 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2062 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2064 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2065 return FALSE;
2068 SERVER_START_REQ( send_console_signal )
2070 req->signal = dwCtrlEvent;
2071 req->group_id = dwProcessGroupID;
2072 ret = !wine_server_call_err( req );
2074 SERVER_END_REQ;
2076 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2077 * have been handled by all processes in the given group?
2078 * As of today, we don't wait...
2080 return ret;
2084 /******************************************************************************
2085 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2087 * PARAMS
2088 * dwDesiredAccess [I] Access flag
2089 * dwShareMode [I] Buffer share mode
2090 * sa [I] Security attributes
2091 * dwFlags [I] Type of buffer to create
2092 * lpScreenBufferData [I] Reserved
2094 * NOTES
2095 * Should call SetLastError
2097 * RETURNS
2098 * Success: Handle to new console screen buffer
2099 * Failure: INVALID_HANDLE_VALUE
2101 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2102 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2103 LPVOID lpScreenBufferData)
2105 HANDLE ret = INVALID_HANDLE_VALUE;
2107 TRACE("(%d,%d,%p,%d,%p)\n",
2108 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2110 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2112 SetLastError(ERROR_INVALID_PARAMETER);
2113 return INVALID_HANDLE_VALUE;
2116 SERVER_START_REQ(create_console_output)
2118 req->handle_in = 0;
2119 req->access = dwDesiredAccess;
2120 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2121 req->share = dwShareMode;
2122 req->fd = -1;
2123 if (!wine_server_call_err( req ))
2124 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2126 SERVER_END_REQ;
2128 return ret;
2132 /***********************************************************************
2133 * GetConsoleScreenBufferInfo (KERNEL32.@)
2135 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2137 BOOL ret;
2139 SERVER_START_REQ(get_console_output_info)
2141 req->handle = console_handle_unmap(hConsoleOutput);
2142 if ((ret = !wine_server_call_err( req )))
2144 csbi->dwSize.X = reply->width;
2145 csbi->dwSize.Y = reply->height;
2146 csbi->dwCursorPosition.X = reply->cursor_x;
2147 csbi->dwCursorPosition.Y = reply->cursor_y;
2148 csbi->wAttributes = reply->attr;
2149 csbi->srWindow.Left = reply->win_left;
2150 csbi->srWindow.Right = reply->win_right;
2151 csbi->srWindow.Top = reply->win_top;
2152 csbi->srWindow.Bottom = reply->win_bottom;
2153 csbi->dwMaximumWindowSize.X = min(reply->width, reply->max_width);
2154 csbi->dwMaximumWindowSize.Y = min(reply->height, reply->max_height);
2157 SERVER_END_REQ;
2159 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2160 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2161 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2162 csbi->wAttributes,
2163 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2164 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2166 return ret;
2170 /******************************************************************************
2171 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2173 * RETURNS
2174 * Success: TRUE
2175 * Failure: FALSE
2177 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2179 BOOL ret;
2181 TRACE("(%p)\n", hConsoleOutput);
2183 SERVER_START_REQ( set_console_input_info )
2185 req->handle = 0;
2186 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2187 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2188 ret = !wine_server_call_err( req );
2190 SERVER_END_REQ;
2191 return ret;
2195 /***********************************************************************
2196 * GetConsoleMode (KERNEL32.@)
2198 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2200 BOOL ret;
2202 SERVER_START_REQ( get_console_mode )
2204 req->handle = console_handle_unmap(hcon);
2205 if ((ret = !wine_server_call_err( req )))
2207 if (mode) *mode = reply->mode;
2210 SERVER_END_REQ;
2211 return ret;
2215 /******************************************************************************
2216 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2218 * PARAMS
2219 * hcon [I] Handle to console input or screen buffer
2220 * mode [I] Input or output mode to set
2222 * RETURNS
2223 * Success: TRUE
2224 * Failure: FALSE
2226 * mode:
2227 * ENABLE_PROCESSED_INPUT 0x01
2228 * ENABLE_LINE_INPUT 0x02
2229 * ENABLE_ECHO_INPUT 0x04
2230 * ENABLE_WINDOW_INPUT 0x08
2231 * ENABLE_MOUSE_INPUT 0x10
2233 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2235 BOOL ret;
2237 SERVER_START_REQ(set_console_mode)
2239 req->handle = console_handle_unmap(hcon);
2240 req->mode = mode;
2241 ret = !wine_server_call_err( req );
2243 SERVER_END_REQ;
2244 /* FIXME: when resetting a console input to editline mode, I think we should
2245 * empty the S_EditString buffer
2248 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2250 return ret;
2254 /******************************************************************
2255 * CONSOLE_WriteChars
2257 * WriteConsoleOutput helper: hides server call semantics
2258 * writes a string at a given pos with standard attribute
2260 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2262 int written = -1;
2264 if (!nc) return 0;
2266 SERVER_START_REQ( write_console_output )
2268 req->handle = console_handle_unmap(hCon);
2269 req->x = pos->X;
2270 req->y = pos->Y;
2271 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2272 req->wrap = FALSE;
2273 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2274 if (!wine_server_call_err( req )) written = reply->written;
2276 SERVER_END_REQ;
2278 if (written > 0) pos->X += written;
2279 return written;
2282 /******************************************************************
2283 * next_line
2285 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2288 static BOOL next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2290 SMALL_RECT src;
2291 CHAR_INFO ci;
2292 COORD dst;
2294 csbi->dwCursorPosition.X = 0;
2295 csbi->dwCursorPosition.Y++;
2297 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return TRUE;
2299 src.Top = 1;
2300 src.Bottom = csbi->dwSize.Y - 1;
2301 src.Left = 0;
2302 src.Right = csbi->dwSize.X - 1;
2304 dst.X = 0;
2305 dst.Y = 0;
2307 ci.Attributes = csbi->wAttributes;
2308 ci.Char.UnicodeChar = ' ';
2310 csbi->dwCursorPosition.Y--;
2311 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2312 return FALSE;
2313 return TRUE;
2316 /******************************************************************
2317 * write_block
2319 * WriteConsoleOutput helper: writes a block of non special characters
2320 * Block can spread on several lines, and wrapping, if needed, is
2321 * handled
2324 static BOOL write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2325 DWORD mode, LPCWSTR ptr, int len)
2327 int blk; /* number of chars to write on current line */
2328 int done; /* number of chars already written */
2330 if (len <= 0) return TRUE;
2332 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2334 for (done = 0; done < len; done += blk)
2336 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2338 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2339 return FALSE;
2340 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2341 return FALSE;
2344 else
2346 int pos = csbi->dwCursorPosition.X;
2347 /* FIXME: we could reduce the number of loops
2348 * but, in most cases we wouldn't gain lots of time (it would only
2349 * happen if we're asked to overwrite more than twice the part of the line,
2350 * which is unlikely
2352 for (done = 0; done < len; done += blk)
2354 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2356 csbi->dwCursorPosition.X = pos;
2357 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2358 return FALSE;
2362 return TRUE;
2365 /***********************************************************************
2366 * WriteConsoleW (KERNEL32.@)
2368 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2369 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2371 DWORD mode;
2372 DWORD nw = 0;
2373 const WCHAR* psz = lpBuffer;
2374 CONSOLE_SCREEN_BUFFER_INFO csbi;
2375 int k, first = 0, fd;
2377 TRACE("%p %s %d %p %p\n",
2378 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2379 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2381 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2383 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2385 char* ptr;
2386 unsigned len;
2387 HANDLE hFile;
2388 NTSTATUS status;
2389 IO_STATUS_BLOCK iosb;
2391 close(fd);
2392 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2393 * to do the job
2395 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2396 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2397 return FALSE;
2399 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2400 hFile = wine_server_ptr_handle(console_handle_unmap(hConsoleOutput));
2401 status = NtWriteFile(hFile, NULL, NULL, NULL, &iosb, ptr, len, 0, NULL);
2402 if (status == STATUS_PENDING)
2404 WaitForSingleObject(hFile, INFINITE);
2405 status = iosb.u.Status;
2408 if (status != STATUS_PENDING && lpNumberOfCharsWritten)
2410 if (iosb.Information == len)
2411 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2412 else
2413 FIXME("Conversion not supported yet\n");
2415 HeapFree(GetProcessHeap(), 0, ptr);
2416 if (status != STATUS_SUCCESS)
2418 SetLastError(RtlNtStatusToDosError(status));
2419 return FALSE;
2421 return TRUE;
2424 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2425 return FALSE;
2427 if (!nNumberOfCharsToWrite) return TRUE;
2429 if (mode & ENABLE_PROCESSED_OUTPUT)
2431 unsigned int i;
2433 for (i = 0; i < nNumberOfCharsToWrite; i++)
2435 switch (psz[i])
2437 case '\b': case '\t': case '\n': case '\a': case '\r':
2438 /* don't handle here the i-th char... done below */
2439 if ((k = i - first) > 0)
2441 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2442 goto the_end;
2443 nw += k;
2445 first = i + 1;
2446 nw++;
2448 switch (psz[i])
2450 case '\b':
2451 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2452 break;
2453 case '\t':
2455 static const WCHAR tmp[] = {' ',' ',' ',' ',' ',' ',' ',' '};
2456 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2457 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2458 goto the_end;
2460 break;
2461 case '\n':
2462 next_line(hConsoleOutput, &csbi);
2463 break;
2464 case '\a':
2465 Beep(400, 300);
2466 break;
2467 case '\r':
2468 csbi.dwCursorPosition.X = 0;
2469 break;
2470 default:
2471 break;
2476 /* write the remaining block (if any) if processed output is enabled, or the
2477 * entire buffer otherwise
2479 if ((k = nNumberOfCharsToWrite - first) > 0)
2481 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2482 goto the_end;
2483 nw += k;
2486 the_end:
2487 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2488 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2489 return nw != 0;
2493 /***********************************************************************
2494 * WriteConsoleA (KERNEL32.@)
2496 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2497 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2499 BOOL ret;
2500 LPWSTR xstring;
2501 DWORD n;
2503 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2505 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2506 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2507 if (!xstring) return FALSE;
2509 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2511 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2513 HeapFree(GetProcessHeap(), 0, xstring);
2515 return ret;
2518 /******************************************************************************
2519 * SetConsoleCursorPosition [KERNEL32.@]
2520 * Sets the cursor position in console
2522 * PARAMS
2523 * hConsoleOutput [I] Handle of console screen buffer
2524 * dwCursorPosition [I] New cursor position coordinates
2526 * RETURNS
2527 * Success: TRUE
2528 * Failure: FALSE
2530 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2532 BOOL ret;
2533 CONSOLE_SCREEN_BUFFER_INFO csbi;
2534 int do_move = 0;
2535 int w, h;
2537 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2539 SERVER_START_REQ(set_console_output_info)
2541 req->handle = console_handle_unmap(hcon);
2542 req->cursor_x = pos.X;
2543 req->cursor_y = pos.Y;
2544 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2545 ret = !wine_server_call_err( req );
2547 SERVER_END_REQ;
2549 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2550 return FALSE;
2552 /* if cursor is no longer visible, scroll the visible window... */
2553 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2554 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2555 if (pos.X < csbi.srWindow.Left)
2557 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2558 do_move++;
2560 else if (pos.X > csbi.srWindow.Right)
2562 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2563 do_move++;
2565 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2567 if (pos.Y < csbi.srWindow.Top)
2569 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2570 do_move++;
2572 else if (pos.Y > csbi.srWindow.Bottom)
2574 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2575 do_move++;
2577 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2579 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2581 return ret;
2584 /******************************************************************************
2585 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2587 * PARAMS
2588 * hcon [I] Handle to console screen buffer
2589 * cinfo [O] Address of cursor information
2591 * RETURNS
2592 * Success: TRUE
2593 * Failure: FALSE
2595 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2597 BOOL ret;
2599 SERVER_START_REQ(get_console_output_info)
2601 req->handle = console_handle_unmap(hCon);
2602 ret = !wine_server_call_err( req );
2603 if (ret && cinfo)
2605 cinfo->dwSize = reply->cursor_size;
2606 cinfo->bVisible = reply->cursor_visible;
2609 SERVER_END_REQ;
2611 if (!ret) return FALSE;
2613 if (!cinfo)
2615 SetLastError(ERROR_INVALID_ACCESS);
2616 ret = FALSE;
2618 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2620 return ret;
2624 /******************************************************************************
2625 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2627 * PARAMS
2628 * hcon [I] Handle to console screen buffer
2629 * cinfo [I] Address of cursor information
2630 * RETURNS
2631 * Success: TRUE
2632 * Failure: FALSE
2634 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2636 BOOL ret;
2638 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2639 SERVER_START_REQ(set_console_output_info)
2641 req->handle = console_handle_unmap(hCon);
2642 req->cursor_size = cinfo->dwSize;
2643 req->cursor_visible = cinfo->bVisible;
2644 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2645 ret = !wine_server_call_err( req );
2647 SERVER_END_REQ;
2648 return ret;
2652 /******************************************************************************
2653 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2655 * PARAMS
2656 * hcon [I] Handle to console screen buffer
2657 * bAbsolute [I] Coordinate type flag
2658 * window [I] Address of new window rectangle
2659 * RETURNS
2660 * Success: TRUE
2661 * Failure: FALSE
2663 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2665 SMALL_RECT p = *window;
2666 BOOL ret;
2668 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2670 if (!bAbsolute)
2672 CONSOLE_SCREEN_BUFFER_INFO csbi;
2674 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2675 return FALSE;
2676 p.Left += csbi.srWindow.Left;
2677 p.Top += csbi.srWindow.Top;
2678 p.Right += csbi.srWindow.Right;
2679 p.Bottom += csbi.srWindow.Bottom;
2681 SERVER_START_REQ(set_console_output_info)
2683 req->handle = console_handle_unmap(hCon);
2684 req->win_left = p.Left;
2685 req->win_top = p.Top;
2686 req->win_right = p.Right;
2687 req->win_bottom = p.Bottom;
2688 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2689 ret = !wine_server_call_err( req );
2691 SERVER_END_REQ;
2693 return ret;
2697 /******************************************************************************
2698 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2700 * Sets the foreground and background color attributes of characters
2701 * written to the screen buffer.
2703 * RETURNS
2704 * Success: TRUE
2705 * Failure: FALSE
2707 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2709 BOOL ret;
2711 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2712 SERVER_START_REQ(set_console_output_info)
2714 req->handle = console_handle_unmap(hConsoleOutput);
2715 req->attr = wAttr;
2716 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2717 ret = !wine_server_call_err( req );
2719 SERVER_END_REQ;
2720 return ret;
2724 /******************************************************************************
2725 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2727 * PARAMS
2728 * hConsoleOutput [I] Handle to console screen buffer
2729 * dwSize [I] New size in character rows and cols
2731 * RETURNS
2732 * Success: TRUE
2733 * Failure: FALSE
2735 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2737 BOOL ret;
2739 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2740 SERVER_START_REQ(set_console_output_info)
2742 req->handle = console_handle_unmap(hConsoleOutput);
2743 req->width = dwSize.X;
2744 req->height = dwSize.Y;
2745 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2746 ret = !wine_server_call_err( req );
2748 SERVER_END_REQ;
2749 return ret;
2753 /******************************************************************************
2754 * ScrollConsoleScreenBufferA [KERNEL32.@]
2757 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2758 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2759 LPCHAR_INFO lpFill)
2761 CHAR_INFO ciw;
2763 ciw.Attributes = lpFill->Attributes;
2764 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2766 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2767 dwDestOrigin, &ciw);
2770 /******************************************************************
2771 * CONSOLE_FillLineUniform
2773 * Helper function for ScrollConsoleScreenBufferW
2774 * Fills a part of a line with a constant character info
2776 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2778 SERVER_START_REQ( fill_console_output )
2780 req->handle = console_handle_unmap(hConsoleOutput);
2781 req->mode = CHAR_INFO_MODE_TEXTATTR;
2782 req->x = i;
2783 req->y = j;
2784 req->count = len;
2785 req->wrap = FALSE;
2786 req->data.ch = lpFill->Char.UnicodeChar;
2787 req->data.attr = lpFill->Attributes;
2788 wine_server_call_err( req );
2790 SERVER_END_REQ;
2793 /******************************************************************************
2794 * ScrollConsoleScreenBufferW [KERNEL32.@]
2798 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2799 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2800 LPCHAR_INFO lpFill)
2802 SMALL_RECT dst;
2803 DWORD ret;
2804 int i, j;
2805 int start = -1;
2806 SMALL_RECT clip;
2807 CONSOLE_SCREEN_BUFFER_INFO csbi;
2808 BOOL inside;
2809 COORD src;
2811 if (lpClipRect)
2812 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2813 lpScrollRect->Left, lpScrollRect->Top,
2814 lpScrollRect->Right, lpScrollRect->Bottom,
2815 lpClipRect->Left, lpClipRect->Top,
2816 lpClipRect->Right, lpClipRect->Bottom,
2817 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2818 else
2819 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2820 lpScrollRect->Left, lpScrollRect->Top,
2821 lpScrollRect->Right, lpScrollRect->Bottom,
2822 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2824 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2825 return FALSE;
2827 src.X = lpScrollRect->Left;
2828 src.Y = lpScrollRect->Top;
2830 /* step 1: get dst rect */
2831 dst.Left = dwDestOrigin.X;
2832 dst.Top = dwDestOrigin.Y;
2833 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2834 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2836 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2837 if (lpClipRect)
2839 clip.Left = max(0, lpClipRect->Left);
2840 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2841 clip.Top = max(0, lpClipRect->Top);
2842 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2844 else
2846 clip.Left = 0;
2847 clip.Right = csbi.dwSize.X - 1;
2848 clip.Top = 0;
2849 clip.Bottom = csbi.dwSize.Y - 1;
2851 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2853 /* step 2b: clip dst rect */
2854 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2855 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2856 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2857 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2859 /* step 3: transfer the bits */
2860 SERVER_START_REQ(move_console_output)
2862 req->handle = console_handle_unmap(hConsoleOutput);
2863 req->x_src = src.X;
2864 req->y_src = src.Y;
2865 req->x_dst = dst.Left;
2866 req->y_dst = dst.Top;
2867 req->w = dst.Right - dst.Left + 1;
2868 req->h = dst.Bottom - dst.Top + 1;
2869 ret = !wine_server_call_err( req );
2871 SERVER_END_REQ;
2873 if (!ret) return FALSE;
2875 /* step 4: clean out the exposed part */
2877 /* have to write cell [i,j] if it is not in dst rect (because it has already
2878 * been written to by the scroll) and is in clip (we shall not write
2879 * outside of clip)
2881 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2883 inside = dst.Top <= j && j <= dst.Bottom;
2884 start = -1;
2885 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2887 if (inside && dst.Left <= i && i <= dst.Right)
2889 if (start != -1)
2891 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2892 start = -1;
2895 else
2897 if (start == -1) start = i;
2900 if (start != -1)
2901 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2904 return TRUE;
2907 /******************************************************************
2908 * AttachConsole (KERNEL32.@)
2910 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2912 FIXME("stub %x\n",dwProcessId);
2913 return TRUE;
2916 /******************************************************************
2917 * GetConsoleDisplayMode (KERNEL32.@)
2919 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2921 TRACE("semi-stub: %p\n", lpModeFlags);
2922 /* It is safe to successfully report windowed mode */
2923 *lpModeFlags = 0;
2924 return TRUE;
2927 /******************************************************************
2928 * SetConsoleDisplayMode (KERNEL32.@)
2930 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2931 COORD *lpNewScreenBufferDimensions)
2933 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2934 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2935 if (dwFlags == 1)
2937 /* We cannot switch to fullscreen */
2938 return FALSE;
2940 return TRUE;
2944 /* ====================================================================
2946 * Console manipulation functions
2948 * ====================================================================*/
2950 /* some missing functions...
2951 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2952 * should get the right API and implement them
2953 * SetConsoleCommandHistoryMode
2954 * SetConsoleNumberOfCommands[AW]
2956 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2958 int len = 0;
2960 SERVER_START_REQ( get_console_input_history )
2962 req->handle = 0;
2963 req->index = idx;
2964 if (buf && buf_len > 1)
2966 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2968 if (!wine_server_call_err( req ))
2970 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2971 len = reply->total / sizeof(WCHAR) + 1;
2974 SERVER_END_REQ;
2975 return len;
2978 /******************************************************************
2979 * CONSOLE_AppendHistory
2983 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2985 size_t len = strlenW(ptr);
2986 BOOL ret;
2988 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2989 if (!len) return FALSE;
2991 SERVER_START_REQ( append_console_input_history )
2993 req->handle = 0;
2994 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2995 ret = !wine_server_call_err( req );
2997 SERVER_END_REQ;
2998 return ret;
3001 /******************************************************************
3002 * CONSOLE_GetNumHistoryEntries
3006 unsigned CONSOLE_GetNumHistoryEntries(void)
3008 unsigned ret = -1;
3009 SERVER_START_REQ(get_console_input_info)
3011 req->handle = 0;
3012 if (!wine_server_call_err( req )) ret = reply->history_index;
3014 SERVER_END_REQ;
3015 return ret;
3018 /******************************************************************
3019 * CONSOLE_GetEditionMode
3023 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
3025 unsigned ret = 0;
3026 SERVER_START_REQ(get_console_input_info)
3028 req->handle = console_handle_unmap(hConIn);
3029 if ((ret = !wine_server_call_err( req )))
3030 *mode = reply->edition_mode;
3032 SERVER_END_REQ;
3033 return ret;
3036 /******************************************************************
3037 * GetConsoleAliasW
3040 * RETURNS
3041 * 0 if an error occurred, non-zero for success
3044 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3045 DWORD TargetBufferLength, LPWSTR lpExename)
3047 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3048 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3049 return 0;
3052 /******************************************************************
3053 * GetConsoleProcessList (KERNEL32.@)
3055 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3057 FIXME("(%p,%d): stub\n", processlist, processcount);
3059 if (!processlist || processcount < 1)
3061 SetLastError(ERROR_INVALID_PARAMETER);
3062 return 0;
3065 return 0;
3068 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3070 memset(&S_termios, 0, sizeof(S_termios));
3071 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3073 HANDLE conin;
3075 /* FIXME: to be done even if program is a GUI ? */
3076 /* This is wine specific: we have no parent (we're started from unix)
3077 * so, create a simple console with bare handles
3079 TERM_Init();
3080 wine_server_send_fd(0);
3081 SERVER_START_REQ( alloc_console )
3083 req->access = GENERIC_READ | GENERIC_WRITE;
3084 req->attributes = OBJ_INHERIT;
3085 req->pid = 0xffffffff;
3086 req->input_fd = 0;
3087 wine_server_call( req );
3088 conin = wine_server_ptr_handle( reply->handle_in );
3089 /* reply->event shouldn't be created by server */
3091 SERVER_END_REQ;
3093 if (!params->hStdInput)
3094 params->hStdInput = conin;
3096 if (!params->hStdOutput)
3098 wine_server_send_fd(1);
3099 SERVER_START_REQ( create_console_output )
3101 req->handle_in = wine_server_obj_handle(conin);
3102 req->access = GENERIC_WRITE|GENERIC_READ;
3103 req->attributes = OBJ_INHERIT;
3104 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3105 req->fd = 1;
3106 wine_server_call(req);
3107 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3109 SERVER_END_REQ;
3111 if (!params->hStdError)
3113 wine_server_send_fd(2);
3114 SERVER_START_REQ( create_console_output )
3116 req->handle_in = wine_server_obj_handle(conin);
3117 req->access = GENERIC_WRITE|GENERIC_READ;
3118 req->attributes = OBJ_INHERIT;
3119 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3120 req->fd = 2;
3121 wine_server_call(req);
3122 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3124 SERVER_END_REQ;
3128 /* convert value from server:
3129 * + INVALID_HANDLE_VALUE => TEB: 0, STARTUPINFO: INVALID_HANDLE_VALUE
3130 * + 0 => TEB: 0, STARTUPINFO: INVALID_HANDLE_VALUE
3131 * + console handle needs to be mapped
3133 if (!params->hStdInput || params->hStdInput == INVALID_HANDLE_VALUE)
3134 params->hStdInput = 0;
3135 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3137 params->hStdInput = console_handle_map(params->hStdInput);
3138 save_console_mode(params->hStdInput);
3141 if (!params->hStdOutput || params->hStdOutput == INVALID_HANDLE_VALUE)
3142 params->hStdOutput = 0;
3143 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3144 params->hStdOutput = console_handle_map(params->hStdOutput);
3146 if (!params->hStdError || params->hStdError == INVALID_HANDLE_VALUE)
3147 params->hStdError = 0;
3148 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3149 params->hStdError = console_handle_map(params->hStdError);
3151 return TRUE;
3154 BOOL CONSOLE_Exit(void)
3156 /* the console is in raw mode, put it back in cooked mode */
3157 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));
3160 /* Undocumented, called by native doskey.exe */
3161 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3162 DWORD WINAPI GetConsoleCommandHistoryA(DWORD unknown1, DWORD unknown2, DWORD unknown3)
3164 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
3165 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3166 return 0;
3169 /* Undocumented, called by native doskey.exe */
3170 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3171 DWORD WINAPI GetConsoleCommandHistoryW(DWORD unknown1, DWORD unknown2, DWORD unknown3)
3173 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
3174 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3175 return 0;
3178 /* Undocumented, called by native doskey.exe */
3179 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3180 DWORD WINAPI GetConsoleCommandHistoryLengthA(LPCSTR unknown)
3182 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3183 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3184 return 0;
3187 /* Undocumented, called by native doskey.exe */
3188 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3189 DWORD WINAPI GetConsoleCommandHistoryLengthW(LPCWSTR unknown)
3191 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3192 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3193 return 0;
3196 DWORD WINAPI GetConsoleAliasesLengthA(LPSTR unknown)
3198 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3199 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3200 return 0;
3203 DWORD WINAPI GetConsoleAliasesLengthW(LPWSTR unknown)
3205 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3206 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3207 return 0;
3210 DWORD WINAPI GetConsoleAliasExesLengthA(void)
3212 FIXME(": stub!\n");
3213 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3214 return 0;
3217 DWORD WINAPI GetConsoleAliasExesLengthW(void)
3219 FIXME(": stub!\n");
3220 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3221 return 0;
3224 VOID WINAPI ExpungeConsoleCommandHistoryA(LPCSTR unknown)
3226 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3227 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3230 VOID WINAPI ExpungeConsoleCommandHistoryW(LPCWSTR unknown)
3232 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3233 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3236 BOOL WINAPI AddConsoleAliasA(LPSTR source, LPSTR target, LPSTR exename)
3238 FIXME(": (%s, %s, %s) stub!\n", debugstr_a(source), debugstr_a(target), debugstr_a(exename));
3239 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3240 return FALSE;
3243 BOOL WINAPI AddConsoleAliasW(LPWSTR source, LPWSTR target, LPWSTR exename)
3245 FIXME(": (%s, %s, %s) stub!\n", debugstr_w(source), debugstr_w(target), debugstr_w(exename));
3246 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3247 return FALSE;
3251 BOOL WINAPI SetConsoleIcon(HICON icon)
3253 FIXME(": (%p) stub!\n", icon);
3254 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3255 return FALSE;
3258 DWORD WINAPI GetNumberOfConsoleFonts(void)
3260 return 1;
3263 BOOL WINAPI SetConsoleFont(HANDLE hConsole, DWORD index)
3265 FIXME("(%p, %u): stub!\n", hConsole, index);
3266 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3267 return FALSE;
3270 BOOL WINAPI SetConsoleKeyShortcuts(BOOL set, BYTE keys, VOID *a, DWORD b)
3272 FIXME(": (%u %u %p %u) stub!\n", set, keys, a, b);
3273 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3274 return FALSE;
3278 BOOL WINAPI GetCurrentConsoleFont(HANDLE hConsole, BOOL maxwindow, LPCONSOLE_FONT_INFO fontinfo)
3280 BOOL ret;
3282 memset(fontinfo, 0, sizeof(CONSOLE_FONT_INFO));
3284 SERVER_START_REQ(get_console_output_info)
3286 req->handle = console_handle_unmap(hConsole);
3287 if ((ret = !wine_server_call_err(req)))
3289 if (maxwindow)
3291 fontinfo->dwFontSize.X = min(reply->width, reply->max_width);
3292 fontinfo->dwFontSize.Y = min(reply->height, reply->max_height);
3294 else
3296 fontinfo->dwFontSize.X = reply->win_right - reply->win_left + 1;
3297 fontinfo->dwFontSize.Y = reply->win_bottom - reply->win_top + 1;
3301 SERVER_END_REQ;
3302 return ret;
3305 static COORD get_console_font_size(HANDLE hConsole, DWORD index)
3307 COORD c = {0,0};
3309 if (index >= GetNumberOfConsoleFonts())
3311 SetLastError(ERROR_INVALID_PARAMETER);
3312 return c;
3315 SERVER_START_REQ(get_console_output_info)
3317 req->handle = console_handle_unmap(hConsole);
3318 if (!wine_server_call_err(req))
3320 c.X = reply->font_width;
3321 c.Y = reply->font_height;
3324 SERVER_END_REQ;
3325 return c;
3328 #ifdef __i386__
3329 #undef GetConsoleFontSize
3330 DWORD WINAPI GetConsoleFontSize(HANDLE hConsole, DWORD index)
3332 union {
3333 COORD c;
3334 DWORD w;
3335 } x;
3337 x.c = get_console_font_size(hConsole, index);
3338 return x.w;
3340 #endif /* defined(__i386__) */
3343 #ifndef __i386__
3344 COORD WINAPI GetConsoleFontSize(HANDLE hConsole, DWORD index)
3346 return get_console_font_size(hConsole, index);
3348 #endif /* !defined(__i386__) */
3350 BOOL WINAPI GetConsoleFontInfo(HANDLE hConsole, BOOL maximize, DWORD numfonts, CONSOLE_FONT_INFO *info)
3352 FIXME("(%p %d %u %p): stub!\n", hConsole, maximize, numfonts, info);
3353 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3354 return FALSE;
3357 BOOL WINAPI GetConsoleScreenBufferInfoEx(HANDLE hConsole, CONSOLE_SCREEN_BUFFER_INFOEX *csbix)
3359 BOOL ret;
3361 if (csbix->cbSize != sizeof(CONSOLE_SCREEN_BUFFER_INFOEX))
3363 SetLastError(ERROR_INVALID_PARAMETER);
3364 return FALSE;
3367 SERVER_START_REQ(get_console_output_info)
3369 req->handle = console_handle_unmap(hConsole);
3370 wine_server_set_reply(req, csbix->ColorTable, sizeof(csbix->ColorTable));
3371 if ((ret = !wine_server_call_err(req)))
3373 csbix->dwSize.X = reply->width;
3374 csbix->dwSize.Y = reply->height;
3375 csbix->dwCursorPosition.X = reply->cursor_x;
3376 csbix->dwCursorPosition.Y = reply->cursor_y;
3377 csbix->wAttributes = reply->attr;
3378 csbix->srWindow.Left = reply->win_left;
3379 csbix->srWindow.Top = reply->win_top;
3380 csbix->srWindow.Right = reply->win_right;
3381 csbix->srWindow.Bottom = reply->win_bottom;
3382 csbix->dwMaximumWindowSize.X = min(reply->width, reply->max_width);
3383 csbix->dwMaximumWindowSize.Y = min(reply->height, reply->max_height);
3384 csbix->wPopupAttributes = reply->popup_attr;
3385 csbix->bFullscreenSupported = FALSE;
3388 SERVER_END_REQ;
3390 return ret;
3393 BOOL WINAPI SetConsoleScreenBufferInfoEx(HANDLE hConsole, CONSOLE_SCREEN_BUFFER_INFOEX *csbix)
3395 FIXME("(%p %p): stub!\n", hConsole, csbix);
3396 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3397 return FALSE;
3400 BOOL WINAPI SetCurrentConsoleFontEx(HANDLE hConsole, BOOL maxwindow, CONSOLE_FONT_INFOEX *cfix)
3402 FIXME("(%p %d %p): stub!\n", hConsole, maxwindow, cfix);
3403 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3404 return FALSE;