TESTING -- override pthreads to fix gstreamer v5
[wine/multimedia.git] / dlls / kernel32 / console.c
blob51d6e60798a98a424f62bb176b73b709d03529ca
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;
1364 /***********************************************************************
1365 * GetLargestConsoleWindowSize (KERNEL32.@)
1367 * NOTE
1368 * This should return a COORD, but calling convention for returning
1369 * structures is different between Windows and gcc on i386.
1371 * VERSION: [i386]
1373 #ifdef __i386__
1374 #undef GetLargestConsoleWindowSize
1375 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1377 union {
1378 COORD c;
1379 DWORD w;
1380 } x;
1381 x.c.X = 80;
1382 x.c.Y = 24;
1383 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1384 return x.w;
1386 #endif /* defined(__i386__) */
1389 /***********************************************************************
1390 * GetLargestConsoleWindowSize (KERNEL32.@)
1392 * NOTE
1393 * This should return a COORD, but calling convention for returning
1394 * structures is different between Windows and gcc on i386.
1396 * VERSION: [!i386]
1398 #ifndef __i386__
1399 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1401 COORD c;
1402 c.X = 80;
1403 c.Y = 24;
1404 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1405 return c;
1407 #endif /* defined(__i386__) */
1409 static WCHAR* S_EditString /* = NULL */;
1410 static unsigned S_EditStrPos /* = 0 */;
1412 /***********************************************************************
1413 * FreeConsole (KERNEL32.@)
1415 BOOL WINAPI FreeConsole(VOID)
1417 BOOL ret;
1419 /* invalidate local copy of input event handle */
1420 console_wait_event = 0;
1422 SERVER_START_REQ(free_console)
1424 ret = !wine_server_call_err( req );
1426 SERVER_END_REQ;
1427 return ret;
1430 /******************************************************************
1431 * start_console_renderer
1433 * helper for AllocConsole
1434 * starts the renderer process
1436 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1437 HANDLE hEvent)
1439 char buffer[1024];
1440 int ret;
1441 PROCESS_INFORMATION pi;
1443 /* FIXME: use dynamic allocation for most of the buffers below */
1444 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1445 if ((ret > -1) && (ret < sizeof(buffer)) &&
1446 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1447 NULL, NULL, si, &pi))
1449 HANDLE wh[2];
1450 DWORD res;
1452 wh[0] = hEvent;
1453 wh[1] = pi.hProcess;
1454 res = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1456 CloseHandle(pi.hThread);
1457 CloseHandle(pi.hProcess);
1459 if (res != WAIT_OBJECT_0) return FALSE;
1461 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1462 pi.dwProcessId, pi.dwThreadId);
1464 return TRUE;
1466 return FALSE;
1469 static BOOL start_console_renderer(STARTUPINFOA* si)
1471 HANDLE hEvent = 0;
1472 LPSTR p;
1473 OBJECT_ATTRIBUTES attr;
1474 BOOL ret = FALSE;
1476 attr.Length = sizeof(attr);
1477 attr.RootDirectory = 0;
1478 attr.Attributes = OBJ_INHERIT;
1479 attr.ObjectName = NULL;
1480 attr.SecurityDescriptor = NULL;
1481 attr.SecurityQualityOfService = NULL;
1483 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1484 if (!hEvent) return FALSE;
1486 /* first try environment variable */
1487 if ((p = getenv("WINECONSOLE")) != NULL)
1489 ret = start_console_renderer_helper(p, si, hEvent);
1490 if (!ret)
1491 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1492 "trying default access\n", p);
1495 /* then try the regular PATH */
1496 if (!ret)
1497 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1499 CloseHandle(hEvent);
1500 return ret;
1503 /***********************************************************************
1504 * AllocConsole (KERNEL32.@)
1506 * creates an xterm with a pty to our program
1508 BOOL WINAPI AllocConsole(void)
1510 HANDLE handle_in = INVALID_HANDLE_VALUE;
1511 HANDLE handle_out = INVALID_HANDLE_VALUE;
1512 HANDLE handle_err = INVALID_HANDLE_VALUE;
1513 STARTUPINFOA siCurrent;
1514 STARTUPINFOA siConsole;
1515 char buffer[1024];
1517 TRACE("()\n");
1519 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1520 FALSE, OPEN_EXISTING );
1522 if (VerifyConsoleIoHandle(handle_in))
1524 /* we already have a console opened on this process, don't create a new one */
1525 CloseHandle(handle_in);
1526 return FALSE;
1529 /* invalidate local copy of input event handle */
1530 console_wait_event = 0;
1532 GetStartupInfoA(&siCurrent);
1534 memset(&siConsole, 0, sizeof(siConsole));
1535 siConsole.cb = sizeof(siConsole);
1536 /* setup a view arguments for wineconsole (it'll use them as default values) */
1537 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1539 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1540 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1541 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1543 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1545 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1546 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1548 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1550 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1551 siConsole.wShowWindow = siCurrent.wShowWindow;
1553 /* FIXME (should pass the unicode form) */
1554 if (siCurrent.lpTitle)
1555 siConsole.lpTitle = siCurrent.lpTitle;
1556 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1558 buffer[sizeof(buffer) - 1] = '\0';
1559 siConsole.lpTitle = buffer;
1562 if (!start_console_renderer(&siConsole))
1563 goto the_end;
1565 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1566 /* all std I/O handles are inheritable by default */
1567 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1568 TRUE, OPEN_EXISTING );
1569 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1571 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1572 TRUE, OPEN_EXISTING );
1573 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1575 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1576 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1577 goto the_end;
1578 } else {
1579 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1580 handle_in = siCurrent.hStdInput;
1581 handle_out = siCurrent.hStdOutput;
1582 handle_err = siCurrent.hStdError;
1585 /* NT resets the STD_*_HANDLEs on console alloc */
1586 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1587 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1588 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1590 SetLastError(ERROR_SUCCESS);
1592 return TRUE;
1594 the_end:
1595 ERR("Can't allocate console\n");
1596 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1597 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1598 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1599 FreeConsole();
1600 return FALSE;
1604 /***********************************************************************
1605 * ReadConsoleA (KERNEL32.@)
1607 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1608 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1610 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1611 DWORD ncr = 0;
1612 BOOL ret;
1614 if (!ptr)
1616 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1617 return FALSE;
1620 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1622 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1623 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1625 HeapFree(GetProcessHeap(), 0, ptr);
1627 return ret;
1630 /***********************************************************************
1631 * ReadConsoleW (KERNEL32.@)
1633 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1634 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1636 DWORD charsread;
1637 LPWSTR xbuf = lpBuffer;
1638 DWORD mode;
1639 BOOL is_bare = FALSE;
1640 int fd;
1642 TRACE("(%p,%p,%d,%p,%p)\n",
1643 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1645 if (nNumberOfCharsToRead > INT_MAX)
1647 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1648 return FALSE;
1651 if (!GetConsoleMode(hConsoleInput, &mode))
1652 return FALSE;
1653 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1655 close(fd);
1656 is_bare = TRUE;
1658 if (mode & ENABLE_LINE_INPUT)
1660 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1662 HeapFree(GetProcessHeap(), 0, S_EditString);
1663 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1664 return FALSE;
1665 S_EditStrPos = 0;
1667 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1668 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1669 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1670 S_EditStrPos += charsread;
1672 else
1674 INPUT_RECORD ir;
1675 DWORD timeout = INFINITE;
1677 /* FIXME: should we read at least 1 char? The SDK does not say */
1678 /* wait for at least one available input record (it doesn't mean we'll have
1679 * chars stored in xbuf...)
1681 * Although SDK doc keeps silence about 1 char, SDK examples assume
1682 * that we should wait for at least one character (not key). --KS
1684 charsread = 0;
1687 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1688 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1689 ir.Event.KeyEvent.uChar.UnicodeChar)
1691 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1692 timeout = 0;
1694 } while (charsread < nNumberOfCharsToRead);
1695 /* nothing has been read */
1696 if (timeout == INFINITE) return FALSE;
1699 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1701 return TRUE;
1705 /***********************************************************************
1706 * ReadConsoleInputW (KERNEL32.@)
1708 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1709 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1711 DWORD idx = 0;
1712 DWORD timeout = INFINITE;
1714 if (!nLength)
1716 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1717 return TRUE;
1720 /* loop until we get at least one event */
1721 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1722 ++idx < nLength)
1723 timeout = 0;
1725 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1726 return idx != 0;
1730 /******************************************************************************
1731 * WriteConsoleOutputCharacterW [KERNEL32.@]
1733 * Copy character to consecutive cells in the console screen buffer.
1735 * PARAMS
1736 * hConsoleOutput [I] Handle to screen buffer
1737 * str [I] Pointer to buffer with chars to write
1738 * length [I] Number of cells to write to
1739 * coord [I] Coords of first cell
1740 * lpNumCharsWritten [O] Pointer to number of cells written
1742 * RETURNS
1743 * Success: TRUE
1744 * Failure: FALSE
1747 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1748 COORD coord, LPDWORD lpNumCharsWritten )
1750 BOOL ret;
1752 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1753 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1755 if ((length > 0 && !str) || !lpNumCharsWritten)
1757 SetLastError(ERROR_INVALID_ACCESS);
1758 return FALSE;
1761 *lpNumCharsWritten = 0;
1763 SERVER_START_REQ( write_console_output )
1765 req->handle = console_handle_unmap(hConsoleOutput);
1766 req->x = coord.X;
1767 req->y = coord.Y;
1768 req->mode = CHAR_INFO_MODE_TEXT;
1769 req->wrap = TRUE;
1770 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1771 if ((ret = !wine_server_call_err( req )))
1772 *lpNumCharsWritten = reply->written;
1774 SERVER_END_REQ;
1775 return ret;
1779 /******************************************************************************
1780 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1782 * PARAMS
1783 * title [I] Address of new title
1785 * RETURNS
1786 * Success: TRUE
1787 * Failure: FALSE
1789 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1791 BOOL ret;
1793 TRACE("(%s)\n", debugstr_w(title));
1794 SERVER_START_REQ( set_console_input_info )
1796 req->handle = 0;
1797 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1798 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1799 ret = !wine_server_call_err( req );
1801 SERVER_END_REQ;
1802 return ret;
1806 /***********************************************************************
1807 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1809 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1811 FIXME("(%p): stub\n", nrofbuttons);
1812 *nrofbuttons = 2;
1813 return TRUE;
1816 /******************************************************************************
1817 * SetConsoleInputExeNameW [KERNEL32.@]
1819 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1821 TRACE("(%s)\n", debugstr_w(name));
1823 if (!name || !name[0])
1825 SetLastError(ERROR_INVALID_PARAMETER);
1826 return FALSE;
1829 RtlEnterCriticalSection(&CONSOLE_CritSect);
1830 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1831 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1833 return TRUE;
1836 /******************************************************************************
1837 * SetConsoleInputExeNameA [KERNEL32.@]
1839 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1841 int len;
1842 LPWSTR nameW;
1843 BOOL ret;
1845 if (!name || !name[0])
1847 SetLastError(ERROR_INVALID_PARAMETER);
1848 return FALSE;
1851 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1852 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1854 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1855 ret = SetConsoleInputExeNameW(nameW);
1856 HeapFree(GetProcessHeap(), 0, nameW);
1858 return ret;
1861 /******************************************************************
1862 * CONSOLE_DefaultHandler
1864 * Final control event handler
1866 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1868 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1869 ExitProcess(0);
1870 /* should never go here */
1871 return TRUE;
1874 /******************************************************************************
1875 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1877 * PARAMS
1878 * func [I] Address of handler function
1879 * add [I] Handler to add or remove
1881 * RETURNS
1882 * Success: TRUE
1883 * Failure: FALSE
1886 struct ConsoleHandler
1888 PHANDLER_ROUTINE handler;
1889 struct ConsoleHandler* next;
1892 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1893 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1895 /*****************************************************************************/
1897 /******************************************************************
1898 * SetConsoleCtrlHandler (KERNEL32.@)
1900 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1902 BOOL ret = TRUE;
1904 TRACE("(%p,%i)\n", func, add);
1906 if (!func)
1908 RtlEnterCriticalSection(&CONSOLE_CritSect);
1909 if (add)
1910 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1911 else
1912 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1913 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1915 else if (add)
1917 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1919 if (!ch) return FALSE;
1920 ch->handler = func;
1921 RtlEnterCriticalSection(&CONSOLE_CritSect);
1922 ch->next = CONSOLE_Handlers;
1923 CONSOLE_Handlers = ch;
1924 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1926 else
1928 struct ConsoleHandler** ch;
1929 RtlEnterCriticalSection(&CONSOLE_CritSect);
1930 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1932 if ((*ch)->handler == func) break;
1934 if (*ch)
1936 struct ConsoleHandler* rch = *ch;
1938 /* sanity check */
1939 if (rch == &CONSOLE_DefaultConsoleHandler)
1941 ERR("Who's trying to remove default handler???\n");
1942 SetLastError(ERROR_INVALID_PARAMETER);
1943 ret = FALSE;
1945 else
1947 *ch = rch->next;
1948 HeapFree(GetProcessHeap(), 0, rch);
1951 else
1953 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1954 SetLastError(ERROR_INVALID_PARAMETER);
1955 ret = FALSE;
1957 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1959 return ret;
1962 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1964 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1965 return EXCEPTION_EXECUTE_HANDLER;
1968 /******************************************************************
1969 * CONSOLE_SendEventThread
1971 * Internal helper to pass an event to the list on installed handlers
1973 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1975 DWORD_PTR event = (DWORD_PTR)pmt;
1976 struct ConsoleHandler* ch;
1978 if (event == CTRL_C_EVENT)
1980 BOOL caught_by_dbg = TRUE;
1981 /* First, try to pass the ctrl-C event to the debugger (if any)
1982 * If it continues, there's nothing more to do
1983 * Otherwise, we need to send the ctrl-C event to the handlers
1985 __TRY
1987 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1989 __EXCEPT(CONSOLE_CtrlEventHandler)
1991 caught_by_dbg = FALSE;
1993 __ENDTRY;
1994 if (caught_by_dbg) return 0;
1995 /* the debugger didn't continue... so, pass to ctrl handlers */
1997 RtlEnterCriticalSection(&CONSOLE_CritSect);
1998 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
2000 if (ch->handler(event)) break;
2002 RtlLeaveCriticalSection(&CONSOLE_CritSect);
2003 return 1;
2006 /******************************************************************
2007 * CONSOLE_HandleCtrlC
2009 * Check whether the shall manipulate CtrlC events
2011 int CONSOLE_HandleCtrlC(unsigned sig)
2013 HANDLE thread;
2015 /* FIXME: better test whether a console is attached to this process ??? */
2016 extern unsigned CONSOLE_GetNumHistoryEntries(void);
2017 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
2019 /* check if we have to ignore ctrl-C events */
2020 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
2022 /* Create a separate thread to signal all the events.
2023 * This is needed because:
2024 * - this function can be called in an Unix signal handler (hence on an
2025 * different stack than the thread that's running). This breaks the
2026 * Win32 exception mechanisms (where the thread's stack is checked).
2027 * - since the current thread, while processing the signal, can hold the
2028 * console critical section, we need another execution environment where
2029 * we can wait on this critical section
2031 thread = CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2032 if (thread == NULL)
2033 return 0;
2035 CloseHandle(thread);
2037 return 1;
2040 /******************************************************************************
2041 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2043 * PARAMS
2044 * dwCtrlEvent [I] Type of event
2045 * dwProcessGroupID [I] Process group ID to send event to
2047 * RETURNS
2048 * Success: True
2049 * Failure: False (and *should* [but doesn't] set LastError)
2051 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2052 DWORD dwProcessGroupID)
2054 BOOL ret;
2056 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2058 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2060 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2061 return FALSE;
2064 SERVER_START_REQ( send_console_signal )
2066 req->signal = dwCtrlEvent;
2067 req->group_id = dwProcessGroupID;
2068 ret = !wine_server_call_err( req );
2070 SERVER_END_REQ;
2072 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2073 * have been handled by all processes in the given group?
2074 * As of today, we don't wait...
2076 return ret;
2080 /******************************************************************************
2081 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2083 * PARAMS
2084 * dwDesiredAccess [I] Access flag
2085 * dwShareMode [I] Buffer share mode
2086 * sa [I] Security attributes
2087 * dwFlags [I] Type of buffer to create
2088 * lpScreenBufferData [I] Reserved
2090 * NOTES
2091 * Should call SetLastError
2093 * RETURNS
2094 * Success: Handle to new console screen buffer
2095 * Failure: INVALID_HANDLE_VALUE
2097 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2098 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2099 LPVOID lpScreenBufferData)
2101 HANDLE ret = INVALID_HANDLE_VALUE;
2103 TRACE("(%d,%d,%p,%d,%p)\n",
2104 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2106 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2108 SetLastError(ERROR_INVALID_PARAMETER);
2109 return INVALID_HANDLE_VALUE;
2112 SERVER_START_REQ(create_console_output)
2114 req->handle_in = 0;
2115 req->access = dwDesiredAccess;
2116 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2117 req->share = dwShareMode;
2118 req->fd = -1;
2119 if (!wine_server_call_err( req ))
2120 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2122 SERVER_END_REQ;
2124 return ret;
2128 /***********************************************************************
2129 * GetConsoleScreenBufferInfo (KERNEL32.@)
2131 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2133 BOOL ret;
2135 SERVER_START_REQ(get_console_output_info)
2137 req->handle = console_handle_unmap(hConsoleOutput);
2138 if ((ret = !wine_server_call_err( req )))
2140 csbi->dwSize.X = reply->width;
2141 csbi->dwSize.Y = reply->height;
2142 csbi->dwCursorPosition.X = reply->cursor_x;
2143 csbi->dwCursorPosition.Y = reply->cursor_y;
2144 csbi->wAttributes = reply->attr;
2145 csbi->srWindow.Left = reply->win_left;
2146 csbi->srWindow.Right = reply->win_right;
2147 csbi->srWindow.Top = reply->win_top;
2148 csbi->srWindow.Bottom = reply->win_bottom;
2149 csbi->dwMaximumWindowSize.X = reply->max_width;
2150 csbi->dwMaximumWindowSize.Y = reply->max_height;
2153 SERVER_END_REQ;
2155 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2156 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2157 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2158 csbi->wAttributes,
2159 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2160 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2162 return ret;
2166 /******************************************************************************
2167 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2169 * RETURNS
2170 * Success: TRUE
2171 * Failure: FALSE
2173 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2175 BOOL ret;
2177 TRACE("(%p)\n", hConsoleOutput);
2179 SERVER_START_REQ( set_console_input_info )
2181 req->handle = 0;
2182 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2183 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2184 ret = !wine_server_call_err( req );
2186 SERVER_END_REQ;
2187 return ret;
2191 /***********************************************************************
2192 * GetConsoleMode (KERNEL32.@)
2194 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2196 BOOL ret;
2198 SERVER_START_REQ( get_console_mode )
2200 req->handle = console_handle_unmap(hcon);
2201 if ((ret = !wine_server_call_err( req )))
2203 if (mode) *mode = reply->mode;
2206 SERVER_END_REQ;
2207 return ret;
2211 /******************************************************************************
2212 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2214 * PARAMS
2215 * hcon [I] Handle to console input or screen buffer
2216 * mode [I] Input or output mode to set
2218 * RETURNS
2219 * Success: TRUE
2220 * Failure: FALSE
2222 * mode:
2223 * ENABLE_PROCESSED_INPUT 0x01
2224 * ENABLE_LINE_INPUT 0x02
2225 * ENABLE_ECHO_INPUT 0x04
2226 * ENABLE_WINDOW_INPUT 0x08
2227 * ENABLE_MOUSE_INPUT 0x10
2229 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2231 BOOL ret;
2233 SERVER_START_REQ(set_console_mode)
2235 req->handle = console_handle_unmap(hcon);
2236 req->mode = mode;
2237 ret = !wine_server_call_err( req );
2239 SERVER_END_REQ;
2240 /* FIXME: when resetting a console input to editline mode, I think we should
2241 * empty the S_EditString buffer
2244 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2246 return ret;
2250 /******************************************************************
2251 * CONSOLE_WriteChars
2253 * WriteConsoleOutput helper: hides server call semantics
2254 * writes a string at a given pos with standard attribute
2256 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2258 int written = -1;
2260 if (!nc) return 0;
2262 SERVER_START_REQ( write_console_output )
2264 req->handle = console_handle_unmap(hCon);
2265 req->x = pos->X;
2266 req->y = pos->Y;
2267 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2268 req->wrap = FALSE;
2269 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2270 if (!wine_server_call_err( req )) written = reply->written;
2272 SERVER_END_REQ;
2274 if (written > 0) pos->X += written;
2275 return written;
2278 /******************************************************************
2279 * next_line
2281 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2284 static BOOL next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2286 SMALL_RECT src;
2287 CHAR_INFO ci;
2288 COORD dst;
2290 csbi->dwCursorPosition.X = 0;
2291 csbi->dwCursorPosition.Y++;
2293 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return TRUE;
2295 src.Top = 1;
2296 src.Bottom = csbi->dwSize.Y - 1;
2297 src.Left = 0;
2298 src.Right = csbi->dwSize.X - 1;
2300 dst.X = 0;
2301 dst.Y = 0;
2303 ci.Attributes = csbi->wAttributes;
2304 ci.Char.UnicodeChar = ' ';
2306 csbi->dwCursorPosition.Y--;
2307 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2308 return FALSE;
2309 return TRUE;
2312 /******************************************************************
2313 * write_block
2315 * WriteConsoleOutput helper: writes a block of non special characters
2316 * Block can spread on several lines, and wrapping, if needed, is
2317 * handled
2320 static BOOL write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2321 DWORD mode, LPCWSTR ptr, int len)
2323 int blk; /* number of chars to write on current line */
2324 int done; /* number of chars already written */
2326 if (len <= 0) return TRUE;
2328 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2330 for (done = 0; done < len; done += blk)
2332 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2334 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2335 return FALSE;
2336 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2337 return FALSE;
2340 else
2342 int pos = csbi->dwCursorPosition.X;
2343 /* FIXME: we could reduce the number of loops
2344 * but, in most cases we wouldn't gain lots of time (it would only
2345 * happen if we're asked to overwrite more than twice the part of the line,
2346 * which is unlikely
2348 for (done = 0; done < len; done += blk)
2350 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2352 csbi->dwCursorPosition.X = pos;
2353 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2354 return FALSE;
2358 return TRUE;
2361 /***********************************************************************
2362 * WriteConsoleW (KERNEL32.@)
2364 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2365 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2367 DWORD mode;
2368 DWORD nw = 0;
2369 const WCHAR* psz = lpBuffer;
2370 CONSOLE_SCREEN_BUFFER_INFO csbi;
2371 int k, first = 0, fd;
2373 TRACE("%p %s %d %p %p\n",
2374 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2375 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2377 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2379 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2381 char* ptr;
2382 unsigned len;
2383 HANDLE hFile;
2384 NTSTATUS status;
2385 IO_STATUS_BLOCK iosb;
2387 close(fd);
2388 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2389 * to do the job
2391 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2392 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2393 return FALSE;
2395 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2396 hFile = wine_server_ptr_handle(console_handle_unmap(hConsoleOutput));
2397 status = NtWriteFile(hFile, NULL, NULL, NULL, &iosb, ptr, len, 0, NULL);
2398 if (status == STATUS_PENDING)
2400 WaitForSingleObject(hFile, INFINITE);
2401 status = iosb.u.Status;
2404 if (status != STATUS_PENDING && lpNumberOfCharsWritten)
2406 if (iosb.Information == len)
2407 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2408 else
2409 FIXME("Conversion not supported yet\n");
2411 HeapFree(GetProcessHeap(), 0, ptr);
2412 if (status != STATUS_SUCCESS)
2414 SetLastError(RtlNtStatusToDosError(status));
2415 return FALSE;
2417 return TRUE;
2420 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2421 return FALSE;
2423 if (!nNumberOfCharsToWrite) return TRUE;
2425 if (mode & ENABLE_PROCESSED_OUTPUT)
2427 unsigned int i;
2429 for (i = 0; i < nNumberOfCharsToWrite; i++)
2431 switch (psz[i])
2433 case '\b': case '\t': case '\n': case '\a': case '\r':
2434 /* don't handle here the i-th char... done below */
2435 if ((k = i - first) > 0)
2437 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2438 goto the_end;
2439 nw += k;
2441 first = i + 1;
2442 nw++;
2444 switch (psz[i])
2446 case '\b':
2447 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2448 break;
2449 case '\t':
2451 static const WCHAR tmp[] = {' ',' ',' ',' ',' ',' ',' ',' '};
2452 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2453 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2454 goto the_end;
2456 break;
2457 case '\n':
2458 next_line(hConsoleOutput, &csbi);
2459 break;
2460 case '\a':
2461 Beep(400, 300);
2462 break;
2463 case '\r':
2464 csbi.dwCursorPosition.X = 0;
2465 break;
2466 default:
2467 break;
2472 /* write the remaining block (if any) if processed output is enabled, or the
2473 * entire buffer otherwise
2475 if ((k = nNumberOfCharsToWrite - first) > 0)
2477 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2478 goto the_end;
2479 nw += k;
2482 the_end:
2483 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2484 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2485 return nw != 0;
2489 /***********************************************************************
2490 * WriteConsoleA (KERNEL32.@)
2492 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2493 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2495 BOOL ret;
2496 LPWSTR xstring;
2497 DWORD n;
2499 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2501 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2502 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2503 if (!xstring) return FALSE;
2505 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2507 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2509 HeapFree(GetProcessHeap(), 0, xstring);
2511 return ret;
2514 /******************************************************************************
2515 * SetConsoleCursorPosition [KERNEL32.@]
2516 * Sets the cursor position in console
2518 * PARAMS
2519 * hConsoleOutput [I] Handle of console screen buffer
2520 * dwCursorPosition [I] New cursor position coordinates
2522 * RETURNS
2523 * Success: TRUE
2524 * Failure: FALSE
2526 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2528 BOOL ret;
2529 CONSOLE_SCREEN_BUFFER_INFO csbi;
2530 int do_move = 0;
2531 int w, h;
2533 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2535 SERVER_START_REQ(set_console_output_info)
2537 req->handle = console_handle_unmap(hcon);
2538 req->cursor_x = pos.X;
2539 req->cursor_y = pos.Y;
2540 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2541 ret = !wine_server_call_err( req );
2543 SERVER_END_REQ;
2545 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2546 return FALSE;
2548 /* if cursor is no longer visible, scroll the visible window... */
2549 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2550 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2551 if (pos.X < csbi.srWindow.Left)
2553 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2554 do_move++;
2556 else if (pos.X > csbi.srWindow.Right)
2558 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2559 do_move++;
2561 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2563 if (pos.Y < csbi.srWindow.Top)
2565 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2566 do_move++;
2568 else if (pos.Y > csbi.srWindow.Bottom)
2570 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2571 do_move++;
2573 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2575 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2577 return ret;
2580 /******************************************************************************
2581 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2583 * PARAMS
2584 * hcon [I] Handle to console screen buffer
2585 * cinfo [O] Address of cursor information
2587 * RETURNS
2588 * Success: TRUE
2589 * Failure: FALSE
2591 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2593 BOOL ret;
2595 SERVER_START_REQ(get_console_output_info)
2597 req->handle = console_handle_unmap(hCon);
2598 ret = !wine_server_call_err( req );
2599 if (ret && cinfo)
2601 cinfo->dwSize = reply->cursor_size;
2602 cinfo->bVisible = reply->cursor_visible;
2605 SERVER_END_REQ;
2607 if (!ret) return FALSE;
2609 if (!cinfo)
2611 SetLastError(ERROR_INVALID_ACCESS);
2612 ret = FALSE;
2614 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2616 return ret;
2620 /******************************************************************************
2621 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2623 * PARAMS
2624 * hcon [I] Handle to console screen buffer
2625 * cinfo [I] Address of cursor information
2626 * RETURNS
2627 * Success: TRUE
2628 * Failure: FALSE
2630 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2632 BOOL ret;
2634 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2635 SERVER_START_REQ(set_console_output_info)
2637 req->handle = console_handle_unmap(hCon);
2638 req->cursor_size = cinfo->dwSize;
2639 req->cursor_visible = cinfo->bVisible;
2640 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2641 ret = !wine_server_call_err( req );
2643 SERVER_END_REQ;
2644 return ret;
2648 /******************************************************************************
2649 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2651 * PARAMS
2652 * hcon [I] Handle to console screen buffer
2653 * bAbsolute [I] Coordinate type flag
2654 * window [I] Address of new window rectangle
2655 * RETURNS
2656 * Success: TRUE
2657 * Failure: FALSE
2659 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2661 SMALL_RECT p = *window;
2662 BOOL ret;
2664 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2666 if (!bAbsolute)
2668 CONSOLE_SCREEN_BUFFER_INFO csbi;
2670 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2671 return FALSE;
2672 p.Left += csbi.srWindow.Left;
2673 p.Top += csbi.srWindow.Top;
2674 p.Right += csbi.srWindow.Right;
2675 p.Bottom += csbi.srWindow.Bottom;
2677 SERVER_START_REQ(set_console_output_info)
2679 req->handle = console_handle_unmap(hCon);
2680 req->win_left = p.Left;
2681 req->win_top = p.Top;
2682 req->win_right = p.Right;
2683 req->win_bottom = p.Bottom;
2684 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2685 ret = !wine_server_call_err( req );
2687 SERVER_END_REQ;
2689 return ret;
2693 /******************************************************************************
2694 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2696 * Sets the foreground and background color attributes of characters
2697 * written to the screen buffer.
2699 * RETURNS
2700 * Success: TRUE
2701 * Failure: FALSE
2703 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2705 BOOL ret;
2707 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2708 SERVER_START_REQ(set_console_output_info)
2710 req->handle = console_handle_unmap(hConsoleOutput);
2711 req->attr = wAttr;
2712 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2713 ret = !wine_server_call_err( req );
2715 SERVER_END_REQ;
2716 return ret;
2720 /******************************************************************************
2721 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2723 * PARAMS
2724 * hConsoleOutput [I] Handle to console screen buffer
2725 * dwSize [I] New size in character rows and cols
2727 * RETURNS
2728 * Success: TRUE
2729 * Failure: FALSE
2731 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2733 BOOL ret;
2735 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2736 SERVER_START_REQ(set_console_output_info)
2738 req->handle = console_handle_unmap(hConsoleOutput);
2739 req->width = dwSize.X;
2740 req->height = dwSize.Y;
2741 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2742 ret = !wine_server_call_err( req );
2744 SERVER_END_REQ;
2745 return ret;
2749 /******************************************************************************
2750 * ScrollConsoleScreenBufferA [KERNEL32.@]
2753 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2754 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2755 LPCHAR_INFO lpFill)
2757 CHAR_INFO ciw;
2759 ciw.Attributes = lpFill->Attributes;
2760 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2762 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2763 dwDestOrigin, &ciw);
2766 /******************************************************************
2767 * CONSOLE_FillLineUniform
2769 * Helper function for ScrollConsoleScreenBufferW
2770 * Fills a part of a line with a constant character info
2772 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2774 SERVER_START_REQ( fill_console_output )
2776 req->handle = console_handle_unmap(hConsoleOutput);
2777 req->mode = CHAR_INFO_MODE_TEXTATTR;
2778 req->x = i;
2779 req->y = j;
2780 req->count = len;
2781 req->wrap = FALSE;
2782 req->data.ch = lpFill->Char.UnicodeChar;
2783 req->data.attr = lpFill->Attributes;
2784 wine_server_call_err( req );
2786 SERVER_END_REQ;
2789 /******************************************************************************
2790 * ScrollConsoleScreenBufferW [KERNEL32.@]
2794 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2795 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2796 LPCHAR_INFO lpFill)
2798 SMALL_RECT dst;
2799 DWORD ret;
2800 int i, j;
2801 int start = -1;
2802 SMALL_RECT clip;
2803 CONSOLE_SCREEN_BUFFER_INFO csbi;
2804 BOOL inside;
2805 COORD src;
2807 if (lpClipRect)
2808 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2809 lpScrollRect->Left, lpScrollRect->Top,
2810 lpScrollRect->Right, lpScrollRect->Bottom,
2811 lpClipRect->Left, lpClipRect->Top,
2812 lpClipRect->Right, lpClipRect->Bottom,
2813 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2814 else
2815 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2816 lpScrollRect->Left, lpScrollRect->Top,
2817 lpScrollRect->Right, lpScrollRect->Bottom,
2818 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2820 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2821 return FALSE;
2823 src.X = lpScrollRect->Left;
2824 src.Y = lpScrollRect->Top;
2826 /* step 1: get dst rect */
2827 dst.Left = dwDestOrigin.X;
2828 dst.Top = dwDestOrigin.Y;
2829 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2830 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2832 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2833 if (lpClipRect)
2835 clip.Left = max(0, lpClipRect->Left);
2836 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2837 clip.Top = max(0, lpClipRect->Top);
2838 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2840 else
2842 clip.Left = 0;
2843 clip.Right = csbi.dwSize.X - 1;
2844 clip.Top = 0;
2845 clip.Bottom = csbi.dwSize.Y - 1;
2847 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2849 /* step 2b: clip dst rect */
2850 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2851 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2852 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2853 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2855 /* step 3: transfer the bits */
2856 SERVER_START_REQ(move_console_output)
2858 req->handle = console_handle_unmap(hConsoleOutput);
2859 req->x_src = src.X;
2860 req->y_src = src.Y;
2861 req->x_dst = dst.Left;
2862 req->y_dst = dst.Top;
2863 req->w = dst.Right - dst.Left + 1;
2864 req->h = dst.Bottom - dst.Top + 1;
2865 ret = !wine_server_call_err( req );
2867 SERVER_END_REQ;
2869 if (!ret) return FALSE;
2871 /* step 4: clean out the exposed part */
2873 /* have to write cell [i,j] if it is not in dst rect (because it has already
2874 * been written to by the scroll) and is in clip (we shall not write
2875 * outside of clip)
2877 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2879 inside = dst.Top <= j && j <= dst.Bottom;
2880 start = -1;
2881 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2883 if (inside && dst.Left <= i && i <= dst.Right)
2885 if (start != -1)
2887 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2888 start = -1;
2891 else
2893 if (start == -1) start = i;
2896 if (start != -1)
2897 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2900 return TRUE;
2903 /******************************************************************
2904 * AttachConsole (KERNEL32.@)
2906 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2908 FIXME("stub %x\n",dwProcessId);
2909 return TRUE;
2912 /******************************************************************
2913 * GetConsoleDisplayMode (KERNEL32.@)
2915 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2917 TRACE("semi-stub: %p\n", lpModeFlags);
2918 /* It is safe to successfully report windowed mode */
2919 *lpModeFlags = 0;
2920 return TRUE;
2923 /******************************************************************
2924 * SetConsoleDisplayMode (KERNEL32.@)
2926 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2927 COORD *lpNewScreenBufferDimensions)
2929 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2930 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2931 if (dwFlags == 1)
2933 /* We cannot switch to fullscreen */
2934 return FALSE;
2936 return TRUE;
2940 /* ====================================================================
2942 * Console manipulation functions
2944 * ====================================================================*/
2946 /* some missing functions...
2947 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2948 * should get the right API and implement them
2949 * SetConsoleCommandHistoryMode
2950 * SetConsoleNumberOfCommands[AW]
2952 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2954 int len = 0;
2956 SERVER_START_REQ( get_console_input_history )
2958 req->handle = 0;
2959 req->index = idx;
2960 if (buf && buf_len > 1)
2962 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2964 if (!wine_server_call_err( req ))
2966 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2967 len = reply->total / sizeof(WCHAR) + 1;
2970 SERVER_END_REQ;
2971 return len;
2974 /******************************************************************
2975 * CONSOLE_AppendHistory
2979 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2981 size_t len = strlenW(ptr);
2982 BOOL ret;
2984 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2985 if (!len) return FALSE;
2987 SERVER_START_REQ( append_console_input_history )
2989 req->handle = 0;
2990 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2991 ret = !wine_server_call_err( req );
2993 SERVER_END_REQ;
2994 return ret;
2997 /******************************************************************
2998 * CONSOLE_GetNumHistoryEntries
3002 unsigned CONSOLE_GetNumHistoryEntries(void)
3004 unsigned ret = -1;
3005 SERVER_START_REQ(get_console_input_info)
3007 req->handle = 0;
3008 if (!wine_server_call_err( req )) ret = reply->history_index;
3010 SERVER_END_REQ;
3011 return ret;
3014 /******************************************************************
3015 * CONSOLE_GetEditionMode
3019 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
3021 unsigned ret = 0;
3022 SERVER_START_REQ(get_console_input_info)
3024 req->handle = console_handle_unmap(hConIn);
3025 if ((ret = !wine_server_call_err( req )))
3026 *mode = reply->edition_mode;
3028 SERVER_END_REQ;
3029 return ret;
3032 /******************************************************************
3033 * GetConsoleAliasW
3036 * RETURNS
3037 * 0 if an error occurred, non-zero for success
3040 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3041 DWORD TargetBufferLength, LPWSTR lpExename)
3043 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3044 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3045 return 0;
3048 /******************************************************************
3049 * GetConsoleProcessList (KERNEL32.@)
3051 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3053 FIXME("(%p,%d): stub\n", processlist, processcount);
3055 if (!processlist || processcount < 1)
3057 SetLastError(ERROR_INVALID_PARAMETER);
3058 return 0;
3061 return 0;
3064 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3066 memset(&S_termios, 0, sizeof(S_termios));
3067 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3069 HANDLE conin;
3071 /* FIXME: to be done even if program is a GUI ? */
3072 /* This is wine specific: we have no parent (we're started from unix)
3073 * so, create a simple console with bare handles
3075 TERM_Init();
3076 wine_server_send_fd(0);
3077 SERVER_START_REQ( alloc_console )
3079 req->access = GENERIC_READ | GENERIC_WRITE;
3080 req->attributes = OBJ_INHERIT;
3081 req->pid = 0xffffffff;
3082 req->input_fd = 0;
3083 wine_server_call( req );
3084 conin = wine_server_ptr_handle( reply->handle_in );
3085 /* reply->event shouldn't be created by server */
3087 SERVER_END_REQ;
3089 if (!params->hStdInput)
3090 params->hStdInput = conin;
3092 if (!params->hStdOutput)
3094 wine_server_send_fd(1);
3095 SERVER_START_REQ( create_console_output )
3097 req->handle_in = wine_server_obj_handle(conin);
3098 req->access = GENERIC_WRITE|GENERIC_READ;
3099 req->attributes = OBJ_INHERIT;
3100 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3101 req->fd = 1;
3102 wine_server_call(req);
3103 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3105 SERVER_END_REQ;
3107 if (!params->hStdError)
3109 wine_server_send_fd(2);
3110 SERVER_START_REQ( create_console_output )
3112 req->handle_in = wine_server_obj_handle(conin);
3113 req->access = GENERIC_WRITE|GENERIC_READ;
3114 req->attributes = OBJ_INHERIT;
3115 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3116 req->fd = 2;
3117 wine_server_call(req);
3118 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3120 SERVER_END_REQ;
3124 /* convert value from server:
3125 * + INVALID_HANDLE_VALUE => TEB: 0, STARTUPINFO: INVALID_HANDLE_VALUE
3126 * + 0 => TEB: 0, STARTUPINFO: INVALID_HANDLE_VALUE
3127 * + console handle needs to be mapped
3129 if (!params->hStdInput || params->hStdInput == INVALID_HANDLE_VALUE)
3130 params->hStdInput = 0;
3131 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3133 params->hStdInput = console_handle_map(params->hStdInput);
3134 save_console_mode(params->hStdInput);
3137 if (!params->hStdOutput || params->hStdOutput == INVALID_HANDLE_VALUE)
3138 params->hStdOutput = 0;
3139 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3140 params->hStdOutput = console_handle_map(params->hStdOutput);
3142 if (!params->hStdError || params->hStdError == INVALID_HANDLE_VALUE)
3143 params->hStdError = 0;
3144 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3145 params->hStdError = console_handle_map(params->hStdError);
3147 return TRUE;
3150 BOOL CONSOLE_Exit(void)
3152 /* the console is in raw mode, put it back in cooked mode */
3153 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));
3156 /* Undocumented, called by native doskey.exe */
3157 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3158 DWORD WINAPI GetConsoleCommandHistoryA(DWORD unknown1, DWORD unknown2, DWORD unknown3)
3160 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
3161 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3162 return 0;
3165 /* Undocumented, called by native doskey.exe */
3166 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3167 DWORD WINAPI GetConsoleCommandHistoryW(DWORD unknown1, DWORD unknown2, DWORD unknown3)
3169 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
3170 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3171 return 0;
3174 /* Undocumented, called by native doskey.exe */
3175 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3176 DWORD WINAPI GetConsoleCommandHistoryLengthA(LPCSTR unknown)
3178 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3179 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3180 return 0;
3183 /* Undocumented, called by native doskey.exe */
3184 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3185 DWORD WINAPI GetConsoleCommandHistoryLengthW(LPCWSTR unknown)
3187 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3188 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3189 return 0;
3192 DWORD WINAPI GetConsoleAliasesLengthA(LPSTR unknown)
3194 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3195 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3196 return 0;
3199 DWORD WINAPI GetConsoleAliasesLengthW(LPWSTR unknown)
3201 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3202 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3203 return 0;
3206 VOID WINAPI ExpungeConsoleCommandHistoryA(LPCSTR unknown)
3208 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3209 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3212 VOID WINAPI ExpungeConsoleCommandHistoryW(LPCWSTR unknown)
3214 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3215 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3218 BOOL WINAPI AddConsoleAliasA(LPSTR source, LPSTR target, LPSTR exename)
3220 FIXME(": (%s, %s, %s) stub!\n", debugstr_a(source), debugstr_a(target), debugstr_a(exename));
3221 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3222 return FALSE;
3225 BOOL WINAPI AddConsoleAliasW(LPWSTR source, LPWSTR target, LPWSTR exename)
3227 FIXME(": (%s, %s, %s) stub!\n", debugstr_w(source), debugstr_w(target), debugstr_w(exename));
3228 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3229 return FALSE;
3233 BOOL WINAPI SetConsoleIcon(HICON icon)
3235 FIXME(": (%p) stub!\n", icon);
3236 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3237 return FALSE;
3240 DWORD WINAPI GetNumberOfConsoleFonts(void)
3242 return 1;
3246 BOOL WINAPI SetConsoleKeyShortcuts(BOOL set, BYTE keys, VOID *a, DWORD b)
3248 FIXME(": (%u %u %p %u) stub!\n", set, keys, a, b);
3249 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3250 return FALSE;
3254 BOOL WINAPI GetCurrentConsoleFont(HANDLE hConsole, BOOL maxwindow, LPCONSOLE_FONT_INFO fontinfo)
3256 BOOL ret;
3258 memset(fontinfo, 0, sizeof(CONSOLE_FONT_INFO));
3260 if (maxwindow)
3262 FIXME(": (%p, %d, %p) stub!\n", hConsole, maxwindow, fontinfo);
3263 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3264 return FALSE;
3267 SERVER_START_REQ(get_console_output_info)
3269 req->handle = console_handle_unmap(hConsole);
3270 if ((ret = !wine_server_call_err(req)))
3272 fontinfo->dwFontSize.X = reply->win_right - reply->win_left + 1;
3273 fontinfo->dwFontSize.Y = reply->win_bottom - reply->win_top + 1;
3276 SERVER_END_REQ;
3277 return ret;
3280 static COORD get_console_font_size(HANDLE hConsole, DWORD index)
3282 COORD c = {0,0};
3284 if (index >= GetNumberOfConsoleFonts())
3286 SetLastError(ERROR_INVALID_PARAMETER);
3287 return c;
3290 SERVER_START_REQ(get_console_output_info)
3292 req->handle = console_handle_unmap(hConsole);
3293 if (!wine_server_call_err(req))
3295 c.X = reply->font_width;
3296 c.Y = reply->font_height;
3299 SERVER_END_REQ;
3300 return c;
3303 #ifdef __i386__
3304 #undef GetConsoleFontSize
3305 DWORD WINAPI GetConsoleFontSize(HANDLE hConsole, DWORD index)
3307 union {
3308 COORD c;
3309 DWORD w;
3310 } x;
3312 x.c = get_console_font_size(hConsole, index);
3313 return x.w;
3315 #endif /* defined(__i386__) */
3318 #ifndef __i386__
3319 COORD WINAPI GetConsoleFontSize(HANDLE hConsole, DWORD index)
3321 return get_console_font_size(hConsole, index);
3323 #endif /* !defined(__i386__) */