mshtml: Mark some functions as cdecl.
[wine/multimedia.git] / dlls / kernel32 / console.c
blobfc7d7f07eb808b38c1c9ea7efaa664c0eacb9ebd
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 #ifdef HAVE_UNISTD_H
38 # include <unistd.h>
39 #endif
40 #include <assert.h>
41 #ifdef HAVE_TERMIOS_H
42 # include <termios.h>
43 #endif
44 #ifdef HAVE_SYS_POLL_H
45 # include <sys/poll.h>
46 #endif
48 #include "ntstatus.h"
49 #define WIN32_NO_STATUS
50 #include "windef.h"
51 #include "winbase.h"
52 #include "winnls.h"
53 #include "winerror.h"
54 #include "wincon.h"
55 #include "wine/server.h"
56 #include "wine/exception.h"
57 #include "wine/unicode.h"
58 #include "wine/debug.h"
59 #include "excpt.h"
60 #include "console_private.h"
61 #include "kernel_private.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(console);
65 static CRITICAL_SECTION CONSOLE_CritSect;
66 static CRITICAL_SECTION_DEBUG critsect_debug =
68 0, 0, &CONSOLE_CritSect,
69 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
70 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
72 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
74 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
75 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
77 /* FIXME: this is not thread safe */
78 static HANDLE console_wait_event;
80 /* map input records to ASCII */
81 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
83 int i;
84 char ch;
86 for (i = 0; i < count; i++)
88 if (buffer[i].EventType != KEY_EVENT) continue;
89 WideCharToMultiByte( GetConsoleCP(), 0,
90 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
91 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
95 /* map input records to Unicode */
96 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
98 int i;
99 WCHAR ch;
101 for (i = 0; i < count; i++)
103 if (buffer[i].EventType != KEY_EVENT) continue;
104 MultiByteToWideChar( GetConsoleCP(), 0,
105 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
106 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
110 /* map char infos to ASCII */
111 static void char_info_WtoA( CHAR_INFO *buffer, int count )
113 char ch;
115 while (count-- > 0)
117 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
118 &ch, 1, NULL, NULL );
119 buffer->Char.AsciiChar = ch;
120 buffer++;
124 /* map char infos to Unicode */
125 static void char_info_AtoW( CHAR_INFO *buffer, int count )
127 WCHAR ch;
129 while (count-- > 0)
131 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
132 buffer->Char.UnicodeChar = ch;
133 buffer++;
137 static struct termios S_termios; /* saved termios for bare consoles */
138 static BOOL S_termios_raw /* = FALSE */;
140 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
141 * - a bare console is created for all CUI programs started from command line (without
142 * wineconsole) (let's call those PS)
143 * - of course, every child of a PS which requires console inheritance will get it
144 * - the console termios attributes are saved at the start of program which is attached to be
145 * bare console
146 * - if any program attached to a bare console requests input from console, the console is
147 * turned into raw mode
148 * - when the program which created the bare console (the program started from command line)
149 * exits, it will restore the console termios attributes it saved at startup (this
150 * will put back the console into cooked mode if it had been put in raw mode)
151 * - if any other program attached to this bare console is still alive, the Unix shell will put
152 * it in the background, hence forbidding access to the console. Therefore, reading console
153 * input will not be available when the bare console creator has died.
154 * FIXME: This is a limitation of current implementation
157 /* returns the fd for a bare console (-1 otherwise) */
158 static int get_console_bare_fd(HANDLE hin)
160 int fd;
162 if (wine_server_handle_to_fd(wine_server_ptr_handle(console_handle_unmap(hin)),
163 0, &fd, NULL) == STATUS_SUCCESS)
164 return fd;
165 return -1;
168 static BOOL save_console_mode(HANDLE hin)
170 int fd;
171 BOOL ret;
173 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
174 ret = tcgetattr(fd, &S_termios) >= 0;
175 close(fd);
176 return ret;
179 static BOOL put_console_into_raw_mode(int fd)
181 RtlEnterCriticalSection(&CONSOLE_CritSect);
182 if (!S_termios_raw)
184 struct termios term = S_termios;
186 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
187 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
188 term.c_cflag &= ~(CSIZE | PARENB);
189 term.c_cflag |= CS8;
190 /* FIXME: we should actually disable output processing here
191 * and let kernel32/console.c do the job (with support of enable/disable of
192 * processed output)
194 /* term.c_oflag &= ~(OPOST); */
195 term.c_cc[VMIN] = 1;
196 term.c_cc[VTIME] = 0;
197 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
199 RtlLeaveCriticalSection(&CONSOLE_CritSect);
201 return S_termios_raw;
204 /* put back the console in cooked mode iff we're the process which created the bare console
205 * we don't test if thie process has set the console in raw mode as it could be one of its
206 * child who did it
208 static BOOL restore_console_mode(HANDLE hin)
210 int fd;
211 BOOL ret;
213 if (!S_termios_raw ||
214 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
215 return TRUE;
216 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
217 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
218 close(fd);
219 TERM_Exit();
220 return ret;
223 /******************************************************************************
224 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
226 * RETURNS
227 * Success: hwnd of the console window.
228 * Failure: NULL
230 HWND WINAPI GetConsoleWindow(VOID)
232 HWND hWnd = NULL;
234 SERVER_START_REQ(get_console_input_info)
236 req->handle = 0;
237 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
239 SERVER_END_REQ;
241 return hWnd;
245 /******************************************************************************
246 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
248 * RETURNS
249 * Code page code
251 UINT WINAPI GetConsoleCP(VOID)
253 BOOL ret;
254 UINT codepage = GetOEMCP(); /* default value */
256 SERVER_START_REQ(get_console_input_info)
258 req->handle = 0;
259 ret = !wine_server_call_err(req);
260 if (ret && reply->input_cp)
261 codepage = reply->input_cp;
263 SERVER_END_REQ;
265 return codepage;
269 /******************************************************************************
270 * SetConsoleCP [KERNEL32.@]
272 BOOL WINAPI SetConsoleCP(UINT cp)
274 BOOL ret;
276 if (!IsValidCodePage(cp))
278 SetLastError(ERROR_INVALID_PARAMETER);
279 return FALSE;
282 SERVER_START_REQ(set_console_input_info)
284 req->handle = 0;
285 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
286 req->input_cp = cp;
287 ret = !wine_server_call_err(req);
289 SERVER_END_REQ;
291 return ret;
295 /***********************************************************************
296 * GetConsoleOutputCP (KERNEL32.@)
298 UINT WINAPI GetConsoleOutputCP(VOID)
300 BOOL ret;
301 UINT codepage = GetOEMCP(); /* default value */
303 SERVER_START_REQ(get_console_input_info)
305 req->handle = 0;
306 ret = !wine_server_call_err(req);
307 if (ret && reply->output_cp)
308 codepage = reply->output_cp;
310 SERVER_END_REQ;
312 return codepage;
316 /******************************************************************************
317 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
319 * PARAMS
320 * cp [I] code page to set
322 * RETURNS
323 * Success: TRUE
324 * Failure: FALSE
326 BOOL WINAPI SetConsoleOutputCP(UINT cp)
328 BOOL ret;
330 if (!IsValidCodePage(cp))
332 SetLastError(ERROR_INVALID_PARAMETER);
333 return FALSE;
336 SERVER_START_REQ(set_console_input_info)
338 req->handle = 0;
339 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
340 req->output_cp = cp;
341 ret = !wine_server_call_err(req);
343 SERVER_END_REQ;
345 return ret;
349 /***********************************************************************
350 * Beep (KERNEL32.@)
352 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
354 static const char beep = '\a';
355 /* dwFreq and dwDur are ignored by Win95 */
356 if (isatty(2)) write( 2, &beep, 1 );
357 return TRUE;
361 /******************************************************************
362 * OpenConsoleW (KERNEL32.@)
364 * Undocumented
365 * Open a handle to the current process console.
366 * Returns INVALID_HANDLE_VALUE on failure.
368 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
370 HANDLE output = INVALID_HANDLE_VALUE;
371 HANDLE ret;
373 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
375 if (name)
377 if (strcmpiW(coninW, name) == 0)
378 output = (HANDLE) FALSE;
379 else if (strcmpiW(conoutW, name) == 0)
380 output = (HANDLE) TRUE;
383 if (output == INVALID_HANDLE_VALUE)
385 SetLastError(ERROR_INVALID_PARAMETER);
386 return INVALID_HANDLE_VALUE;
388 else if (creation != OPEN_EXISTING)
390 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
391 SetLastError(ERROR_SHARING_VIOLATION);
392 else
393 SetLastError(ERROR_INVALID_PARAMETER);
394 return INVALID_HANDLE_VALUE;
397 SERVER_START_REQ( open_console )
399 req->from = wine_server_obj_handle( output );
400 req->access = access;
401 req->attributes = inherit ? OBJ_INHERIT : 0;
402 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
403 wine_server_call_err( req );
404 ret = wine_server_ptr_handle( reply->handle );
406 SERVER_END_REQ;
407 if (ret)
408 ret = console_handle_map(ret);
410 return ret;
413 /******************************************************************
414 * VerifyConsoleIoHandle (KERNEL32.@)
416 * Undocumented
418 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
420 BOOL ret;
422 if (!is_console_handle(handle)) return FALSE;
423 SERVER_START_REQ(get_console_mode)
425 req->handle = console_handle_unmap(handle);
426 ret = !wine_server_call( req );
428 SERVER_END_REQ;
429 return ret;
432 /******************************************************************
433 * DuplicateConsoleHandle (KERNEL32.@)
435 * Undocumented
437 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
438 DWORD options)
440 HANDLE ret;
442 if (!is_console_handle(handle) ||
443 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
444 GetCurrentProcess(), &ret, access, inherit, options))
445 return INVALID_HANDLE_VALUE;
446 return console_handle_map(ret);
449 /******************************************************************
450 * CloseConsoleHandle (KERNEL32.@)
452 * Undocumented
454 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
456 if (!is_console_handle(handle))
458 SetLastError(ERROR_INVALID_PARAMETER);
459 return FALSE;
461 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
464 /******************************************************************
465 * GetConsoleInputWaitHandle (KERNEL32.@)
467 * Undocumented
469 HANDLE WINAPI GetConsoleInputWaitHandle(void)
471 if (!console_wait_event)
473 SERVER_START_REQ(get_console_wait_event)
475 if (!wine_server_call_err( req ))
476 console_wait_event = wine_server_ptr_handle( reply->handle );
478 SERVER_END_REQ;
480 return console_wait_event;
484 /******************************************************************************
485 * WriteConsoleInputA [KERNEL32.@]
487 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
488 DWORD count, LPDWORD written )
490 INPUT_RECORD *recW = NULL;
491 BOOL ret;
493 if (count > 0)
495 if (!buffer)
497 SetLastError( ERROR_INVALID_ACCESS );
498 return FALSE;
501 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) )))
503 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
504 return FALSE;
507 memcpy( recW, buffer, count * sizeof(*recW) );
508 input_records_AtoW( recW, count );
511 ret = WriteConsoleInputW( handle, recW, count, written );
512 HeapFree( GetProcessHeap(), 0, recW );
513 return ret;
517 /******************************************************************************
518 * WriteConsoleInputW [KERNEL32.@]
520 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
521 DWORD count, LPDWORD written )
523 DWORD events_written = 0;
524 BOOL ret;
526 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
528 if (count > 0 && !buffer)
530 SetLastError(ERROR_INVALID_ACCESS);
531 return FALSE;
534 SERVER_START_REQ( write_console_input )
536 req->handle = console_handle_unmap(handle);
537 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
538 if ((ret = !wine_server_call_err( req )))
539 events_written = reply->written;
541 SERVER_END_REQ;
543 if (written) *written = events_written;
544 else
546 SetLastError(ERROR_INVALID_ACCESS);
547 ret = FALSE;
549 return ret;
553 /***********************************************************************
554 * WriteConsoleOutputA (KERNEL32.@)
556 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
557 COORD size, COORD coord, LPSMALL_RECT region )
559 int y;
560 BOOL ret;
561 COORD new_size, new_coord;
562 CHAR_INFO *ciw;
564 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
565 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
567 if (new_size.X <= 0 || new_size.Y <= 0)
569 region->Bottom = region->Top + new_size.Y - 1;
570 region->Right = region->Left + new_size.X - 1;
571 return TRUE;
574 /* only copy the useful rectangle */
575 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
576 return FALSE;
577 for (y = 0; y < new_size.Y; y++)
579 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
580 new_size.X * sizeof(CHAR_INFO) );
581 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
583 new_coord.X = new_coord.Y = 0;
584 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
585 HeapFree( GetProcessHeap(), 0, ciw );
586 return ret;
590 /***********************************************************************
591 * WriteConsoleOutputW (KERNEL32.@)
593 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
594 COORD size, COORD coord, LPSMALL_RECT region )
596 int width, height, y;
597 BOOL ret = TRUE;
599 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
600 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
601 region->Left, region->Top, region->Right, region->Bottom);
603 width = min( region->Right - region->Left + 1, size.X - coord.X );
604 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
606 if (width > 0 && height > 0)
608 for (y = 0; y < height; y++)
610 SERVER_START_REQ( write_console_output )
612 req->handle = console_handle_unmap(hConsoleOutput);
613 req->x = region->Left;
614 req->y = region->Top + y;
615 req->mode = CHAR_INFO_MODE_TEXTATTR;
616 req->wrap = FALSE;
617 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
618 width * sizeof(CHAR_INFO));
619 if ((ret = !wine_server_call_err( req )))
621 width = min( width, reply->width - region->Left );
622 height = min( height, reply->height - region->Top );
625 SERVER_END_REQ;
626 if (!ret) break;
629 region->Bottom = region->Top + height - 1;
630 region->Right = region->Left + width - 1;
631 return ret;
635 /******************************************************************************
636 * WriteConsoleOutputCharacterA [KERNEL32.@]
638 * See WriteConsoleOutputCharacterW.
640 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
641 COORD coord, LPDWORD lpNumCharsWritten )
643 BOOL ret;
644 LPWSTR strW = NULL;
645 DWORD lenW = 0;
647 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
648 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
650 if (length > 0)
652 if (!str)
654 SetLastError( ERROR_INVALID_ACCESS );
655 return FALSE;
658 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
660 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
662 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
663 return FALSE;
666 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
669 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
670 HeapFree( GetProcessHeap(), 0, strW );
671 return ret;
675 /******************************************************************************
676 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
677 * the console screen buffer
679 * PARAMS
680 * hConsoleOutput [I] Handle to screen buffer
681 * attr [I] Pointer to buffer with write attributes
682 * length [I] Number of cells to write to
683 * coord [I] Coords of first cell
684 * lpNumAttrsWritten [O] Pointer to number of cells written
686 * RETURNS
687 * Success: TRUE
688 * Failure: FALSE
691 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
692 COORD coord, LPDWORD lpNumAttrsWritten )
694 BOOL ret;
696 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
698 if ((length > 0 && !attr) || !lpNumAttrsWritten)
700 SetLastError(ERROR_INVALID_ACCESS);
701 return FALSE;
704 *lpNumAttrsWritten = 0;
706 SERVER_START_REQ( write_console_output )
708 req->handle = console_handle_unmap(hConsoleOutput);
709 req->x = coord.X;
710 req->y = coord.Y;
711 req->mode = CHAR_INFO_MODE_ATTR;
712 req->wrap = TRUE;
713 wine_server_add_data( req, attr, length * sizeof(WORD) );
714 if ((ret = !wine_server_call_err( req )))
715 *lpNumAttrsWritten = reply->written;
717 SERVER_END_REQ;
718 return ret;
722 /******************************************************************************
723 * FillConsoleOutputCharacterA [KERNEL32.@]
725 * See FillConsoleOutputCharacterW.
727 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
728 COORD coord, LPDWORD lpNumCharsWritten )
730 WCHAR wch;
732 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
733 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
737 /******************************************************************************
738 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
740 * PARAMS
741 * hConsoleOutput [I] Handle to screen buffer
742 * ch [I] Character to write
743 * length [I] Number of cells to write to
744 * coord [I] Coords of first cell
745 * lpNumCharsWritten [O] Pointer to number of cells written
747 * RETURNS
748 * Success: TRUE
749 * Failure: FALSE
751 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
752 COORD coord, LPDWORD lpNumCharsWritten)
754 BOOL ret;
756 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
757 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
759 if (!lpNumCharsWritten)
761 SetLastError(ERROR_INVALID_ACCESS);
762 return FALSE;
765 *lpNumCharsWritten = 0;
767 SERVER_START_REQ( fill_console_output )
769 req->handle = console_handle_unmap(hConsoleOutput);
770 req->x = coord.X;
771 req->y = coord.Y;
772 req->mode = CHAR_INFO_MODE_TEXT;
773 req->wrap = TRUE;
774 req->data.ch = ch;
775 req->count = length;
776 if ((ret = !wine_server_call_err( req )))
777 *lpNumCharsWritten = reply->written;
779 SERVER_END_REQ;
780 return ret;
784 /******************************************************************************
785 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
787 * PARAMS
788 * hConsoleOutput [I] Handle to screen buffer
789 * attr [I] Color attribute to write
790 * length [I] Number of cells to write to
791 * coord [I] Coords of first cell
792 * lpNumAttrsWritten [O] Pointer to number of cells written
794 * RETURNS
795 * Success: TRUE
796 * Failure: FALSE
798 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
799 COORD coord, LPDWORD lpNumAttrsWritten )
801 BOOL ret;
803 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
804 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
806 if (!lpNumAttrsWritten)
808 SetLastError(ERROR_INVALID_ACCESS);
809 return FALSE;
812 *lpNumAttrsWritten = 0;
814 SERVER_START_REQ( fill_console_output )
816 req->handle = console_handle_unmap(hConsoleOutput);
817 req->x = coord.X;
818 req->y = coord.Y;
819 req->mode = CHAR_INFO_MODE_ATTR;
820 req->wrap = TRUE;
821 req->data.attr = attr;
822 req->count = length;
823 if ((ret = !wine_server_call_err( req )))
824 *lpNumAttrsWritten = reply->written;
826 SERVER_END_REQ;
827 return ret;
831 /******************************************************************************
832 * ReadConsoleOutputCharacterA [KERNEL32.@]
835 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
836 COORD coord, LPDWORD read_count)
838 DWORD read;
839 BOOL ret;
840 LPWSTR wptr;
842 if (!read_count)
844 SetLastError(ERROR_INVALID_ACCESS);
845 return FALSE;
848 *read_count = 0;
850 if (!(wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR))))
852 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
853 return FALSE;
856 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
858 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
859 *read_count = read;
861 HeapFree( GetProcessHeap(), 0, wptr );
862 return ret;
866 /******************************************************************************
867 * ReadConsoleOutputCharacterW [KERNEL32.@]
870 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
871 COORD coord, LPDWORD read_count )
873 BOOL ret;
875 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
877 if (!read_count)
879 SetLastError(ERROR_INVALID_ACCESS);
880 return FALSE;
883 *read_count = 0;
885 SERVER_START_REQ( read_console_output )
887 req->handle = console_handle_unmap(hConsoleOutput);
888 req->x = coord.X;
889 req->y = coord.Y;
890 req->mode = CHAR_INFO_MODE_TEXT;
891 req->wrap = TRUE;
892 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
893 if ((ret = !wine_server_call_err( req )))
894 *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
896 SERVER_END_REQ;
897 return ret;
901 /******************************************************************************
902 * ReadConsoleOutputAttribute [KERNEL32.@]
904 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
905 COORD coord, LPDWORD read_count)
907 BOOL ret;
909 TRACE("(%p,%p,%d,%dx%d,%p)\n",
910 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
912 if (!read_count)
914 SetLastError(ERROR_INVALID_ACCESS);
915 return FALSE;
918 *read_count = 0;
920 SERVER_START_REQ( read_console_output )
922 req->handle = console_handle_unmap(hConsoleOutput);
923 req->x = coord.X;
924 req->y = coord.Y;
925 req->mode = CHAR_INFO_MODE_ATTR;
926 req->wrap = TRUE;
927 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
928 if ((ret = !wine_server_call_err( req )))
929 *read_count = wine_server_reply_size(reply) / sizeof(WORD);
931 SERVER_END_REQ;
932 return ret;
936 /******************************************************************************
937 * ReadConsoleOutputA [KERNEL32.@]
940 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
941 COORD coord, LPSMALL_RECT region )
943 BOOL ret;
944 int y;
946 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
947 if (ret && region->Right >= region->Left)
949 for (y = 0; y <= region->Bottom - region->Top; y++)
951 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
952 region->Right - region->Left + 1 );
955 return ret;
959 /******************************************************************************
960 * ReadConsoleOutputW [KERNEL32.@]
962 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
963 * think we need to be *that* compatible. -- AJ
965 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
966 COORD coord, LPSMALL_RECT region )
968 int width, height, y;
969 BOOL ret = TRUE;
971 width = min( region->Right - region->Left + 1, size.X - coord.X );
972 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
974 if (width > 0 && height > 0)
976 for (y = 0; y < height; y++)
978 SERVER_START_REQ( read_console_output )
980 req->handle = console_handle_unmap(hConsoleOutput);
981 req->x = region->Left;
982 req->y = region->Top + y;
983 req->mode = CHAR_INFO_MODE_TEXTATTR;
984 req->wrap = FALSE;
985 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
986 width * sizeof(CHAR_INFO) );
987 if ((ret = !wine_server_call_err( req )))
989 width = min( width, reply->width - region->Left );
990 height = min( height, reply->height - region->Top );
993 SERVER_END_REQ;
994 if (!ret) break;
997 region->Bottom = region->Top + height - 1;
998 region->Right = region->Left + width - 1;
999 return ret;
1003 /******************************************************************************
1004 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
1006 * PARAMS
1007 * handle [I] Handle to console input buffer
1008 * buffer [O] Address of buffer for read data
1009 * count [I] Number of records to read
1010 * pRead [O] Address of number of records read
1012 * RETURNS
1013 * Success: TRUE
1014 * Failure: FALSE
1016 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1018 DWORD read;
1020 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
1021 input_records_WtoA( buffer, read );
1022 if (pRead) *pRead = read;
1023 return TRUE;
1027 /***********************************************************************
1028 * PeekConsoleInputA (KERNEL32.@)
1030 * Gets 'count' first events (or less) from input queue.
1032 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1034 DWORD read;
1036 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
1037 input_records_WtoA( buffer, read );
1038 if (pRead) *pRead = read;
1039 return TRUE;
1043 /***********************************************************************
1044 * PeekConsoleInputW (KERNEL32.@)
1046 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
1048 BOOL ret;
1049 SERVER_START_REQ( read_console_input )
1051 req->handle = console_handle_unmap(handle);
1052 req->flush = FALSE;
1053 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1054 if ((ret = !wine_server_call_err( req )))
1056 if (read) *read = count ? reply->read : 0;
1059 SERVER_END_REQ;
1060 return ret;
1064 /***********************************************************************
1065 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1067 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1069 BOOL ret;
1070 SERVER_START_REQ( read_console_input )
1072 req->handle = console_handle_unmap(handle);
1073 req->flush = FALSE;
1074 if ((ret = !wine_server_call_err( req )))
1076 if (nrofevents)
1077 *nrofevents = reply->read;
1078 else
1080 SetLastError(ERROR_INVALID_ACCESS);
1081 ret = FALSE;
1085 SERVER_END_REQ;
1086 return ret;
1090 /******************************************************************************
1091 * read_console_input
1093 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1095 * Returns
1096 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1098 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1100 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1102 enum read_console_input_return ret;
1103 char input[8];
1104 WCHAR inputw[8];
1105 int i;
1106 size_t idx = 0, idxw;
1107 unsigned numEvent;
1108 INPUT_RECORD ir[8];
1109 DWORD written;
1110 struct pollfd pollfd;
1111 BOOL locked = FALSE, next_char;
1115 if (idx == sizeof(input))
1117 FIXME("buffer too small (%s)\n", wine_dbgstr_an(input, idx));
1118 ret = rci_error;
1119 break;
1121 pollfd.fd = fd;
1122 pollfd.events = POLLIN;
1123 pollfd.revents = 0;
1124 next_char = FALSE;
1126 switch (poll(&pollfd, 1, timeout))
1128 case 1:
1129 if (!locked)
1131 RtlEnterCriticalSection(&CONSOLE_CritSect);
1132 locked = TRUE;
1134 i = read(fd, &input[idx], 1);
1135 if (i < 0)
1137 ret = rci_error;
1138 break;
1140 if (i == 0)
1142 /* actually another thread likely beat us to reading the char
1143 * return rci_gotone, while not perfect, it should work in most of the cases (as the new event
1144 * should be now in the queue, fed from the other thread)
1146 ret = rci_gotone;
1147 break;
1150 idx++;
1151 numEvent = TERM_FillInputRecord(input, idx, ir);
1152 switch (numEvent)
1154 case 0:
1155 /* we need more char(s) to tell if it matches a key-db entry. wait 1/2s for next char */
1156 timeout = 500;
1157 next_char = TRUE;
1158 break;
1159 case -1:
1160 /* we haven't found the string into key-db, push full input string into server */
1161 idxw = MultiByteToWideChar(CP_UNIXCP, 0, input, idx, inputw, sizeof(inputw) / sizeof(inputw[0]));
1163 /* we cannot translate yet... likely we need more chars (wait max 1/2s for next char) */
1164 if (idxw == 0)
1166 timeout = 500;
1167 next_char = TRUE;
1168 break;
1170 for (i = 0; i < idxw; i++)
1172 numEvent = TERM_FillSimpleChar(inputw[i], ir);
1173 WriteConsoleInputW(handle, ir, numEvent, &written);
1175 ret = rci_gotone;
1176 break;
1177 default:
1178 /* we got a transformation from key-db... push this into server */
1179 ret = WriteConsoleInputW(handle, ir, numEvent, &written) ? rci_gotone : rci_error;
1180 break;
1182 break;
1183 case 0: ret = rci_timeout; break;
1184 default: ret = rci_error; break;
1186 } while (next_char);
1187 if (locked) RtlLeaveCriticalSection(&CONSOLE_CritSect);
1189 return ret;
1192 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1194 int fd;
1195 enum read_console_input_return ret;
1197 if ((fd = get_console_bare_fd(handle)) != -1)
1199 put_console_into_raw_mode(fd);
1200 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1202 ret = bare_console_fetch_input(handle, fd, timeout);
1204 else ret = rci_gotone;
1205 close(fd);
1206 if (ret != rci_gotone) return ret;
1208 else
1210 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1212 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1213 return rci_timeout;
1216 SERVER_START_REQ( read_console_input )
1218 req->handle = console_handle_unmap(handle);
1219 req->flush = TRUE;
1220 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1221 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1222 else ret = rci_gotone;
1224 SERVER_END_REQ;
1226 return ret;
1230 /***********************************************************************
1231 * FlushConsoleInputBuffer (KERNEL32.@)
1233 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1235 enum read_console_input_return last;
1236 INPUT_RECORD ir;
1238 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1240 return last == rci_timeout;
1244 /***********************************************************************
1245 * SetConsoleTitleA (KERNEL32.@)
1247 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1249 LPWSTR titleW;
1250 BOOL ret;
1252 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1253 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1254 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1255 ret = SetConsoleTitleW(titleW);
1256 HeapFree(GetProcessHeap(), 0, titleW);
1257 return ret;
1261 /***********************************************************************
1262 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1264 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1266 FIXME( "stub %p\n", layoutName);
1267 return TRUE;
1270 /***********************************************************************
1271 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1273 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
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 ret;
1452 wh[0] = hEvent;
1453 wh[1] = pi.hProcess;
1454 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1456 CloseHandle(pi.hThread);
1457 CloseHandle(pi.hProcess);
1459 if (ret != 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 ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1615 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1617 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1618 HeapFree(GetProcessHeap(), 0, ptr);
1620 return ret;
1623 /***********************************************************************
1624 * ReadConsoleW (KERNEL32.@)
1626 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1627 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1629 DWORD charsread;
1630 LPWSTR xbuf = lpBuffer;
1631 DWORD mode;
1632 BOOL is_bare = FALSE;
1633 int fd;
1635 TRACE("(%p,%p,%d,%p,%p)\n",
1636 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1638 if (!GetConsoleMode(hConsoleInput, &mode))
1639 return FALSE;
1640 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1642 close(fd);
1643 is_bare = TRUE;
1645 if (mode & ENABLE_LINE_INPUT)
1647 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1649 HeapFree(GetProcessHeap(), 0, S_EditString);
1650 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1651 return FALSE;
1652 S_EditStrPos = 0;
1654 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1655 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1656 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1657 S_EditStrPos += charsread;
1659 else
1661 INPUT_RECORD ir;
1662 DWORD timeout = INFINITE;
1664 /* FIXME: should we read at least 1 char? The SDK does not say */
1665 /* wait for at least one available input record (it doesn't mean we'll have
1666 * chars stored in xbuf...)
1668 * Although SDK doc keeps silence about 1 char, SDK examples assume
1669 * that we should wait for at least one character (not key). --KS
1671 charsread = 0;
1674 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1675 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1676 ir.Event.KeyEvent.uChar.UnicodeChar)
1678 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1679 timeout = 0;
1681 } while (charsread < nNumberOfCharsToRead);
1682 /* nothing has been read */
1683 if (timeout == INFINITE) return FALSE;
1686 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1688 return TRUE;
1692 /***********************************************************************
1693 * ReadConsoleInputW (KERNEL32.@)
1695 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1696 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1698 DWORD idx = 0;
1699 DWORD timeout = INFINITE;
1701 if (!nLength)
1703 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1704 return TRUE;
1707 /* loop until we get at least one event */
1708 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1709 ++idx < nLength)
1710 timeout = 0;
1712 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1713 return idx != 0;
1717 /******************************************************************************
1718 * WriteConsoleOutputCharacterW [KERNEL32.@]
1720 * Copy character to consecutive cells in the console screen buffer.
1722 * PARAMS
1723 * hConsoleOutput [I] Handle to screen buffer
1724 * str [I] Pointer to buffer with chars to write
1725 * length [I] Number of cells to write to
1726 * coord [I] Coords of first cell
1727 * lpNumCharsWritten [O] Pointer to number of cells written
1729 * RETURNS
1730 * Success: TRUE
1731 * Failure: FALSE
1734 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1735 COORD coord, LPDWORD lpNumCharsWritten )
1737 BOOL ret;
1739 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1740 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1742 if ((length > 0 && !str) || !lpNumCharsWritten)
1744 SetLastError(ERROR_INVALID_ACCESS);
1745 return FALSE;
1748 *lpNumCharsWritten = 0;
1750 SERVER_START_REQ( write_console_output )
1752 req->handle = console_handle_unmap(hConsoleOutput);
1753 req->x = coord.X;
1754 req->y = coord.Y;
1755 req->mode = CHAR_INFO_MODE_TEXT;
1756 req->wrap = TRUE;
1757 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1758 if ((ret = !wine_server_call_err( req )))
1759 *lpNumCharsWritten = reply->written;
1761 SERVER_END_REQ;
1762 return ret;
1766 /******************************************************************************
1767 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1769 * PARAMS
1770 * title [I] Address of new title
1772 * RETURNS
1773 * Success: TRUE
1774 * Failure: FALSE
1776 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1778 BOOL ret;
1780 TRACE("(%s)\n", debugstr_w(title));
1781 SERVER_START_REQ( set_console_input_info )
1783 req->handle = 0;
1784 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1785 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1786 ret = !wine_server_call_err( req );
1788 SERVER_END_REQ;
1789 return ret;
1793 /***********************************************************************
1794 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1796 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1798 FIXME("(%p): stub\n", nrofbuttons);
1799 *nrofbuttons = 2;
1800 return TRUE;
1803 /******************************************************************************
1804 * SetConsoleInputExeNameW [KERNEL32.@]
1806 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1808 TRACE("(%s)\n", debugstr_w(name));
1810 if (!name || !name[0])
1812 SetLastError(ERROR_INVALID_PARAMETER);
1813 return FALSE;
1816 RtlEnterCriticalSection(&CONSOLE_CritSect);
1817 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1818 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1820 return TRUE;
1823 /******************************************************************************
1824 * SetConsoleInputExeNameA [KERNEL32.@]
1826 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1828 int len;
1829 LPWSTR nameW;
1830 BOOL ret;
1832 if (!name || !name[0])
1834 SetLastError(ERROR_INVALID_PARAMETER);
1835 return FALSE;
1838 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1839 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1841 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1842 ret = SetConsoleInputExeNameW(nameW);
1843 HeapFree(GetProcessHeap(), 0, nameW);
1845 return ret;
1848 /******************************************************************
1849 * CONSOLE_DefaultHandler
1851 * Final control event handler
1853 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1855 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1856 ExitProcess(0);
1857 /* should never go here */
1858 return TRUE;
1861 /******************************************************************************
1862 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1864 * PARAMS
1865 * func [I] Address of handler function
1866 * add [I] Handler to add or remove
1868 * RETURNS
1869 * Success: TRUE
1870 * Failure: FALSE
1873 struct ConsoleHandler
1875 PHANDLER_ROUTINE handler;
1876 struct ConsoleHandler* next;
1879 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1880 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1882 /*****************************************************************************/
1884 /******************************************************************
1885 * SetConsoleCtrlHandler (KERNEL32.@)
1887 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1889 BOOL ret = TRUE;
1891 TRACE("(%p,%i)\n", func, add);
1893 if (!func)
1895 RtlEnterCriticalSection(&CONSOLE_CritSect);
1896 if (add)
1897 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1898 else
1899 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1900 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1902 else if (add)
1904 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1906 if (!ch) return FALSE;
1907 ch->handler = func;
1908 RtlEnterCriticalSection(&CONSOLE_CritSect);
1909 ch->next = CONSOLE_Handlers;
1910 CONSOLE_Handlers = ch;
1911 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1913 else
1915 struct ConsoleHandler** ch;
1916 RtlEnterCriticalSection(&CONSOLE_CritSect);
1917 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1919 if ((*ch)->handler == func) break;
1921 if (*ch)
1923 struct ConsoleHandler* rch = *ch;
1925 /* sanity check */
1926 if (rch == &CONSOLE_DefaultConsoleHandler)
1928 ERR("Who's trying to remove default handler???\n");
1929 SetLastError(ERROR_INVALID_PARAMETER);
1930 ret = FALSE;
1932 else
1934 *ch = rch->next;
1935 HeapFree(GetProcessHeap(), 0, rch);
1938 else
1940 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1941 SetLastError(ERROR_INVALID_PARAMETER);
1942 ret = FALSE;
1944 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1946 return ret;
1949 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1951 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1952 return EXCEPTION_EXECUTE_HANDLER;
1955 /******************************************************************
1956 * CONSOLE_SendEventThread
1958 * Internal helper to pass an event to the list on installed handlers
1960 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1962 DWORD_PTR event = (DWORD_PTR)pmt;
1963 struct ConsoleHandler* ch;
1965 if (event == CTRL_C_EVENT)
1967 BOOL caught_by_dbg = TRUE;
1968 /* First, try to pass the ctrl-C event to the debugger (if any)
1969 * If it continues, there's nothing more to do
1970 * Otherwise, we need to send the ctrl-C event to the handlers
1972 __TRY
1974 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1976 __EXCEPT(CONSOLE_CtrlEventHandler)
1978 caught_by_dbg = FALSE;
1980 __ENDTRY;
1981 if (caught_by_dbg) return 0;
1982 /* the debugger didn't continue... so, pass to ctrl handlers */
1984 RtlEnterCriticalSection(&CONSOLE_CritSect);
1985 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1987 if (ch->handler(event)) break;
1989 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1990 return 1;
1993 /******************************************************************
1994 * CONSOLE_HandleCtrlC
1996 * Check whether the shall manipulate CtrlC events
1998 int CONSOLE_HandleCtrlC(unsigned sig)
2000 /* FIXME: better test whether a console is attached to this process ??? */
2001 extern unsigned CONSOLE_GetNumHistoryEntries(void);
2002 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
2004 /* check if we have to ignore ctrl-C events */
2005 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
2007 /* Create a separate thread to signal all the events.
2008 * This is needed because:
2009 * - this function can be called in an Unix signal handler (hence on an
2010 * different stack than the thread that's running). This breaks the
2011 * Win32 exception mechanisms (where the thread's stack is checked).
2012 * - since the current thread, while processing the signal, can hold the
2013 * console critical section, we need another execution environment where
2014 * we can wait on this critical section
2016 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2018 return 1;
2021 /******************************************************************************
2022 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2024 * PARAMS
2025 * dwCtrlEvent [I] Type of event
2026 * dwProcessGroupID [I] Process group ID to send event to
2028 * RETURNS
2029 * Success: True
2030 * Failure: False (and *should* [but doesn't] set LastError)
2032 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2033 DWORD dwProcessGroupID)
2035 BOOL ret;
2037 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2039 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2041 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2042 return FALSE;
2045 SERVER_START_REQ( send_console_signal )
2047 req->signal = dwCtrlEvent;
2048 req->group_id = dwProcessGroupID;
2049 ret = !wine_server_call_err( req );
2051 SERVER_END_REQ;
2053 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2054 * have been handled by all processes in the given group?
2055 * As of today, we don't wait...
2057 return ret;
2061 /******************************************************************************
2062 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2064 * PARAMS
2065 * dwDesiredAccess [I] Access flag
2066 * dwShareMode [I] Buffer share mode
2067 * sa [I] Security attributes
2068 * dwFlags [I] Type of buffer to create
2069 * lpScreenBufferData [I] Reserved
2071 * NOTES
2072 * Should call SetLastError
2074 * RETURNS
2075 * Success: Handle to new console screen buffer
2076 * Failure: INVALID_HANDLE_VALUE
2078 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2079 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2080 LPVOID lpScreenBufferData)
2082 HANDLE ret = INVALID_HANDLE_VALUE;
2084 TRACE("(%d,%d,%p,%d,%p)\n",
2085 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2087 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2089 SetLastError(ERROR_INVALID_PARAMETER);
2090 return INVALID_HANDLE_VALUE;
2093 SERVER_START_REQ(create_console_output)
2095 req->handle_in = 0;
2096 req->access = dwDesiredAccess;
2097 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2098 req->share = dwShareMode;
2099 req->fd = -1;
2100 if (!wine_server_call_err( req ))
2101 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2103 SERVER_END_REQ;
2105 return ret;
2109 /***********************************************************************
2110 * GetConsoleScreenBufferInfo (KERNEL32.@)
2112 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2114 BOOL ret;
2116 SERVER_START_REQ(get_console_output_info)
2118 req->handle = console_handle_unmap(hConsoleOutput);
2119 if ((ret = !wine_server_call_err( req )))
2121 csbi->dwSize.X = reply->width;
2122 csbi->dwSize.Y = reply->height;
2123 csbi->dwCursorPosition.X = reply->cursor_x;
2124 csbi->dwCursorPosition.Y = reply->cursor_y;
2125 csbi->wAttributes = reply->attr;
2126 csbi->srWindow.Left = reply->win_left;
2127 csbi->srWindow.Right = reply->win_right;
2128 csbi->srWindow.Top = reply->win_top;
2129 csbi->srWindow.Bottom = reply->win_bottom;
2130 csbi->dwMaximumWindowSize.X = reply->max_width;
2131 csbi->dwMaximumWindowSize.Y = reply->max_height;
2134 SERVER_END_REQ;
2136 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2137 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2138 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2139 csbi->wAttributes,
2140 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2141 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2143 return ret;
2147 /******************************************************************************
2148 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2150 * RETURNS
2151 * Success: TRUE
2152 * Failure: FALSE
2154 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2156 BOOL ret;
2158 TRACE("(%p)\n", hConsoleOutput);
2160 SERVER_START_REQ( set_console_input_info )
2162 req->handle = 0;
2163 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2164 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2165 ret = !wine_server_call_err( req );
2167 SERVER_END_REQ;
2168 return ret;
2172 /***********************************************************************
2173 * GetConsoleMode (KERNEL32.@)
2175 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2177 BOOL ret;
2179 SERVER_START_REQ( get_console_mode )
2181 req->handle = console_handle_unmap(hcon);
2182 if ((ret = !wine_server_call_err( req )))
2184 if (mode) *mode = reply->mode;
2187 SERVER_END_REQ;
2188 return ret;
2192 /******************************************************************************
2193 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2195 * PARAMS
2196 * hcon [I] Handle to console input or screen buffer
2197 * mode [I] Input or output mode to set
2199 * RETURNS
2200 * Success: TRUE
2201 * Failure: FALSE
2203 * mode:
2204 * ENABLE_PROCESSED_INPUT 0x01
2205 * ENABLE_LINE_INPUT 0x02
2206 * ENABLE_ECHO_INPUT 0x04
2207 * ENABLE_WINDOW_INPUT 0x08
2208 * ENABLE_MOUSE_INPUT 0x10
2210 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2212 BOOL ret;
2214 SERVER_START_REQ(set_console_mode)
2216 req->handle = console_handle_unmap(hcon);
2217 req->mode = mode;
2218 ret = !wine_server_call_err( req );
2220 SERVER_END_REQ;
2221 /* FIXME: when resetting a console input to editline mode, I think we should
2222 * empty the S_EditString buffer
2225 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2227 return ret;
2231 /******************************************************************
2232 * CONSOLE_WriteChars
2234 * WriteConsoleOutput helper: hides server call semantics
2235 * writes a string at a given pos with standard attribute
2237 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2239 int written = -1;
2241 if (!nc) return 0;
2243 SERVER_START_REQ( write_console_output )
2245 req->handle = console_handle_unmap(hCon);
2246 req->x = pos->X;
2247 req->y = pos->Y;
2248 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2249 req->wrap = FALSE;
2250 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2251 if (!wine_server_call_err( req )) written = reply->written;
2253 SERVER_END_REQ;
2255 if (written > 0) pos->X += written;
2256 return written;
2259 /******************************************************************
2260 * next_line
2262 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2265 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2267 SMALL_RECT src;
2268 CHAR_INFO ci;
2269 COORD dst;
2271 csbi->dwCursorPosition.X = 0;
2272 csbi->dwCursorPosition.Y++;
2274 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2276 src.Top = 1;
2277 src.Bottom = csbi->dwSize.Y - 1;
2278 src.Left = 0;
2279 src.Right = csbi->dwSize.X - 1;
2281 dst.X = 0;
2282 dst.Y = 0;
2284 ci.Attributes = csbi->wAttributes;
2285 ci.Char.UnicodeChar = ' ';
2287 csbi->dwCursorPosition.Y--;
2288 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2289 return 0;
2290 return 1;
2293 /******************************************************************
2294 * write_block
2296 * WriteConsoleOutput helper: writes a block of non special characters
2297 * Block can spread on several lines, and wrapping, if needed, is
2298 * handled
2301 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2302 DWORD mode, LPCWSTR ptr, int len)
2304 int blk; /* number of chars to write on current line */
2305 int done; /* number of chars already written */
2307 if (len <= 0) return 1;
2309 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2311 for (done = 0; done < len; done += blk)
2313 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2315 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2316 return 0;
2317 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2318 return 0;
2321 else
2323 int pos = csbi->dwCursorPosition.X;
2324 /* FIXME: we could reduce the number of loops
2325 * but, in most cases we wouldn't gain lots of time (it would only
2326 * happen if we're asked to overwrite more than twice the part of the line,
2327 * which is unlikely
2329 for (done = 0; done < len; done += blk)
2331 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2333 csbi->dwCursorPosition.X = pos;
2334 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2335 return 0;
2339 return 1;
2342 /***********************************************************************
2343 * WriteConsoleW (KERNEL32.@)
2345 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2346 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2348 DWORD mode;
2349 DWORD nw = 0;
2350 const WCHAR* psz = lpBuffer;
2351 CONSOLE_SCREEN_BUFFER_INFO csbi;
2352 int k, first = 0, fd;
2354 TRACE("%p %s %d %p %p\n",
2355 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2356 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2358 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2360 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2362 char* ptr;
2363 unsigned len;
2364 BOOL ret;
2366 close(fd);
2367 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2368 * to do the job
2370 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2371 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2372 return FALSE;
2374 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2375 ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2376 ptr, len, lpNumberOfCharsWritten, NULL);
2377 if (ret && lpNumberOfCharsWritten)
2379 if (*lpNumberOfCharsWritten == len)
2380 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2381 else
2382 FIXME("Conversion not supported yet\n");
2384 HeapFree(GetProcessHeap(), 0, ptr);
2385 return ret;
2388 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2389 return FALSE;
2391 if (!nNumberOfCharsToWrite) return TRUE;
2393 if (mode & ENABLE_PROCESSED_OUTPUT)
2395 unsigned int i;
2397 for (i = 0; i < nNumberOfCharsToWrite; i++)
2399 switch (psz[i])
2401 case '\b': case '\t': case '\n': case '\a': case '\r':
2402 /* don't handle here the i-th char... done below */
2403 if ((k = i - first) > 0)
2405 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2406 goto the_end;
2407 nw += k;
2409 first = i + 1;
2410 nw++;
2412 switch (psz[i])
2414 case '\b':
2415 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2416 break;
2417 case '\t':
2419 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2421 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2422 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2423 goto the_end;
2425 break;
2426 case '\n':
2427 next_line(hConsoleOutput, &csbi);
2428 break;
2429 case '\a':
2430 Beep(400, 300);
2431 break;
2432 case '\r':
2433 csbi.dwCursorPosition.X = 0;
2434 break;
2435 default:
2436 break;
2441 /* write the remaining block (if any) if processed output is enabled, or the
2442 * entire buffer otherwise
2444 if ((k = nNumberOfCharsToWrite - first) > 0)
2446 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2447 goto the_end;
2448 nw += k;
2451 the_end:
2452 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2453 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2454 return nw != 0;
2458 /***********************************************************************
2459 * WriteConsoleA (KERNEL32.@)
2461 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2462 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2464 BOOL ret;
2465 LPWSTR xstring;
2466 DWORD n;
2468 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2470 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2471 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2472 if (!xstring) return 0;
2474 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2476 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2478 HeapFree(GetProcessHeap(), 0, xstring);
2480 return ret;
2483 /******************************************************************************
2484 * SetConsoleCursorPosition [KERNEL32.@]
2485 * Sets the cursor position in console
2487 * PARAMS
2488 * hConsoleOutput [I] Handle of console screen buffer
2489 * dwCursorPosition [I] New cursor position coordinates
2491 * RETURNS
2492 * Success: TRUE
2493 * Failure: FALSE
2495 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2497 BOOL ret;
2498 CONSOLE_SCREEN_BUFFER_INFO csbi;
2499 int do_move = 0;
2500 int w, h;
2502 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2504 SERVER_START_REQ(set_console_output_info)
2506 req->handle = console_handle_unmap(hcon);
2507 req->cursor_x = pos.X;
2508 req->cursor_y = pos.Y;
2509 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2510 ret = !wine_server_call_err( req );
2512 SERVER_END_REQ;
2514 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2515 return FALSE;
2517 /* if cursor is no longer visible, scroll the visible window... */
2518 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2519 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2520 if (pos.X < csbi.srWindow.Left)
2522 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2523 do_move++;
2525 else if (pos.X > csbi.srWindow.Right)
2527 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2528 do_move++;
2530 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2532 if (pos.Y < csbi.srWindow.Top)
2534 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2535 do_move++;
2537 else if (pos.Y > csbi.srWindow.Bottom)
2539 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2540 do_move++;
2542 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2544 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2546 return ret;
2549 /******************************************************************************
2550 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2552 * PARAMS
2553 * hcon [I] Handle to console screen buffer
2554 * cinfo [O] Address of cursor information
2556 * RETURNS
2557 * Success: TRUE
2558 * Failure: FALSE
2560 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2562 BOOL ret;
2564 SERVER_START_REQ(get_console_output_info)
2566 req->handle = console_handle_unmap(hCon);
2567 ret = !wine_server_call_err( req );
2568 if (ret && cinfo)
2570 cinfo->dwSize = reply->cursor_size;
2571 cinfo->bVisible = reply->cursor_visible;
2574 SERVER_END_REQ;
2576 if (!ret) return FALSE;
2578 if (!cinfo)
2580 SetLastError(ERROR_INVALID_ACCESS);
2581 ret = FALSE;
2583 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2585 return ret;
2589 /******************************************************************************
2590 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2592 * PARAMS
2593 * hcon [I] Handle to console screen buffer
2594 * cinfo [I] Address of cursor information
2595 * RETURNS
2596 * Success: TRUE
2597 * Failure: FALSE
2599 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2601 BOOL ret;
2603 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2604 SERVER_START_REQ(set_console_output_info)
2606 req->handle = console_handle_unmap(hCon);
2607 req->cursor_size = cinfo->dwSize;
2608 req->cursor_visible = cinfo->bVisible;
2609 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2610 ret = !wine_server_call_err( req );
2612 SERVER_END_REQ;
2613 return ret;
2617 /******************************************************************************
2618 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2620 * PARAMS
2621 * hcon [I] Handle to console screen buffer
2622 * bAbsolute [I] Coordinate type flag
2623 * window [I] Address of new window rectangle
2624 * RETURNS
2625 * Success: TRUE
2626 * Failure: FALSE
2628 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2630 SMALL_RECT p = *window;
2631 BOOL ret;
2633 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2635 if (!bAbsolute)
2637 CONSOLE_SCREEN_BUFFER_INFO csbi;
2639 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2640 return FALSE;
2641 p.Left += csbi.srWindow.Left;
2642 p.Top += csbi.srWindow.Top;
2643 p.Right += csbi.srWindow.Right;
2644 p.Bottom += csbi.srWindow.Bottom;
2646 SERVER_START_REQ(set_console_output_info)
2648 req->handle = console_handle_unmap(hCon);
2649 req->win_left = p.Left;
2650 req->win_top = p.Top;
2651 req->win_right = p.Right;
2652 req->win_bottom = p.Bottom;
2653 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2654 ret = !wine_server_call_err( req );
2656 SERVER_END_REQ;
2658 return ret;
2662 /******************************************************************************
2663 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2665 * Sets the foreground and background color attributes of characters
2666 * written to the screen buffer.
2668 * RETURNS
2669 * Success: TRUE
2670 * Failure: FALSE
2672 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2674 BOOL ret;
2676 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2677 SERVER_START_REQ(set_console_output_info)
2679 req->handle = console_handle_unmap(hConsoleOutput);
2680 req->attr = wAttr;
2681 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2682 ret = !wine_server_call_err( req );
2684 SERVER_END_REQ;
2685 return ret;
2689 /******************************************************************************
2690 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2692 * PARAMS
2693 * hConsoleOutput [I] Handle to console screen buffer
2694 * dwSize [I] New size in character rows and cols
2696 * RETURNS
2697 * Success: TRUE
2698 * Failure: FALSE
2700 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2702 BOOL ret;
2704 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2705 SERVER_START_REQ(set_console_output_info)
2707 req->handle = console_handle_unmap(hConsoleOutput);
2708 req->width = dwSize.X;
2709 req->height = dwSize.Y;
2710 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2711 ret = !wine_server_call_err( req );
2713 SERVER_END_REQ;
2714 return ret;
2718 /******************************************************************************
2719 * ScrollConsoleScreenBufferA [KERNEL32.@]
2722 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2723 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2724 LPCHAR_INFO lpFill)
2726 CHAR_INFO ciw;
2728 ciw.Attributes = lpFill->Attributes;
2729 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2731 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2732 dwDestOrigin, &ciw);
2735 /******************************************************************
2736 * CONSOLE_FillLineUniform
2738 * Helper function for ScrollConsoleScreenBufferW
2739 * Fills a part of a line with a constant character info
2741 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2743 SERVER_START_REQ( fill_console_output )
2745 req->handle = console_handle_unmap(hConsoleOutput);
2746 req->mode = CHAR_INFO_MODE_TEXTATTR;
2747 req->x = i;
2748 req->y = j;
2749 req->count = len;
2750 req->wrap = FALSE;
2751 req->data.ch = lpFill->Char.UnicodeChar;
2752 req->data.attr = lpFill->Attributes;
2753 wine_server_call_err( req );
2755 SERVER_END_REQ;
2758 /******************************************************************************
2759 * ScrollConsoleScreenBufferW [KERNEL32.@]
2763 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2764 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2765 LPCHAR_INFO lpFill)
2767 SMALL_RECT dst;
2768 DWORD ret;
2769 int i, j;
2770 int start = -1;
2771 SMALL_RECT clip;
2772 CONSOLE_SCREEN_BUFFER_INFO csbi;
2773 BOOL inside;
2774 COORD src;
2776 if (lpClipRect)
2777 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2778 lpScrollRect->Left, lpScrollRect->Top,
2779 lpScrollRect->Right, lpScrollRect->Bottom,
2780 lpClipRect->Left, lpClipRect->Top,
2781 lpClipRect->Right, lpClipRect->Bottom,
2782 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2783 else
2784 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2785 lpScrollRect->Left, lpScrollRect->Top,
2786 lpScrollRect->Right, lpScrollRect->Bottom,
2787 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2789 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2790 return FALSE;
2792 src.X = lpScrollRect->Left;
2793 src.Y = lpScrollRect->Top;
2795 /* step 1: get dst rect */
2796 dst.Left = dwDestOrigin.X;
2797 dst.Top = dwDestOrigin.Y;
2798 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2799 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2801 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2802 if (lpClipRect)
2804 clip.Left = max(0, lpClipRect->Left);
2805 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2806 clip.Top = max(0, lpClipRect->Top);
2807 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2809 else
2811 clip.Left = 0;
2812 clip.Right = csbi.dwSize.X - 1;
2813 clip.Top = 0;
2814 clip.Bottom = csbi.dwSize.Y - 1;
2816 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2818 /* step 2b: clip dst rect */
2819 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2820 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2821 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2822 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2824 /* step 3: transfer the bits */
2825 SERVER_START_REQ(move_console_output)
2827 req->handle = console_handle_unmap(hConsoleOutput);
2828 req->x_src = src.X;
2829 req->y_src = src.Y;
2830 req->x_dst = dst.Left;
2831 req->y_dst = dst.Top;
2832 req->w = dst.Right - dst.Left + 1;
2833 req->h = dst.Bottom - dst.Top + 1;
2834 ret = !wine_server_call_err( req );
2836 SERVER_END_REQ;
2838 if (!ret) return FALSE;
2840 /* step 4: clean out the exposed part */
2842 /* have to write cell [i,j] if it is not in dst rect (because it has already
2843 * been written to by the scroll) and is in clip (we shall not write
2844 * outside of clip)
2846 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2848 inside = dst.Top <= j && j <= dst.Bottom;
2849 start = -1;
2850 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2852 if (inside && dst.Left <= i && i <= dst.Right)
2854 if (start != -1)
2856 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2857 start = -1;
2860 else
2862 if (start == -1) start = i;
2865 if (start != -1)
2866 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2869 return TRUE;
2872 /******************************************************************
2873 * AttachConsole (KERNEL32.@)
2875 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2877 FIXME("stub %x\n",dwProcessId);
2878 return TRUE;
2881 /******************************************************************
2882 * GetConsoleDisplayMode (KERNEL32.@)
2884 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2886 TRACE("semi-stub: %p\n", lpModeFlags);
2887 /* It is safe to successfully report windowed mode */
2888 *lpModeFlags = 0;
2889 return TRUE;
2892 /******************************************************************
2893 * SetConsoleDisplayMode (KERNEL32.@)
2895 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2896 COORD *lpNewScreenBufferDimensions)
2898 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2899 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2900 if (dwFlags == 1)
2902 /* We cannot switch to fullscreen */
2903 return FALSE;
2905 return TRUE;
2909 /* ====================================================================
2911 * Console manipulation functions
2913 * ====================================================================*/
2915 /* some missing functions...
2916 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2917 * should get the right API and implement them
2918 * GetConsoleCommandHistory[AW] (dword dword dword)
2919 * GetConsoleCommandHistoryLength[AW]
2920 * SetConsoleCommandHistoryMode
2921 * SetConsoleNumberOfCommands[AW]
2923 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2925 int len = 0;
2927 SERVER_START_REQ( get_console_input_history )
2929 req->handle = 0;
2930 req->index = idx;
2931 if (buf && buf_len > 1)
2933 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2935 if (!wine_server_call_err( req ))
2937 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2938 len = reply->total / sizeof(WCHAR) + 1;
2941 SERVER_END_REQ;
2942 return len;
2945 /******************************************************************
2946 * CONSOLE_AppendHistory
2950 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2952 size_t len = strlenW(ptr);
2953 BOOL ret;
2955 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2956 if (!len) return FALSE;
2958 SERVER_START_REQ( append_console_input_history )
2960 req->handle = 0;
2961 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2962 ret = !wine_server_call_err( req );
2964 SERVER_END_REQ;
2965 return ret;
2968 /******************************************************************
2969 * CONSOLE_GetNumHistoryEntries
2973 unsigned CONSOLE_GetNumHistoryEntries(void)
2975 unsigned ret = -1;
2976 SERVER_START_REQ(get_console_input_info)
2978 req->handle = 0;
2979 if (!wine_server_call_err( req )) ret = reply->history_index;
2981 SERVER_END_REQ;
2982 return ret;
2985 /******************************************************************
2986 * CONSOLE_GetEditionMode
2990 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2992 unsigned ret = FALSE;
2993 SERVER_START_REQ(get_console_input_info)
2995 req->handle = console_handle_unmap(hConIn);
2996 if ((ret = !wine_server_call_err( req )))
2997 *mode = reply->edition_mode;
2999 SERVER_END_REQ;
3000 return ret;
3003 /******************************************************************
3004 * GetConsoleAliasW
3007 * RETURNS
3008 * 0 if an error occurred, non-zero for success
3011 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3012 DWORD TargetBufferLength, LPWSTR lpExename)
3014 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3015 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3016 return 0;
3019 /******************************************************************
3020 * GetConsoleProcessList (KERNEL32.@)
3022 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3024 FIXME("(%p,%d): stub\n", processlist, processcount);
3026 if (!processlist || processcount < 1)
3028 SetLastError(ERROR_INVALID_PARAMETER);
3029 return 0;
3032 return 0;
3035 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3037 memset(&S_termios, 0, sizeof(S_termios));
3038 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3040 HANDLE conin;
3042 /* FIXME: to be done even if program is a GUI ? */
3043 /* This is wine specific: we have no parent (we're started from unix)
3044 * so, create a simple console with bare handles
3046 TERM_Init();
3047 wine_server_send_fd(0);
3048 SERVER_START_REQ( alloc_console )
3050 req->access = GENERIC_READ | GENERIC_WRITE;
3051 req->attributes = OBJ_INHERIT;
3052 req->pid = 0xffffffff;
3053 req->input_fd = 0;
3054 wine_server_call( req );
3055 conin = wine_server_ptr_handle( reply->handle_in );
3056 /* reply->event shouldn't be created by server */
3058 SERVER_END_REQ;
3060 if (!params->hStdInput)
3061 params->hStdInput = conin;
3063 if (!params->hStdOutput)
3065 wine_server_send_fd(1);
3066 SERVER_START_REQ( create_console_output )
3068 req->handle_in = wine_server_obj_handle(conin);
3069 req->access = GENERIC_WRITE|GENERIC_READ;
3070 req->attributes = OBJ_INHERIT;
3071 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3072 req->fd = 1;
3073 wine_server_call(req);
3074 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3076 SERVER_END_REQ;
3078 if (!params->hStdError)
3080 wine_server_send_fd(2);
3081 SERVER_START_REQ( create_console_output )
3083 req->handle_in = wine_server_obj_handle(conin);
3084 req->access = GENERIC_WRITE|GENERIC_READ;
3085 req->attributes = OBJ_INHERIT;
3086 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3087 req->fd = 2;
3088 wine_server_call(req);
3089 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3091 SERVER_END_REQ;
3095 /* convert value from server:
3096 * + 0 => INVALID_HANDLE_VALUE
3097 * + console handle needs to be mapped
3099 if (!params->hStdInput)
3100 params->hStdInput = INVALID_HANDLE_VALUE;
3101 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3103 params->hStdInput = console_handle_map(params->hStdInput);
3104 save_console_mode(params->hStdInput);
3107 if (!params->hStdOutput)
3108 params->hStdOutput = INVALID_HANDLE_VALUE;
3109 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3110 params->hStdOutput = console_handle_map(params->hStdOutput);
3112 if (!params->hStdError)
3113 params->hStdError = INVALID_HANDLE_VALUE;
3114 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3115 params->hStdError = console_handle_map(params->hStdError);
3117 return TRUE;
3120 BOOL CONSOLE_Exit(void)
3122 /* the console is in raw mode, put it back in cooked mode */
3123 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));