shell32/tests: Some tests for IShellWindows.
[wine.git] / dlls / kernel32 / console.c
blob14f11894edba9e8089a4ff59934a1bf8dce3471f
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;
216 if (!S_termios_raw ||
217 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
218 return TRUE;
219 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
220 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
221 close(fd);
222 TERM_Exit();
223 return ret;
226 /******************************************************************************
227 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
229 * RETURNS
230 * Success: hwnd of the console window.
231 * Failure: NULL
233 HWND WINAPI GetConsoleWindow(VOID)
235 HWND hWnd = NULL;
237 SERVER_START_REQ(get_console_input_info)
239 req->handle = 0;
240 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
242 SERVER_END_REQ;
244 return hWnd;
248 /******************************************************************************
249 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
251 * RETURNS
252 * Code page code
254 UINT WINAPI GetConsoleCP(VOID)
256 BOOL ret;
257 UINT codepage = GetOEMCP(); /* default value */
259 SERVER_START_REQ(get_console_input_info)
261 req->handle = 0;
262 ret = !wine_server_call_err(req);
263 if (ret && reply->input_cp)
264 codepage = reply->input_cp;
266 SERVER_END_REQ;
268 return codepage;
272 /******************************************************************************
273 * SetConsoleCP [KERNEL32.@]
275 BOOL WINAPI SetConsoleCP(UINT cp)
277 BOOL ret;
279 if (!IsValidCodePage(cp))
281 SetLastError(ERROR_INVALID_PARAMETER);
282 return FALSE;
285 SERVER_START_REQ(set_console_input_info)
287 req->handle = 0;
288 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
289 req->input_cp = cp;
290 ret = !wine_server_call_err(req);
292 SERVER_END_REQ;
294 return ret;
298 /***********************************************************************
299 * GetConsoleOutputCP (KERNEL32.@)
301 UINT WINAPI GetConsoleOutputCP(VOID)
303 BOOL ret;
304 UINT codepage = GetOEMCP(); /* default value */
306 SERVER_START_REQ(get_console_input_info)
308 req->handle = 0;
309 ret = !wine_server_call_err(req);
310 if (ret && reply->output_cp)
311 codepage = reply->output_cp;
313 SERVER_END_REQ;
315 return codepage;
319 /******************************************************************************
320 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
322 * PARAMS
323 * cp [I] code page to set
325 * RETURNS
326 * Success: TRUE
327 * Failure: FALSE
329 BOOL WINAPI SetConsoleOutputCP(UINT cp)
331 BOOL ret;
333 if (!IsValidCodePage(cp))
335 SetLastError(ERROR_INVALID_PARAMETER);
336 return FALSE;
339 SERVER_START_REQ(set_console_input_info)
341 req->handle = 0;
342 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
343 req->output_cp = cp;
344 ret = !wine_server_call_err(req);
346 SERVER_END_REQ;
348 return ret;
352 /***********************************************************************
353 * Beep (KERNEL32.@)
355 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
357 static const char beep = '\a';
358 /* dwFreq and dwDur are ignored by Win95 */
359 if (isatty(2)) write( 2, &beep, 1 );
360 return TRUE;
364 /******************************************************************
365 * OpenConsoleW (KERNEL32.@)
367 * Undocumented
368 * Open a handle to the current process console.
369 * Returns INVALID_HANDLE_VALUE on failure.
371 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
373 HANDLE output = INVALID_HANDLE_VALUE;
374 HANDLE ret;
376 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
378 if (name)
380 if (strcmpiW(coninW, name) == 0)
381 output = (HANDLE) FALSE;
382 else if (strcmpiW(conoutW, name) == 0)
383 output = (HANDLE) TRUE;
386 if (output == INVALID_HANDLE_VALUE || creation != OPEN_EXISTING)
388 SetLastError(ERROR_INVALID_PARAMETER);
389 return INVALID_HANDLE_VALUE;
392 SERVER_START_REQ( open_console )
394 req->from = wine_server_obj_handle( output );
395 req->access = access;
396 req->attributes = inherit ? OBJ_INHERIT : 0;
397 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
398 wine_server_call_err( req );
399 ret = wine_server_ptr_handle( reply->handle );
401 SERVER_END_REQ;
402 if (ret)
403 ret = console_handle_map(ret);
405 return ret;
408 /******************************************************************
409 * VerifyConsoleIoHandle (KERNEL32.@)
411 * Undocumented
413 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
415 BOOL ret;
417 if (!is_console_handle(handle)) return FALSE;
418 SERVER_START_REQ(get_console_mode)
420 req->handle = console_handle_unmap(handle);
421 ret = !wine_server_call( req );
423 SERVER_END_REQ;
424 return ret;
427 /******************************************************************
428 * DuplicateConsoleHandle (KERNEL32.@)
430 * Undocumented
432 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
433 DWORD options)
435 HANDLE ret;
437 if (!is_console_handle(handle) ||
438 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
439 GetCurrentProcess(), &ret, access, inherit, options))
440 return INVALID_HANDLE_VALUE;
441 return console_handle_map(ret);
444 /******************************************************************
445 * CloseConsoleHandle (KERNEL32.@)
447 * Undocumented
449 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
451 if (!is_console_handle(handle))
453 SetLastError(ERROR_INVALID_PARAMETER);
454 return FALSE;
456 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
459 /******************************************************************
460 * GetConsoleInputWaitHandle (KERNEL32.@)
462 * Undocumented
464 HANDLE WINAPI GetConsoleInputWaitHandle(void)
466 if (!console_wait_event)
468 SERVER_START_REQ(get_console_wait_event)
470 if (!wine_server_call_err( req ))
471 console_wait_event = wine_server_ptr_handle( reply->handle );
473 SERVER_END_REQ;
475 return console_wait_event;
479 /******************************************************************************
480 * WriteConsoleInputA [KERNEL32.@]
482 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
483 DWORD count, LPDWORD written )
485 INPUT_RECORD *recW = NULL;
486 BOOL ret;
488 if (count > 0)
490 if (!buffer)
492 SetLastError( ERROR_INVALID_ACCESS );
493 return FALSE;
496 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) )))
498 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
499 return FALSE;
502 memcpy( recW, buffer, count * sizeof(*recW) );
503 input_records_AtoW( recW, count );
506 ret = WriteConsoleInputW( handle, recW, count, written );
507 HeapFree( GetProcessHeap(), 0, recW );
508 return ret;
512 /******************************************************************************
513 * WriteConsoleInputW [KERNEL32.@]
515 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
516 DWORD count, LPDWORD written )
518 DWORD events_written = 0;
519 BOOL ret;
521 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
523 if (count > 0 && !buffer)
525 SetLastError(ERROR_INVALID_ACCESS);
526 return FALSE;
529 SERVER_START_REQ( write_console_input )
531 req->handle = console_handle_unmap(handle);
532 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
533 if ((ret = !wine_server_call_err( req )))
534 events_written = reply->written;
536 SERVER_END_REQ;
538 if (written) *written = events_written;
539 else
541 SetLastError(ERROR_INVALID_ACCESS);
542 ret = FALSE;
544 return ret;
548 /***********************************************************************
549 * WriteConsoleOutputA (KERNEL32.@)
551 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
552 COORD size, COORD coord, LPSMALL_RECT region )
554 int y;
555 BOOL ret;
556 COORD new_size, new_coord;
557 CHAR_INFO *ciw;
559 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
560 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
562 if (new_size.X <= 0 || new_size.Y <= 0)
564 region->Bottom = region->Top + new_size.Y - 1;
565 region->Right = region->Left + new_size.X - 1;
566 return TRUE;
569 /* only copy the useful rectangle */
570 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
571 return FALSE;
572 for (y = 0; y < new_size.Y; y++)
574 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
575 new_size.X * sizeof(CHAR_INFO) );
576 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
578 new_coord.X = new_coord.Y = 0;
579 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
580 HeapFree( GetProcessHeap(), 0, ciw );
581 return ret;
585 /***********************************************************************
586 * WriteConsoleOutputW (KERNEL32.@)
588 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
589 COORD size, COORD coord, LPSMALL_RECT region )
591 int width, height, y;
592 BOOL ret = TRUE;
594 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
595 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
596 region->Left, region->Top, region->Right, region->Bottom);
598 width = min( region->Right - region->Left + 1, size.X - coord.X );
599 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
601 if (width > 0 && height > 0)
603 for (y = 0; y < height; y++)
605 SERVER_START_REQ( write_console_output )
607 req->handle = console_handle_unmap(hConsoleOutput);
608 req->x = region->Left;
609 req->y = region->Top + y;
610 req->mode = CHAR_INFO_MODE_TEXTATTR;
611 req->wrap = FALSE;
612 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
613 width * sizeof(CHAR_INFO));
614 if ((ret = !wine_server_call_err( req )))
616 width = min( width, reply->width - region->Left );
617 height = min( height, reply->height - region->Top );
620 SERVER_END_REQ;
621 if (!ret) break;
624 region->Bottom = region->Top + height - 1;
625 region->Right = region->Left + width - 1;
626 return ret;
630 /******************************************************************************
631 * WriteConsoleOutputCharacterA [KERNEL32.@]
633 * See WriteConsoleOutputCharacterW.
635 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
636 COORD coord, LPDWORD lpNumCharsWritten )
638 BOOL ret;
639 LPWSTR strW = NULL;
640 DWORD lenW = 0;
642 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
643 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
645 if (length > 0)
647 if (!str)
649 SetLastError( ERROR_INVALID_ACCESS );
650 return FALSE;
653 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
655 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
657 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
658 return FALSE;
661 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
664 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
665 HeapFree( GetProcessHeap(), 0, strW );
666 return ret;
670 /******************************************************************************
671 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
672 * the console screen buffer
674 * PARAMS
675 * hConsoleOutput [I] Handle to screen buffer
676 * attr [I] Pointer to buffer with write attributes
677 * length [I] Number of cells to write to
678 * coord [I] Coords of first cell
679 * lpNumAttrsWritten [O] Pointer to number of cells written
681 * RETURNS
682 * Success: TRUE
683 * Failure: FALSE
686 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, const WORD *attr, DWORD length,
687 COORD coord, LPDWORD lpNumAttrsWritten )
689 BOOL ret;
691 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
693 if ((length > 0 && !attr) || !lpNumAttrsWritten)
695 SetLastError(ERROR_INVALID_ACCESS);
696 return FALSE;
699 *lpNumAttrsWritten = 0;
701 SERVER_START_REQ( write_console_output )
703 req->handle = console_handle_unmap(hConsoleOutput);
704 req->x = coord.X;
705 req->y = coord.Y;
706 req->mode = CHAR_INFO_MODE_ATTR;
707 req->wrap = TRUE;
708 wine_server_add_data( req, attr, length * sizeof(WORD) );
709 if ((ret = !wine_server_call_err( req )))
710 *lpNumAttrsWritten = reply->written;
712 SERVER_END_REQ;
713 return ret;
717 /******************************************************************************
718 * FillConsoleOutputCharacterA [KERNEL32.@]
720 * See FillConsoleOutputCharacterW.
722 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
723 COORD coord, LPDWORD lpNumCharsWritten )
725 WCHAR wch;
727 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
728 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
732 /******************************************************************************
733 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
735 * PARAMS
736 * hConsoleOutput [I] Handle to screen buffer
737 * ch [I] Character to write
738 * length [I] Number of cells to write to
739 * coord [I] Coords of first cell
740 * lpNumCharsWritten [O] Pointer to number of cells written
742 * RETURNS
743 * Success: TRUE
744 * Failure: FALSE
746 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
747 COORD coord, LPDWORD lpNumCharsWritten)
749 BOOL ret;
751 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
752 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
754 if (!lpNumCharsWritten)
756 SetLastError(ERROR_INVALID_ACCESS);
757 return FALSE;
760 *lpNumCharsWritten = 0;
762 SERVER_START_REQ( fill_console_output )
764 req->handle = console_handle_unmap(hConsoleOutput);
765 req->x = coord.X;
766 req->y = coord.Y;
767 req->mode = CHAR_INFO_MODE_TEXT;
768 req->wrap = TRUE;
769 req->data.ch = ch;
770 req->count = length;
771 if ((ret = !wine_server_call_err( req )))
772 *lpNumCharsWritten = reply->written;
774 SERVER_END_REQ;
775 return ret;
779 /******************************************************************************
780 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
782 * PARAMS
783 * hConsoleOutput [I] Handle to screen buffer
784 * attr [I] Color attribute to write
785 * length [I] Number of cells to write to
786 * coord [I] Coords of first cell
787 * lpNumAttrsWritten [O] Pointer to number of cells written
789 * RETURNS
790 * Success: TRUE
791 * Failure: FALSE
793 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
794 COORD coord, LPDWORD lpNumAttrsWritten )
796 BOOL ret;
798 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
799 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
801 if (!lpNumAttrsWritten)
803 SetLastError(ERROR_INVALID_ACCESS);
804 return FALSE;
807 *lpNumAttrsWritten = 0;
809 SERVER_START_REQ( fill_console_output )
811 req->handle = console_handle_unmap(hConsoleOutput);
812 req->x = coord.X;
813 req->y = coord.Y;
814 req->mode = CHAR_INFO_MODE_ATTR;
815 req->wrap = TRUE;
816 req->data.attr = attr;
817 req->count = length;
818 if ((ret = !wine_server_call_err( req )))
819 *lpNumAttrsWritten = reply->written;
821 SERVER_END_REQ;
822 return ret;
826 /******************************************************************************
827 * ReadConsoleOutputCharacterA [KERNEL32.@]
830 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
831 COORD coord, LPDWORD read_count)
833 DWORD read;
834 BOOL ret;
835 LPWSTR wptr;
837 if (!read_count)
839 SetLastError(ERROR_INVALID_ACCESS);
840 return FALSE;
843 *read_count = 0;
845 if (!(wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR))))
847 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
848 return FALSE;
851 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
853 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
854 *read_count = read;
856 HeapFree( GetProcessHeap(), 0, wptr );
857 return ret;
861 /******************************************************************************
862 * ReadConsoleOutputCharacterW [KERNEL32.@]
865 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
866 COORD coord, LPDWORD read_count )
868 BOOL ret;
870 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
872 if (!read_count)
874 SetLastError(ERROR_INVALID_ACCESS);
875 return FALSE;
878 *read_count = 0;
880 SERVER_START_REQ( read_console_output )
882 req->handle = console_handle_unmap(hConsoleOutput);
883 req->x = coord.X;
884 req->y = coord.Y;
885 req->mode = CHAR_INFO_MODE_TEXT;
886 req->wrap = TRUE;
887 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
888 if ((ret = !wine_server_call_err( req )))
889 *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
891 SERVER_END_REQ;
892 return ret;
896 /******************************************************************************
897 * ReadConsoleOutputAttribute [KERNEL32.@]
899 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
900 COORD coord, LPDWORD read_count)
902 BOOL ret;
904 TRACE("(%p,%p,%d,%dx%d,%p)\n",
905 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
907 if (!read_count)
909 SetLastError(ERROR_INVALID_ACCESS);
910 return FALSE;
913 *read_count = 0;
915 SERVER_START_REQ( read_console_output )
917 req->handle = console_handle_unmap(hConsoleOutput);
918 req->x = coord.X;
919 req->y = coord.Y;
920 req->mode = CHAR_INFO_MODE_ATTR;
921 req->wrap = TRUE;
922 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
923 if ((ret = !wine_server_call_err( req )))
924 *read_count = wine_server_reply_size(reply) / sizeof(WORD);
926 SERVER_END_REQ;
927 return ret;
931 /******************************************************************************
932 * ReadConsoleOutputA [KERNEL32.@]
935 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
936 COORD coord, LPSMALL_RECT region )
938 BOOL ret;
939 int y;
941 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
942 if (ret && region->Right >= region->Left)
944 for (y = 0; y <= region->Bottom - region->Top; y++)
946 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
947 region->Right - region->Left + 1 );
950 return ret;
954 /******************************************************************************
955 * ReadConsoleOutputW [KERNEL32.@]
957 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
958 * think we need to be *that* compatible. -- AJ
960 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
961 COORD coord, LPSMALL_RECT region )
963 int width, height, y;
964 BOOL ret = TRUE;
966 width = min( region->Right - region->Left + 1, size.X - coord.X );
967 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
969 if (width > 0 && height > 0)
971 for (y = 0; y < height; y++)
973 SERVER_START_REQ( read_console_output )
975 req->handle = console_handle_unmap(hConsoleOutput);
976 req->x = region->Left;
977 req->y = region->Top + y;
978 req->mode = CHAR_INFO_MODE_TEXTATTR;
979 req->wrap = FALSE;
980 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
981 width * sizeof(CHAR_INFO) );
982 if ((ret = !wine_server_call_err( req )))
984 width = min( width, reply->width - region->Left );
985 height = min( height, reply->height - region->Top );
988 SERVER_END_REQ;
989 if (!ret) break;
992 region->Bottom = region->Top + height - 1;
993 region->Right = region->Left + width - 1;
994 return ret;
998 /******************************************************************************
999 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
1001 * PARAMS
1002 * handle [I] Handle to console input buffer
1003 * buffer [O] Address of buffer for read data
1004 * count [I] Number of records to read
1005 * pRead [O] Address of number of records read
1007 * RETURNS
1008 * Success: TRUE
1009 * Failure: FALSE
1011 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1013 DWORD read;
1015 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
1016 input_records_WtoA( buffer, read );
1017 if (pRead) *pRead = read;
1018 return TRUE;
1022 /***********************************************************************
1023 * PeekConsoleInputA (KERNEL32.@)
1025 * Gets 'count' first events (or less) from input queue.
1027 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1029 DWORD read;
1031 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
1032 input_records_WtoA( buffer, read );
1033 if (pRead) *pRead = read;
1034 return TRUE;
1038 /***********************************************************************
1039 * PeekConsoleInputW (KERNEL32.@)
1041 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
1043 BOOL ret;
1044 SERVER_START_REQ( read_console_input )
1046 req->handle = console_handle_unmap(handle);
1047 req->flush = FALSE;
1048 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1049 if ((ret = !wine_server_call_err( req )))
1051 if (read) *read = count ? reply->read : 0;
1054 SERVER_END_REQ;
1055 return ret;
1059 /***********************************************************************
1060 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1062 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1064 BOOL ret;
1065 SERVER_START_REQ( read_console_input )
1067 req->handle = console_handle_unmap(handle);
1068 req->flush = FALSE;
1069 if ((ret = !wine_server_call_err( req )))
1071 if (nrofevents)
1072 *nrofevents = reply->read;
1073 else
1075 SetLastError(ERROR_INVALID_ACCESS);
1076 ret = FALSE;
1080 SERVER_END_REQ;
1081 return ret;
1085 /******************************************************************************
1086 * read_console_input
1088 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1090 * Returns
1091 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1093 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1095 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1097 enum read_console_input_return ret;
1098 char input[8];
1099 WCHAR inputw[8];
1100 int i;
1101 size_t idx = 0, idxw;
1102 unsigned numEvent;
1103 INPUT_RECORD ir[8];
1104 DWORD written;
1105 struct pollfd pollfd;
1106 BOOL locked = FALSE, next_char;
1110 if (idx == sizeof(input))
1112 FIXME("buffer too small (%s)\n", wine_dbgstr_an(input, idx));
1113 ret = rci_error;
1114 break;
1116 pollfd.fd = fd;
1117 pollfd.events = POLLIN;
1118 pollfd.revents = 0;
1119 next_char = FALSE;
1121 switch (poll(&pollfd, 1, timeout))
1123 case 1:
1124 if (!locked)
1126 RtlEnterCriticalSection(&CONSOLE_CritSect);
1127 locked = TRUE;
1129 i = read(fd, &input[idx], 1);
1130 if (i < 0)
1132 ret = rci_error;
1133 break;
1135 if (i == 0)
1137 /* actually another thread likely beat us to reading the char
1138 * return rci_gotone, while not perfect, it should work in most of the cases (as the new event
1139 * should be now in the queue, fed from the other thread)
1141 ret = rci_gotone;
1142 break;
1145 idx++;
1146 numEvent = TERM_FillInputRecord(input, idx, ir);
1147 switch (numEvent)
1149 case 0:
1150 /* we need more char(s) to tell if it matches a key-db entry. wait 1/2s for next char */
1151 timeout = 500;
1152 next_char = TRUE;
1153 break;
1154 case -1:
1155 /* we haven't found the string into key-db, push full input string into server */
1156 idxw = MultiByteToWideChar(CP_UNIXCP, 0, input, idx, inputw, sizeof(inputw) / sizeof(inputw[0]));
1158 /* we cannot translate yet... likely we need more chars (wait max 1/2s for next char) */
1159 if (idxw == 0)
1161 timeout = 500;
1162 next_char = TRUE;
1163 break;
1165 for (i = 0; i < idxw; i++)
1167 numEvent = TERM_FillSimpleChar(inputw[i], ir);
1168 WriteConsoleInputW(handle, ir, numEvent, &written);
1170 ret = rci_gotone;
1171 break;
1172 default:
1173 /* we got a transformation from key-db... push this into server */
1174 ret = WriteConsoleInputW(handle, ir, numEvent, &written) ? rci_gotone : rci_error;
1175 break;
1177 break;
1178 case 0: ret = rci_timeout; break;
1179 default: ret = rci_error; break;
1181 } while (next_char);
1182 if (locked) RtlLeaveCriticalSection(&CONSOLE_CritSect);
1184 return ret;
1187 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1189 int fd;
1190 enum read_console_input_return ret;
1192 if ((fd = get_console_bare_fd(handle)) != -1)
1194 put_console_into_raw_mode(fd);
1195 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1197 ret = bare_console_fetch_input(handle, fd, timeout);
1199 else ret = rci_gotone;
1200 close(fd);
1201 if (ret != rci_gotone) return ret;
1203 else
1205 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1207 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1208 return rci_timeout;
1211 SERVER_START_REQ( read_console_input )
1213 req->handle = console_handle_unmap(handle);
1214 req->flush = TRUE;
1215 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1216 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1217 else ret = rci_gotone;
1219 SERVER_END_REQ;
1221 return ret;
1225 /***********************************************************************
1226 * FlushConsoleInputBuffer (KERNEL32.@)
1228 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1230 enum read_console_input_return last;
1231 INPUT_RECORD ir;
1233 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1235 return last == rci_timeout;
1239 /***********************************************************************
1240 * SetConsoleTitleA (KERNEL32.@)
1242 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1244 LPWSTR titleW;
1245 BOOL ret;
1247 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1248 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1249 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1250 ret = SetConsoleTitleW(titleW);
1251 HeapFree(GetProcessHeap(), 0, titleW);
1252 return ret;
1256 /***********************************************************************
1257 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1259 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1261 FIXME( "stub %p\n", layoutName);
1262 return TRUE;
1265 /***********************************************************************
1266 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1268 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1270 static int once;
1271 if (!once++)
1272 FIXME( "stub %p\n", layoutName);
1273 return TRUE;
1276 static WCHAR input_exe[MAX_PATH + 1];
1278 /***********************************************************************
1279 * GetConsoleInputExeNameW (KERNEL32.@)
1281 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1283 TRACE("%u %p\n", buflen, buffer);
1285 RtlEnterCriticalSection(&CONSOLE_CritSect);
1286 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1287 else SetLastError(ERROR_BUFFER_OVERFLOW);
1288 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1290 return TRUE;
1293 /***********************************************************************
1294 * GetConsoleInputExeNameA (KERNEL32.@)
1296 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1298 TRACE("%u %p\n", buflen, buffer);
1300 RtlEnterCriticalSection(&CONSOLE_CritSect);
1301 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1302 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1303 else SetLastError(ERROR_BUFFER_OVERFLOW);
1304 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1306 return TRUE;
1309 /***********************************************************************
1310 * GetConsoleTitleA (KERNEL32.@)
1312 * See GetConsoleTitleW.
1314 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1316 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1317 DWORD ret;
1319 if (!ptr) return 0;
1320 ret = GetConsoleTitleW( ptr, size );
1321 if (ret)
1323 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1324 ret = strlen(title);
1326 HeapFree(GetProcessHeap(), 0, ptr);
1327 return ret;
1331 /******************************************************************************
1332 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1334 * PARAMS
1335 * title [O] Address of buffer for title
1336 * size [I] Size of buffer
1338 * RETURNS
1339 * Success: Length of string copied
1340 * Failure: 0
1342 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1344 DWORD ret = 0;
1346 SERVER_START_REQ( get_console_input_info )
1348 req->handle = 0;
1349 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1350 if (!wine_server_call_err( req ))
1352 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1353 title[ret] = 0;
1356 SERVER_END_REQ;
1357 return ret;
1361 /***********************************************************************
1362 * GetLargestConsoleWindowSize (KERNEL32.@)
1364 * NOTE
1365 * This should return a COORD, but calling convention for returning
1366 * structures is different between Windows and gcc on i386.
1368 * VERSION: [i386]
1370 #ifdef __i386__
1371 #undef GetLargestConsoleWindowSize
1372 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1374 union {
1375 COORD c;
1376 DWORD w;
1377 } x;
1378 x.c.X = 80;
1379 x.c.Y = 24;
1380 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1381 return x.w;
1383 #endif /* defined(__i386__) */
1386 /***********************************************************************
1387 * GetLargestConsoleWindowSize (KERNEL32.@)
1389 * NOTE
1390 * This should return a COORD, but calling convention for returning
1391 * structures is different between Windows and gcc on i386.
1393 * VERSION: [!i386]
1395 #ifndef __i386__
1396 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1398 COORD c;
1399 c.X = 80;
1400 c.Y = 24;
1401 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1402 return c;
1404 #endif /* defined(__i386__) */
1406 static WCHAR* S_EditString /* = NULL */;
1407 static unsigned S_EditStrPos /* = 0 */;
1409 /***********************************************************************
1410 * FreeConsole (KERNEL32.@)
1412 BOOL WINAPI FreeConsole(VOID)
1414 BOOL ret;
1416 /* invalidate local copy of input event handle */
1417 console_wait_event = 0;
1419 SERVER_START_REQ(free_console)
1421 ret = !wine_server_call_err( req );
1423 SERVER_END_REQ;
1424 return ret;
1427 /******************************************************************
1428 * start_console_renderer
1430 * helper for AllocConsole
1431 * starts the renderer process
1433 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1434 HANDLE hEvent)
1436 char buffer[1024];
1437 int ret;
1438 PROCESS_INFORMATION pi;
1440 /* FIXME: use dynamic allocation for most of the buffers below */
1441 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1442 if ((ret > -1) && (ret < sizeof(buffer)) &&
1443 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1444 NULL, NULL, si, &pi))
1446 HANDLE wh[2];
1447 DWORD res;
1449 wh[0] = hEvent;
1450 wh[1] = pi.hProcess;
1451 res = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1453 CloseHandle(pi.hThread);
1454 CloseHandle(pi.hProcess);
1456 if (res != WAIT_OBJECT_0) return FALSE;
1458 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1459 pi.dwProcessId, pi.dwThreadId);
1461 return TRUE;
1463 return FALSE;
1466 static BOOL start_console_renderer(STARTUPINFOA* si)
1468 HANDLE hEvent = 0;
1469 LPSTR p;
1470 OBJECT_ATTRIBUTES attr;
1471 BOOL ret = FALSE;
1473 attr.Length = sizeof(attr);
1474 attr.RootDirectory = 0;
1475 attr.Attributes = OBJ_INHERIT;
1476 attr.ObjectName = NULL;
1477 attr.SecurityDescriptor = NULL;
1478 attr.SecurityQualityOfService = NULL;
1480 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1481 if (!hEvent) return FALSE;
1483 /* first try environment variable */
1484 if ((p = getenv("WINECONSOLE")) != NULL)
1486 ret = start_console_renderer_helper(p, si, hEvent);
1487 if (!ret)
1488 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1489 "trying default access\n", p);
1492 /* then try the regular PATH */
1493 if (!ret)
1494 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1496 CloseHandle(hEvent);
1497 return ret;
1500 /***********************************************************************
1501 * AllocConsole (KERNEL32.@)
1503 * creates an xterm with a pty to our program
1505 BOOL WINAPI AllocConsole(void)
1507 HANDLE handle_in = INVALID_HANDLE_VALUE;
1508 HANDLE handle_out = INVALID_HANDLE_VALUE;
1509 HANDLE handle_err = INVALID_HANDLE_VALUE;
1510 STARTUPINFOA siCurrent;
1511 STARTUPINFOA siConsole;
1512 char buffer[1024];
1514 TRACE("()\n");
1516 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1517 FALSE, OPEN_EXISTING );
1519 if (VerifyConsoleIoHandle(handle_in))
1521 /* we already have a console opened on this process, don't create a new one */
1522 CloseHandle(handle_in);
1523 return FALSE;
1526 /* invalidate local copy of input event handle */
1527 console_wait_event = 0;
1529 GetStartupInfoA(&siCurrent);
1531 memset(&siConsole, 0, sizeof(siConsole));
1532 siConsole.cb = sizeof(siConsole);
1533 /* setup a view arguments for wineconsole (it'll use them as default values) */
1534 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1536 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1537 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1538 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1540 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1542 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1543 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1545 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1547 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1548 siConsole.wShowWindow = siCurrent.wShowWindow;
1550 /* FIXME (should pass the unicode form) */
1551 if (siCurrent.lpTitle)
1552 siConsole.lpTitle = siCurrent.lpTitle;
1553 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1555 buffer[sizeof(buffer) - 1] = '\0';
1556 siConsole.lpTitle = buffer;
1559 if (!start_console_renderer(&siConsole))
1560 goto the_end;
1562 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1563 /* all std I/O handles are inheritable by default */
1564 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1565 TRUE, OPEN_EXISTING );
1566 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1568 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1569 TRUE, OPEN_EXISTING );
1570 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1572 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1573 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1574 goto the_end;
1575 } else {
1576 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1577 handle_in = siCurrent.hStdInput;
1578 handle_out = siCurrent.hStdOutput;
1579 handle_err = siCurrent.hStdError;
1582 /* NT resets the STD_*_HANDLEs on console alloc */
1583 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1584 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1585 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1587 SetLastError(ERROR_SUCCESS);
1589 return TRUE;
1591 the_end:
1592 ERR("Can't allocate console\n");
1593 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1594 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1595 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1596 FreeConsole();
1597 return FALSE;
1601 /***********************************************************************
1602 * ReadConsoleA (KERNEL32.@)
1604 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1605 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1607 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1608 DWORD ncr = 0;
1609 BOOL ret;
1611 if (!ptr)
1613 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1614 return FALSE;
1617 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1619 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1620 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1622 HeapFree(GetProcessHeap(), 0, ptr);
1624 return ret;
1627 /***********************************************************************
1628 * ReadConsoleW (KERNEL32.@)
1630 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1631 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1633 DWORD charsread;
1634 LPWSTR xbuf = lpBuffer;
1635 DWORD mode;
1636 BOOL is_bare = FALSE;
1637 int fd;
1639 TRACE("(%p,%p,%d,%p,%p)\n",
1640 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1642 if (nNumberOfCharsToRead > INT_MAX)
1644 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1645 return FALSE;
1648 if (!GetConsoleMode(hConsoleInput, &mode))
1649 return FALSE;
1650 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1652 close(fd);
1653 is_bare = TRUE;
1655 if (mode & ENABLE_LINE_INPUT)
1657 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1659 HeapFree(GetProcessHeap(), 0, S_EditString);
1660 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1661 return FALSE;
1662 S_EditStrPos = 0;
1664 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1665 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1666 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1667 S_EditStrPos += charsread;
1669 else
1671 INPUT_RECORD ir;
1672 DWORD timeout = INFINITE;
1674 /* FIXME: should we read at least 1 char? The SDK does not say */
1675 /* wait for at least one available input record (it doesn't mean we'll have
1676 * chars stored in xbuf...)
1678 * Although SDK doc keeps silence about 1 char, SDK examples assume
1679 * that we should wait for at least one character (not key). --KS
1681 charsread = 0;
1684 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1685 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1686 ir.Event.KeyEvent.uChar.UnicodeChar)
1688 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1689 timeout = 0;
1691 } while (charsread < nNumberOfCharsToRead);
1692 /* nothing has been read */
1693 if (timeout == INFINITE) return FALSE;
1696 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1698 return TRUE;
1702 /***********************************************************************
1703 * ReadConsoleInputW (KERNEL32.@)
1705 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1706 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1708 DWORD idx = 0;
1709 DWORD timeout = INFINITE;
1711 if (!nLength)
1713 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1714 return TRUE;
1717 /* loop until we get at least one event */
1718 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1719 ++idx < nLength)
1720 timeout = 0;
1722 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1723 return idx != 0;
1727 /******************************************************************************
1728 * WriteConsoleOutputCharacterW [KERNEL32.@]
1730 * Copy character to consecutive cells in the console screen buffer.
1732 * PARAMS
1733 * hConsoleOutput [I] Handle to screen buffer
1734 * str [I] Pointer to buffer with chars to write
1735 * length [I] Number of cells to write to
1736 * coord [I] Coords of first cell
1737 * lpNumCharsWritten [O] Pointer to number of cells written
1739 * RETURNS
1740 * Success: TRUE
1741 * Failure: FALSE
1744 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1745 COORD coord, LPDWORD lpNumCharsWritten )
1747 BOOL ret;
1749 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1750 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1752 if ((length > 0 && !str) || !lpNumCharsWritten)
1754 SetLastError(ERROR_INVALID_ACCESS);
1755 return FALSE;
1758 *lpNumCharsWritten = 0;
1760 SERVER_START_REQ( write_console_output )
1762 req->handle = console_handle_unmap(hConsoleOutput);
1763 req->x = coord.X;
1764 req->y = coord.Y;
1765 req->mode = CHAR_INFO_MODE_TEXT;
1766 req->wrap = TRUE;
1767 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1768 if ((ret = !wine_server_call_err( req )))
1769 *lpNumCharsWritten = reply->written;
1771 SERVER_END_REQ;
1772 return ret;
1776 /******************************************************************************
1777 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1779 * PARAMS
1780 * title [I] Address of new title
1782 * RETURNS
1783 * Success: TRUE
1784 * Failure: FALSE
1786 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1788 BOOL ret;
1790 TRACE("(%s)\n", debugstr_w(title));
1791 SERVER_START_REQ( set_console_input_info )
1793 req->handle = 0;
1794 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1795 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1796 ret = !wine_server_call_err( req );
1798 SERVER_END_REQ;
1799 return ret;
1803 /***********************************************************************
1804 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1806 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1808 FIXME("(%p): stub\n", nrofbuttons);
1809 *nrofbuttons = 2;
1810 return TRUE;
1813 /******************************************************************************
1814 * SetConsoleInputExeNameW [KERNEL32.@]
1816 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1818 TRACE("(%s)\n", debugstr_w(name));
1820 if (!name || !name[0])
1822 SetLastError(ERROR_INVALID_PARAMETER);
1823 return FALSE;
1826 RtlEnterCriticalSection(&CONSOLE_CritSect);
1827 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1828 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1830 return TRUE;
1833 /******************************************************************************
1834 * SetConsoleInputExeNameA [KERNEL32.@]
1836 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1838 int len;
1839 LPWSTR nameW;
1840 BOOL ret;
1842 if (!name || !name[0])
1844 SetLastError(ERROR_INVALID_PARAMETER);
1845 return FALSE;
1848 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1849 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1851 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1852 ret = SetConsoleInputExeNameW(nameW);
1853 HeapFree(GetProcessHeap(), 0, nameW);
1855 return ret;
1858 /******************************************************************
1859 * CONSOLE_DefaultHandler
1861 * Final control event handler
1863 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1865 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1866 ExitProcess(0);
1867 /* should never go here */
1868 return TRUE;
1871 /******************************************************************************
1872 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1874 * PARAMS
1875 * func [I] Address of handler function
1876 * add [I] Handler to add or remove
1878 * RETURNS
1879 * Success: TRUE
1880 * Failure: FALSE
1883 struct ConsoleHandler
1885 PHANDLER_ROUTINE handler;
1886 struct ConsoleHandler* next;
1889 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1890 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1892 /*****************************************************************************/
1894 /******************************************************************
1895 * SetConsoleCtrlHandler (KERNEL32.@)
1897 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1899 BOOL ret = TRUE;
1901 TRACE("(%p,%i)\n", func, add);
1903 if (!func)
1905 RtlEnterCriticalSection(&CONSOLE_CritSect);
1906 if (add)
1907 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1908 else
1909 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1910 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1912 else if (add)
1914 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1916 if (!ch) return FALSE;
1917 ch->handler = func;
1918 RtlEnterCriticalSection(&CONSOLE_CritSect);
1919 ch->next = CONSOLE_Handlers;
1920 CONSOLE_Handlers = ch;
1921 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1923 else
1925 struct ConsoleHandler** ch;
1926 RtlEnterCriticalSection(&CONSOLE_CritSect);
1927 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1929 if ((*ch)->handler == func) break;
1931 if (*ch)
1933 struct ConsoleHandler* rch = *ch;
1935 /* sanity check */
1936 if (rch == &CONSOLE_DefaultConsoleHandler)
1938 ERR("Who's trying to remove default handler???\n");
1939 SetLastError(ERROR_INVALID_PARAMETER);
1940 ret = FALSE;
1942 else
1944 *ch = rch->next;
1945 HeapFree(GetProcessHeap(), 0, rch);
1948 else
1950 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1951 SetLastError(ERROR_INVALID_PARAMETER);
1952 ret = FALSE;
1954 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1956 return ret;
1959 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1961 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1962 return EXCEPTION_EXECUTE_HANDLER;
1965 /******************************************************************
1966 * CONSOLE_SendEventThread
1968 * Internal helper to pass an event to the list on installed handlers
1970 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1972 DWORD_PTR event = (DWORD_PTR)pmt;
1973 struct ConsoleHandler* ch;
1975 if (event == CTRL_C_EVENT)
1977 BOOL caught_by_dbg = TRUE;
1978 /* First, try to pass the ctrl-C event to the debugger (if any)
1979 * If it continues, there's nothing more to do
1980 * Otherwise, we need to send the ctrl-C event to the handlers
1982 __TRY
1984 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1986 __EXCEPT(CONSOLE_CtrlEventHandler)
1988 caught_by_dbg = FALSE;
1990 __ENDTRY;
1991 if (caught_by_dbg) return 0;
1992 /* the debugger didn't continue... so, pass to ctrl handlers */
1994 RtlEnterCriticalSection(&CONSOLE_CritSect);
1995 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1997 if (ch->handler(event)) break;
1999 RtlLeaveCriticalSection(&CONSOLE_CritSect);
2000 return 1;
2003 /******************************************************************
2004 * CONSOLE_HandleCtrlC
2006 * Check whether the shall manipulate CtrlC events
2008 int CONSOLE_HandleCtrlC(unsigned sig)
2010 HANDLE thread;
2012 /* FIXME: better test whether a console is attached to this process ??? */
2013 extern unsigned CONSOLE_GetNumHistoryEntries(void);
2014 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
2016 /* check if we have to ignore ctrl-C events */
2017 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
2019 /* Create a separate thread to signal all the events.
2020 * This is needed because:
2021 * - this function can be called in an Unix signal handler (hence on an
2022 * different stack than the thread that's running). This breaks the
2023 * Win32 exception mechanisms (where the thread's stack is checked).
2024 * - since the current thread, while processing the signal, can hold the
2025 * console critical section, we need another execution environment where
2026 * we can wait on this critical section
2028 thread = CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2029 if (thread == NULL)
2030 return 0;
2032 CloseHandle(thread);
2034 return 1;
2037 /******************************************************************************
2038 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2040 * PARAMS
2041 * dwCtrlEvent [I] Type of event
2042 * dwProcessGroupID [I] Process group ID to send event to
2044 * RETURNS
2045 * Success: True
2046 * Failure: False (and *should* [but doesn't] set LastError)
2048 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2049 DWORD dwProcessGroupID)
2051 BOOL ret;
2053 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2055 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2057 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2058 return FALSE;
2061 SERVER_START_REQ( send_console_signal )
2063 req->signal = dwCtrlEvent;
2064 req->group_id = dwProcessGroupID;
2065 ret = !wine_server_call_err( req );
2067 SERVER_END_REQ;
2069 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2070 * have been handled by all processes in the given group?
2071 * As of today, we don't wait...
2073 return ret;
2077 /******************************************************************************
2078 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2080 * PARAMS
2081 * dwDesiredAccess [I] Access flag
2082 * dwShareMode [I] Buffer share mode
2083 * sa [I] Security attributes
2084 * dwFlags [I] Type of buffer to create
2085 * lpScreenBufferData [I] Reserved
2087 * NOTES
2088 * Should call SetLastError
2090 * RETURNS
2091 * Success: Handle to new console screen buffer
2092 * Failure: INVALID_HANDLE_VALUE
2094 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2095 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2096 LPVOID lpScreenBufferData)
2098 HANDLE ret = INVALID_HANDLE_VALUE;
2100 TRACE("(%d,%d,%p,%d,%p)\n",
2101 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2103 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2105 SetLastError(ERROR_INVALID_PARAMETER);
2106 return INVALID_HANDLE_VALUE;
2109 SERVER_START_REQ(create_console_output)
2111 req->handle_in = 0;
2112 req->access = dwDesiredAccess;
2113 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2114 req->share = dwShareMode;
2115 req->fd = -1;
2116 if (!wine_server_call_err( req ))
2117 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2119 SERVER_END_REQ;
2121 return ret;
2125 /***********************************************************************
2126 * GetConsoleScreenBufferInfo (KERNEL32.@)
2128 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2130 BOOL ret;
2132 SERVER_START_REQ(get_console_output_info)
2134 req->handle = console_handle_unmap(hConsoleOutput);
2135 if ((ret = !wine_server_call_err( req )))
2137 csbi->dwSize.X = reply->width;
2138 csbi->dwSize.Y = reply->height;
2139 csbi->dwCursorPosition.X = reply->cursor_x;
2140 csbi->dwCursorPosition.Y = reply->cursor_y;
2141 csbi->wAttributes = reply->attr;
2142 csbi->srWindow.Left = reply->win_left;
2143 csbi->srWindow.Right = reply->win_right;
2144 csbi->srWindow.Top = reply->win_top;
2145 csbi->srWindow.Bottom = reply->win_bottom;
2146 csbi->dwMaximumWindowSize.X = reply->max_width;
2147 csbi->dwMaximumWindowSize.Y = reply->max_height;
2150 SERVER_END_REQ;
2152 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2153 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2154 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2155 csbi->wAttributes,
2156 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2157 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2159 return ret;
2163 /******************************************************************************
2164 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2166 * RETURNS
2167 * Success: TRUE
2168 * Failure: FALSE
2170 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2172 BOOL ret;
2174 TRACE("(%p)\n", hConsoleOutput);
2176 SERVER_START_REQ( set_console_input_info )
2178 req->handle = 0;
2179 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2180 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2181 ret = !wine_server_call_err( req );
2183 SERVER_END_REQ;
2184 return ret;
2188 /***********************************************************************
2189 * GetConsoleMode (KERNEL32.@)
2191 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2193 BOOL ret;
2195 SERVER_START_REQ( get_console_mode )
2197 req->handle = console_handle_unmap(hcon);
2198 if ((ret = !wine_server_call_err( req )))
2200 if (mode) *mode = reply->mode;
2203 SERVER_END_REQ;
2204 return ret;
2208 /******************************************************************************
2209 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2211 * PARAMS
2212 * hcon [I] Handle to console input or screen buffer
2213 * mode [I] Input or output mode to set
2215 * RETURNS
2216 * Success: TRUE
2217 * Failure: FALSE
2219 * mode:
2220 * ENABLE_PROCESSED_INPUT 0x01
2221 * ENABLE_LINE_INPUT 0x02
2222 * ENABLE_ECHO_INPUT 0x04
2223 * ENABLE_WINDOW_INPUT 0x08
2224 * ENABLE_MOUSE_INPUT 0x10
2226 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2228 BOOL ret;
2230 SERVER_START_REQ(set_console_mode)
2232 req->handle = console_handle_unmap(hcon);
2233 req->mode = mode;
2234 ret = !wine_server_call_err( req );
2236 SERVER_END_REQ;
2237 /* FIXME: when resetting a console input to editline mode, I think we should
2238 * empty the S_EditString buffer
2241 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2243 return ret;
2247 /******************************************************************
2248 * CONSOLE_WriteChars
2250 * WriteConsoleOutput helper: hides server call semantics
2251 * writes a string at a given pos with standard attribute
2253 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2255 int written = -1;
2257 if (!nc) return 0;
2259 SERVER_START_REQ( write_console_output )
2261 req->handle = console_handle_unmap(hCon);
2262 req->x = pos->X;
2263 req->y = pos->Y;
2264 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2265 req->wrap = FALSE;
2266 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2267 if (!wine_server_call_err( req )) written = reply->written;
2269 SERVER_END_REQ;
2271 if (written > 0) pos->X += written;
2272 return written;
2275 /******************************************************************
2276 * next_line
2278 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2281 static BOOL next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2283 SMALL_RECT src;
2284 CHAR_INFO ci;
2285 COORD dst;
2287 csbi->dwCursorPosition.X = 0;
2288 csbi->dwCursorPosition.Y++;
2290 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return TRUE;
2292 src.Top = 1;
2293 src.Bottom = csbi->dwSize.Y - 1;
2294 src.Left = 0;
2295 src.Right = csbi->dwSize.X - 1;
2297 dst.X = 0;
2298 dst.Y = 0;
2300 ci.Attributes = csbi->wAttributes;
2301 ci.Char.UnicodeChar = ' ';
2303 csbi->dwCursorPosition.Y--;
2304 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2305 return FALSE;
2306 return TRUE;
2309 /******************************************************************
2310 * write_block
2312 * WriteConsoleOutput helper: writes a block of non special characters
2313 * Block can spread on several lines, and wrapping, if needed, is
2314 * handled
2317 static BOOL write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2318 DWORD mode, LPCWSTR ptr, int len)
2320 int blk; /* number of chars to write on current line */
2321 int done; /* number of chars already written */
2323 if (len <= 0) return TRUE;
2325 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2327 for (done = 0; done < len; done += blk)
2329 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2331 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2332 return FALSE;
2333 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2334 return FALSE;
2337 else
2339 int pos = csbi->dwCursorPosition.X;
2340 /* FIXME: we could reduce the number of loops
2341 * but, in most cases we wouldn't gain lots of time (it would only
2342 * happen if we're asked to overwrite more than twice the part of the line,
2343 * which is unlikely
2345 for (done = 0; done < len; done += blk)
2347 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2349 csbi->dwCursorPosition.X = pos;
2350 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2351 return FALSE;
2355 return TRUE;
2358 /***********************************************************************
2359 * WriteConsoleW (KERNEL32.@)
2361 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2362 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2364 DWORD mode;
2365 DWORD nw = 0;
2366 const WCHAR* psz = lpBuffer;
2367 CONSOLE_SCREEN_BUFFER_INFO csbi;
2368 int k, first = 0, fd;
2370 TRACE("%p %s %d %p %p\n",
2371 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2372 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2374 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2376 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2378 char* ptr;
2379 unsigned len;
2380 HANDLE hFile;
2381 NTSTATUS status;
2382 IO_STATUS_BLOCK iosb;
2384 close(fd);
2385 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2386 * to do the job
2388 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2389 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2390 return FALSE;
2392 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2393 hFile = wine_server_ptr_handle(console_handle_unmap(hConsoleOutput));
2394 status = NtWriteFile(hFile, NULL, NULL, NULL, &iosb, ptr, len, 0, NULL);
2395 if (status == STATUS_PENDING)
2397 WaitForSingleObject(hFile, INFINITE);
2398 status = iosb.u.Status;
2401 if (status != STATUS_PENDING && lpNumberOfCharsWritten)
2403 if (iosb.Information == len)
2404 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2405 else
2406 FIXME("Conversion not supported yet\n");
2408 HeapFree(GetProcessHeap(), 0, ptr);
2409 if (status != STATUS_SUCCESS)
2411 SetLastError(RtlNtStatusToDosError(status));
2412 return FALSE;
2414 return TRUE;
2417 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2418 return FALSE;
2420 if (!nNumberOfCharsToWrite) return TRUE;
2422 if (mode & ENABLE_PROCESSED_OUTPUT)
2424 unsigned int i;
2426 for (i = 0; i < nNumberOfCharsToWrite; i++)
2428 switch (psz[i])
2430 case '\b': case '\t': case '\n': case '\a': case '\r':
2431 /* don't handle here the i-th char... done below */
2432 if ((k = i - first) > 0)
2434 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2435 goto the_end;
2436 nw += k;
2438 first = i + 1;
2439 nw++;
2441 switch (psz[i])
2443 case '\b':
2444 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2445 break;
2446 case '\t':
2448 static const WCHAR tmp[] = {' ',' ',' ',' ',' ',' ',' ',' '};
2449 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2450 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2451 goto the_end;
2453 break;
2454 case '\n':
2455 next_line(hConsoleOutput, &csbi);
2456 break;
2457 case '\a':
2458 Beep(400, 300);
2459 break;
2460 case '\r':
2461 csbi.dwCursorPosition.X = 0;
2462 break;
2463 default:
2464 break;
2469 /* write the remaining block (if any) if processed output is enabled, or the
2470 * entire buffer otherwise
2472 if ((k = nNumberOfCharsToWrite - first) > 0)
2474 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2475 goto the_end;
2476 nw += k;
2479 the_end:
2480 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2481 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2482 return nw != 0;
2486 /***********************************************************************
2487 * WriteConsoleA (KERNEL32.@)
2489 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2490 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2492 BOOL ret;
2493 LPWSTR xstring;
2494 DWORD n;
2496 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2498 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2499 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2500 if (!xstring) return FALSE;
2502 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2504 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2506 HeapFree(GetProcessHeap(), 0, xstring);
2508 return ret;
2511 /******************************************************************************
2512 * SetConsoleCursorPosition [KERNEL32.@]
2513 * Sets the cursor position in console
2515 * PARAMS
2516 * hConsoleOutput [I] Handle of console screen buffer
2517 * dwCursorPosition [I] New cursor position coordinates
2519 * RETURNS
2520 * Success: TRUE
2521 * Failure: FALSE
2523 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2525 BOOL ret;
2526 CONSOLE_SCREEN_BUFFER_INFO csbi;
2527 int do_move = 0;
2528 int w, h;
2530 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2532 SERVER_START_REQ(set_console_output_info)
2534 req->handle = console_handle_unmap(hcon);
2535 req->cursor_x = pos.X;
2536 req->cursor_y = pos.Y;
2537 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2538 ret = !wine_server_call_err( req );
2540 SERVER_END_REQ;
2542 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2543 return FALSE;
2545 /* if cursor is no longer visible, scroll the visible window... */
2546 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2547 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2548 if (pos.X < csbi.srWindow.Left)
2550 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2551 do_move++;
2553 else if (pos.X > csbi.srWindow.Right)
2555 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2556 do_move++;
2558 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2560 if (pos.Y < csbi.srWindow.Top)
2562 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2563 do_move++;
2565 else if (pos.Y > csbi.srWindow.Bottom)
2567 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2568 do_move++;
2570 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2572 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2574 return ret;
2577 /******************************************************************************
2578 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2580 * PARAMS
2581 * hcon [I] Handle to console screen buffer
2582 * cinfo [O] Address of cursor information
2584 * RETURNS
2585 * Success: TRUE
2586 * Failure: FALSE
2588 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2590 BOOL ret;
2592 SERVER_START_REQ(get_console_output_info)
2594 req->handle = console_handle_unmap(hCon);
2595 ret = !wine_server_call_err( req );
2596 if (ret && cinfo)
2598 cinfo->dwSize = reply->cursor_size;
2599 cinfo->bVisible = reply->cursor_visible;
2602 SERVER_END_REQ;
2604 if (!ret) return FALSE;
2606 if (!cinfo)
2608 SetLastError(ERROR_INVALID_ACCESS);
2609 ret = FALSE;
2611 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2613 return ret;
2617 /******************************************************************************
2618 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2620 * PARAMS
2621 * hcon [I] Handle to console screen buffer
2622 * cinfo [I] Address of cursor information
2623 * RETURNS
2624 * Success: TRUE
2625 * Failure: FALSE
2627 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2629 BOOL ret;
2631 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2632 SERVER_START_REQ(set_console_output_info)
2634 req->handle = console_handle_unmap(hCon);
2635 req->cursor_size = cinfo->dwSize;
2636 req->cursor_visible = cinfo->bVisible;
2637 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2638 ret = !wine_server_call_err( req );
2640 SERVER_END_REQ;
2641 return ret;
2645 /******************************************************************************
2646 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2648 * PARAMS
2649 * hcon [I] Handle to console screen buffer
2650 * bAbsolute [I] Coordinate type flag
2651 * window [I] Address of new window rectangle
2652 * RETURNS
2653 * Success: TRUE
2654 * Failure: FALSE
2656 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2658 SMALL_RECT p = *window;
2659 BOOL ret;
2661 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2663 if (!bAbsolute)
2665 CONSOLE_SCREEN_BUFFER_INFO csbi;
2667 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2668 return FALSE;
2669 p.Left += csbi.srWindow.Left;
2670 p.Top += csbi.srWindow.Top;
2671 p.Right += csbi.srWindow.Right;
2672 p.Bottom += csbi.srWindow.Bottom;
2674 SERVER_START_REQ(set_console_output_info)
2676 req->handle = console_handle_unmap(hCon);
2677 req->win_left = p.Left;
2678 req->win_top = p.Top;
2679 req->win_right = p.Right;
2680 req->win_bottom = p.Bottom;
2681 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2682 ret = !wine_server_call_err( req );
2684 SERVER_END_REQ;
2686 return ret;
2690 /******************************************************************************
2691 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2693 * Sets the foreground and background color attributes of characters
2694 * written to the screen buffer.
2696 * RETURNS
2697 * Success: TRUE
2698 * Failure: FALSE
2700 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2702 BOOL ret;
2704 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2705 SERVER_START_REQ(set_console_output_info)
2707 req->handle = console_handle_unmap(hConsoleOutput);
2708 req->attr = wAttr;
2709 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2710 ret = !wine_server_call_err( req );
2712 SERVER_END_REQ;
2713 return ret;
2717 /******************************************************************************
2718 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2720 * PARAMS
2721 * hConsoleOutput [I] Handle to console screen buffer
2722 * dwSize [I] New size in character rows and cols
2724 * RETURNS
2725 * Success: TRUE
2726 * Failure: FALSE
2728 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2730 BOOL ret;
2732 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2733 SERVER_START_REQ(set_console_output_info)
2735 req->handle = console_handle_unmap(hConsoleOutput);
2736 req->width = dwSize.X;
2737 req->height = dwSize.Y;
2738 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2739 ret = !wine_server_call_err( req );
2741 SERVER_END_REQ;
2742 return ret;
2746 /******************************************************************************
2747 * ScrollConsoleScreenBufferA [KERNEL32.@]
2750 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2751 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2752 LPCHAR_INFO lpFill)
2754 CHAR_INFO ciw;
2756 ciw.Attributes = lpFill->Attributes;
2757 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2759 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2760 dwDestOrigin, &ciw);
2763 /******************************************************************
2764 * CONSOLE_FillLineUniform
2766 * Helper function for ScrollConsoleScreenBufferW
2767 * Fills a part of a line with a constant character info
2769 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2771 SERVER_START_REQ( fill_console_output )
2773 req->handle = console_handle_unmap(hConsoleOutput);
2774 req->mode = CHAR_INFO_MODE_TEXTATTR;
2775 req->x = i;
2776 req->y = j;
2777 req->count = len;
2778 req->wrap = FALSE;
2779 req->data.ch = lpFill->Char.UnicodeChar;
2780 req->data.attr = lpFill->Attributes;
2781 wine_server_call_err( req );
2783 SERVER_END_REQ;
2786 /******************************************************************************
2787 * ScrollConsoleScreenBufferW [KERNEL32.@]
2791 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2792 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2793 LPCHAR_INFO lpFill)
2795 SMALL_RECT dst;
2796 DWORD ret;
2797 int i, j;
2798 int start = -1;
2799 SMALL_RECT clip;
2800 CONSOLE_SCREEN_BUFFER_INFO csbi;
2801 BOOL inside;
2802 COORD src;
2804 if (lpClipRect)
2805 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2806 lpScrollRect->Left, lpScrollRect->Top,
2807 lpScrollRect->Right, lpScrollRect->Bottom,
2808 lpClipRect->Left, lpClipRect->Top,
2809 lpClipRect->Right, lpClipRect->Bottom,
2810 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2811 else
2812 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2813 lpScrollRect->Left, lpScrollRect->Top,
2814 lpScrollRect->Right, lpScrollRect->Bottom,
2815 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2817 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2818 return FALSE;
2820 src.X = lpScrollRect->Left;
2821 src.Y = lpScrollRect->Top;
2823 /* step 1: get dst rect */
2824 dst.Left = dwDestOrigin.X;
2825 dst.Top = dwDestOrigin.Y;
2826 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2827 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2829 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2830 if (lpClipRect)
2832 clip.Left = max(0, lpClipRect->Left);
2833 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2834 clip.Top = max(0, lpClipRect->Top);
2835 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2837 else
2839 clip.Left = 0;
2840 clip.Right = csbi.dwSize.X - 1;
2841 clip.Top = 0;
2842 clip.Bottom = csbi.dwSize.Y - 1;
2844 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2846 /* step 2b: clip dst rect */
2847 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2848 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2849 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2850 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2852 /* step 3: transfer the bits */
2853 SERVER_START_REQ(move_console_output)
2855 req->handle = console_handle_unmap(hConsoleOutput);
2856 req->x_src = src.X;
2857 req->y_src = src.Y;
2858 req->x_dst = dst.Left;
2859 req->y_dst = dst.Top;
2860 req->w = dst.Right - dst.Left + 1;
2861 req->h = dst.Bottom - dst.Top + 1;
2862 ret = !wine_server_call_err( req );
2864 SERVER_END_REQ;
2866 if (!ret) return FALSE;
2868 /* step 4: clean out the exposed part */
2870 /* have to write cell [i,j] if it is not in dst rect (because it has already
2871 * been written to by the scroll) and is in clip (we shall not write
2872 * outside of clip)
2874 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2876 inside = dst.Top <= j && j <= dst.Bottom;
2877 start = -1;
2878 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2880 if (inside && dst.Left <= i && i <= dst.Right)
2882 if (start != -1)
2884 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2885 start = -1;
2888 else
2890 if (start == -1) start = i;
2893 if (start != -1)
2894 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2897 return TRUE;
2900 /******************************************************************
2901 * AttachConsole (KERNEL32.@)
2903 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2905 FIXME("stub %x\n",dwProcessId);
2906 return TRUE;
2909 /******************************************************************
2910 * GetConsoleDisplayMode (KERNEL32.@)
2912 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2914 TRACE("semi-stub: %p\n", lpModeFlags);
2915 /* It is safe to successfully report windowed mode */
2916 *lpModeFlags = 0;
2917 return TRUE;
2920 /******************************************************************
2921 * SetConsoleDisplayMode (KERNEL32.@)
2923 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2924 COORD *lpNewScreenBufferDimensions)
2926 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2927 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2928 if (dwFlags == 1)
2930 /* We cannot switch to fullscreen */
2931 return FALSE;
2933 return TRUE;
2937 /* ====================================================================
2939 * Console manipulation functions
2941 * ====================================================================*/
2943 /* some missing functions...
2944 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2945 * should get the right API and implement them
2946 * SetConsoleCommandHistoryMode
2947 * SetConsoleNumberOfCommands[AW]
2949 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2951 int len = 0;
2953 SERVER_START_REQ( get_console_input_history )
2955 req->handle = 0;
2956 req->index = idx;
2957 if (buf && buf_len > 1)
2959 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2961 if (!wine_server_call_err( req ))
2963 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2964 len = reply->total / sizeof(WCHAR) + 1;
2967 SERVER_END_REQ;
2968 return len;
2971 /******************************************************************
2972 * CONSOLE_AppendHistory
2976 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2978 size_t len = strlenW(ptr);
2979 BOOL ret;
2981 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2982 if (!len) return FALSE;
2984 SERVER_START_REQ( append_console_input_history )
2986 req->handle = 0;
2987 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2988 ret = !wine_server_call_err( req );
2990 SERVER_END_REQ;
2991 return ret;
2994 /******************************************************************
2995 * CONSOLE_GetNumHistoryEntries
2999 unsigned CONSOLE_GetNumHistoryEntries(void)
3001 unsigned ret = -1;
3002 SERVER_START_REQ(get_console_input_info)
3004 req->handle = 0;
3005 if (!wine_server_call_err( req )) ret = reply->history_index;
3007 SERVER_END_REQ;
3008 return ret;
3011 /******************************************************************
3012 * CONSOLE_GetEditionMode
3016 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
3018 unsigned ret = 0;
3019 SERVER_START_REQ(get_console_input_info)
3021 req->handle = console_handle_unmap(hConIn);
3022 if ((ret = !wine_server_call_err( req )))
3023 *mode = reply->edition_mode;
3025 SERVER_END_REQ;
3026 return ret;
3029 /******************************************************************
3030 * GetConsoleAliasW
3033 * RETURNS
3034 * 0 if an error occurred, non-zero for success
3037 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3038 DWORD TargetBufferLength, LPWSTR lpExename)
3040 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3041 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3042 return 0;
3045 /******************************************************************
3046 * GetConsoleProcessList (KERNEL32.@)
3048 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3050 FIXME("(%p,%d): stub\n", processlist, processcount);
3052 if (!processlist || processcount < 1)
3054 SetLastError(ERROR_INVALID_PARAMETER);
3055 return 0;
3058 return 0;
3061 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3063 memset(&S_termios, 0, sizeof(S_termios));
3064 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3066 HANDLE conin;
3068 /* FIXME: to be done even if program is a GUI ? */
3069 /* This is wine specific: we have no parent (we're started from unix)
3070 * so, create a simple console with bare handles
3072 TERM_Init();
3073 wine_server_send_fd(0);
3074 SERVER_START_REQ( alloc_console )
3076 req->access = GENERIC_READ | GENERIC_WRITE;
3077 req->attributes = OBJ_INHERIT;
3078 req->pid = 0xffffffff;
3079 req->input_fd = 0;
3080 wine_server_call( req );
3081 conin = wine_server_ptr_handle( reply->handle_in );
3082 /* reply->event shouldn't be created by server */
3084 SERVER_END_REQ;
3086 if (!params->hStdInput)
3087 params->hStdInput = conin;
3089 if (!params->hStdOutput)
3091 wine_server_send_fd(1);
3092 SERVER_START_REQ( create_console_output )
3094 req->handle_in = wine_server_obj_handle(conin);
3095 req->access = GENERIC_WRITE|GENERIC_READ;
3096 req->attributes = OBJ_INHERIT;
3097 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3098 req->fd = 1;
3099 wine_server_call(req);
3100 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3102 SERVER_END_REQ;
3104 if (!params->hStdError)
3106 wine_server_send_fd(2);
3107 SERVER_START_REQ( create_console_output )
3109 req->handle_in = wine_server_obj_handle(conin);
3110 req->access = GENERIC_WRITE|GENERIC_READ;
3111 req->attributes = OBJ_INHERIT;
3112 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3113 req->fd = 2;
3114 wine_server_call(req);
3115 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3117 SERVER_END_REQ;
3121 /* convert value from server:
3122 * + INVALID_HANDLE_VALUE => TEB: 0, STARTUPINFO: INVALID_HANDLE_VALUE
3123 * + 0 => TEB: 0, STARTUPINFO: INVALID_HANDLE_VALUE
3124 * + console handle needs to be mapped
3126 if (!params->hStdInput || params->hStdInput == INVALID_HANDLE_VALUE)
3127 params->hStdInput = 0;
3128 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3130 params->hStdInput = console_handle_map(params->hStdInput);
3131 save_console_mode(params->hStdInput);
3134 if (!params->hStdOutput || params->hStdOutput == INVALID_HANDLE_VALUE)
3135 params->hStdOutput = 0;
3136 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3137 params->hStdOutput = console_handle_map(params->hStdOutput);
3139 if (!params->hStdError || params->hStdError == INVALID_HANDLE_VALUE)
3140 params->hStdError = 0;
3141 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3142 params->hStdError = console_handle_map(params->hStdError);
3144 return TRUE;
3147 BOOL CONSOLE_Exit(void)
3149 /* the console is in raw mode, put it back in cooked mode */
3150 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));
3153 /* Undocumented, called by native doskey.exe */
3154 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3155 DWORD WINAPI GetConsoleCommandHistoryA(DWORD unknown1, DWORD unknown2, DWORD unknown3)
3157 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
3158 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3159 return 0;
3162 /* Undocumented, called by native doskey.exe */
3163 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3164 DWORD WINAPI GetConsoleCommandHistoryW(DWORD unknown1, DWORD unknown2, DWORD unknown3)
3166 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
3167 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3168 return 0;
3171 /* Undocumented, called by native doskey.exe */
3172 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3173 DWORD WINAPI GetConsoleCommandHistoryLengthA(LPCSTR unknown)
3175 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3176 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3177 return 0;
3180 /* Undocumented, called by native doskey.exe */
3181 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3182 DWORD WINAPI GetConsoleCommandHistoryLengthW(LPCWSTR unknown)
3184 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3185 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3186 return 0;
3189 DWORD WINAPI GetConsoleAliasesLengthA(LPSTR unknown)
3191 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3192 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3193 return 0;
3196 DWORD WINAPI GetConsoleAliasesLengthW(LPWSTR unknown)
3198 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3199 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3200 return 0;
3203 VOID WINAPI ExpungeConsoleCommandHistoryA(LPCSTR unknown)
3205 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3206 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3209 VOID WINAPI ExpungeConsoleCommandHistoryW(LPCWSTR unknown)
3211 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3212 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3215 BOOL WINAPI AddConsoleAliasA(LPSTR source, LPSTR target, LPSTR exename)
3217 FIXME(": (%s, %s, %s) stub!\n", debugstr_a(source), debugstr_a(target), debugstr_a(exename));
3218 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3219 return FALSE;
3222 BOOL WINAPI AddConsoleAliasW(LPWSTR source, LPWSTR target, LPWSTR exename)
3224 FIXME(": (%s, %s, %s) stub!\n", debugstr_w(source), debugstr_w(target), debugstr_w(exename));
3225 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3226 return FALSE;
3230 BOOL WINAPI SetConsoleIcon(HICON icon)
3232 FIXME(": (%p) stub!\n", icon);
3233 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3234 return FALSE;
3237 BOOL WINAPI GetCurrentConsoleFont(HANDLE hConsole, BOOL maxwindow, LPCONSOLE_FONT_INFO fontinfo)
3239 FIXME(": (%p, %d, %p) stub!\n", hConsole, maxwindow, fontinfo);
3240 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3241 return FALSE;
3244 #ifdef __i386__
3245 #undef GetConsoleFontSize
3246 DWORD WINAPI GetConsoleFontSize(HANDLE hConsole, DWORD font)
3248 union {
3249 COORD c;
3250 DWORD w;
3251 } x;
3253 FIXME(": (%p, %d) stub!\n", hConsole, font);
3254 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3256 x.c.X = 0;
3257 x.c.Y = 0;
3258 return x.w;
3260 #endif /* defined(__i386__) */
3263 #ifndef __i386__
3264 COORD WINAPI GetConsoleFontSize(HANDLE hConsole, DWORD font)
3266 COORD c;
3267 c.X = 80;
3268 c.Y = 24;
3269 FIXME(": (%p, %d) stub!\n", hConsole, font);
3270 return c;
3272 #endif /* defined(__i386__) */