shell32: Forward ShExtractIconsW to user32.PrivateExtractIconsW.
[wine/wine-gecko.git] / dlls / kernel32 / console.c
blob67c353b4b0edc229cc927cd42c1eb76ebe2a1edd
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 #define NONAMELESSUNION
49 #include "ntstatus.h"
50 #define WIN32_NO_STATUS
51 #include "windef.h"
52 #include "winbase.h"
53 #include "winnls.h"
54 #include "winerror.h"
55 #include "wincon.h"
56 #include "wine/server.h"
57 #include "wine/exception.h"
58 #include "wine/unicode.h"
59 #include "wine/debug.h"
60 #include "excpt.h"
61 #include "console_private.h"
62 #include "kernel_private.h"
64 WINE_DEFAULT_DEBUG_CHANNEL(console);
66 static CRITICAL_SECTION CONSOLE_CritSect;
67 static CRITICAL_SECTION_DEBUG critsect_debug =
69 0, 0, &CONSOLE_CritSect,
70 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
71 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
73 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
75 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
76 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
78 /* FIXME: this is not thread safe */
79 static HANDLE console_wait_event;
81 /* map input records to ASCII */
82 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
84 int i;
85 char ch;
87 for (i = 0; i < count; i++)
89 if (buffer[i].EventType != KEY_EVENT) continue;
90 WideCharToMultiByte( GetConsoleCP(), 0,
91 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
92 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
96 /* map input records to Unicode */
97 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
99 int i;
100 WCHAR ch;
102 for (i = 0; i < count; i++)
104 if (buffer[i].EventType != KEY_EVENT) continue;
105 MultiByteToWideChar( GetConsoleCP(), 0,
106 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
107 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
111 /* map char infos to ASCII */
112 static void char_info_WtoA( CHAR_INFO *buffer, int count )
114 char ch;
116 while (count-- > 0)
118 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
119 &ch, 1, NULL, NULL );
120 buffer->Char.AsciiChar = ch;
121 buffer++;
125 /* map char infos to Unicode */
126 static void char_info_AtoW( CHAR_INFO *buffer, int count )
128 WCHAR ch;
130 while (count-- > 0)
132 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
133 buffer->Char.UnicodeChar = ch;
134 buffer++;
138 static struct termios S_termios; /* saved termios for bare consoles */
139 static BOOL S_termios_raw /* = FALSE */;
141 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
142 * - a bare console is created for all CUI programs started from command line (without
143 * wineconsole) (let's call those PS)
144 * - of course, every child of a PS which requires console inheritance will get it
145 * - the console termios attributes are saved at the start of program which is attached to be
146 * bare console
147 * - if any program attached to a bare console requests input from console, the console is
148 * turned into raw mode
149 * - when the program which created the bare console (the program started from command line)
150 * exits, it will restore the console termios attributes it saved at startup (this
151 * will put back the console into cooked mode if it had been put in raw mode)
152 * - if any other program attached to this bare console is still alive, the Unix shell will put
153 * it in the background, hence forbidding access to the console. Therefore, reading console
154 * input will not be available when the bare console creator has died.
155 * FIXME: This is a limitation of current implementation
158 /* returns the fd for a bare console (-1 otherwise) */
159 static int get_console_bare_fd(HANDLE hin)
161 int fd;
163 if (is_console_handle(hin) &&
164 wine_server_handle_to_fd(wine_server_ptr_handle(console_handle_unmap(hin)),
165 0, &fd, NULL) == STATUS_SUCCESS)
166 return fd;
167 return -1;
170 static BOOL save_console_mode(HANDLE hin)
172 int fd;
173 BOOL ret;
175 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
176 ret = tcgetattr(fd, &S_termios) >= 0;
177 close(fd);
178 return ret;
181 static BOOL put_console_into_raw_mode(int fd)
183 RtlEnterCriticalSection(&CONSOLE_CritSect);
184 if (!S_termios_raw)
186 struct termios term = S_termios;
188 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
189 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
190 term.c_cflag &= ~(CSIZE | PARENB);
191 term.c_cflag |= CS8;
192 /* FIXME: we should actually disable output processing here
193 * and let kernel32/console.c do the job (with support of enable/disable of
194 * processed output)
196 /* term.c_oflag &= ~(OPOST); */
197 term.c_cc[VMIN] = 1;
198 term.c_cc[VTIME] = 0;
199 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
201 RtlLeaveCriticalSection(&CONSOLE_CritSect);
203 return S_termios_raw;
206 /* put back the console in cooked mode iff we're the process which created the bare console
207 * we don't test if this process has set the console in raw mode as it could be one of its
208 * children who did it
210 static BOOL restore_console_mode(HANDLE hin)
212 int fd;
213 BOOL ret;
215 if (!S_termios_raw ||
216 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
217 return TRUE;
218 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
219 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
220 close(fd);
221 TERM_Exit();
222 return ret;
225 /******************************************************************************
226 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
228 * RETURNS
229 * Success: hwnd of the console window.
230 * Failure: NULL
232 HWND WINAPI GetConsoleWindow(VOID)
234 HWND hWnd = NULL;
236 SERVER_START_REQ(get_console_input_info)
238 req->handle = 0;
239 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
241 SERVER_END_REQ;
243 return hWnd;
247 /******************************************************************************
248 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
250 * RETURNS
251 * Code page code
253 UINT WINAPI GetConsoleCP(VOID)
255 BOOL ret;
256 UINT codepage = GetOEMCP(); /* default value */
258 SERVER_START_REQ(get_console_input_info)
260 req->handle = 0;
261 ret = !wine_server_call_err(req);
262 if (ret && reply->input_cp)
263 codepage = reply->input_cp;
265 SERVER_END_REQ;
267 return codepage;
271 /******************************************************************************
272 * SetConsoleCP [KERNEL32.@]
274 BOOL WINAPI SetConsoleCP(UINT cp)
276 BOOL ret;
278 if (!IsValidCodePage(cp))
280 SetLastError(ERROR_INVALID_PARAMETER);
281 return FALSE;
284 SERVER_START_REQ(set_console_input_info)
286 req->handle = 0;
287 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
288 req->input_cp = cp;
289 ret = !wine_server_call_err(req);
291 SERVER_END_REQ;
293 return ret;
297 /***********************************************************************
298 * GetConsoleOutputCP (KERNEL32.@)
300 UINT WINAPI GetConsoleOutputCP(VOID)
302 BOOL ret;
303 UINT codepage = GetOEMCP(); /* default value */
305 SERVER_START_REQ(get_console_input_info)
307 req->handle = 0;
308 ret = !wine_server_call_err(req);
309 if (ret && reply->output_cp)
310 codepage = reply->output_cp;
312 SERVER_END_REQ;
314 return codepage;
318 /******************************************************************************
319 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
321 * PARAMS
322 * cp [I] code page to set
324 * RETURNS
325 * Success: TRUE
326 * Failure: FALSE
328 BOOL WINAPI SetConsoleOutputCP(UINT cp)
330 BOOL ret;
332 if (!IsValidCodePage(cp))
334 SetLastError(ERROR_INVALID_PARAMETER);
335 return FALSE;
338 SERVER_START_REQ(set_console_input_info)
340 req->handle = 0;
341 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
342 req->output_cp = cp;
343 ret = !wine_server_call_err(req);
345 SERVER_END_REQ;
347 return ret;
351 /***********************************************************************
352 * Beep (KERNEL32.@)
354 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
356 static const char beep = '\a';
357 /* dwFreq and dwDur are ignored by Win95 */
358 if (isatty(2)) write( 2, &beep, 1 );
359 return TRUE;
363 /******************************************************************
364 * OpenConsoleW (KERNEL32.@)
366 * Undocumented
367 * Open a handle to the current process console.
368 * Returns INVALID_HANDLE_VALUE on failure.
370 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
372 HANDLE output = INVALID_HANDLE_VALUE;
373 HANDLE ret;
375 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
377 if (name)
379 if (strcmpiW(coninW, name) == 0)
380 output = (HANDLE) FALSE;
381 else if (strcmpiW(conoutW, name) == 0)
382 output = (HANDLE) TRUE;
385 if (output == INVALID_HANDLE_VALUE || creation != OPEN_EXISTING)
387 SetLastError(ERROR_INVALID_PARAMETER);
388 return INVALID_HANDLE_VALUE;
391 SERVER_START_REQ( open_console )
393 req->from = wine_server_obj_handle( output );
394 req->access = access;
395 req->attributes = inherit ? OBJ_INHERIT : 0;
396 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
397 wine_server_call_err( req );
398 ret = wine_server_ptr_handle( reply->handle );
400 SERVER_END_REQ;
401 if (ret)
402 ret = console_handle_map(ret);
404 return ret;
407 /******************************************************************
408 * VerifyConsoleIoHandle (KERNEL32.@)
410 * Undocumented
412 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
414 BOOL ret;
416 if (!is_console_handle(handle)) return FALSE;
417 SERVER_START_REQ(get_console_mode)
419 req->handle = console_handle_unmap(handle);
420 ret = !wine_server_call( req );
422 SERVER_END_REQ;
423 return ret;
426 /******************************************************************
427 * DuplicateConsoleHandle (KERNEL32.@)
429 * Undocumented
431 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
432 DWORD options)
434 HANDLE ret;
436 if (!is_console_handle(handle) ||
437 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
438 GetCurrentProcess(), &ret, access, inherit, options))
439 return INVALID_HANDLE_VALUE;
440 return console_handle_map(ret);
443 /******************************************************************
444 * CloseConsoleHandle (KERNEL32.@)
446 * Undocumented
448 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
450 if (!is_console_handle(handle))
452 SetLastError(ERROR_INVALID_PARAMETER);
453 return FALSE;
455 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
458 /******************************************************************
459 * GetConsoleInputWaitHandle (KERNEL32.@)
461 * Undocumented
463 HANDLE WINAPI GetConsoleInputWaitHandle(void)
465 if (!console_wait_event)
467 SERVER_START_REQ(get_console_wait_event)
469 if (!wine_server_call_err( req ))
470 console_wait_event = wine_server_ptr_handle( reply->handle );
472 SERVER_END_REQ;
474 return console_wait_event;
478 /******************************************************************************
479 * WriteConsoleInputA [KERNEL32.@]
481 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
482 DWORD count, LPDWORD written )
484 INPUT_RECORD *recW = NULL;
485 BOOL ret;
487 if (count > 0)
489 if (!buffer)
491 SetLastError( ERROR_INVALID_ACCESS );
492 return FALSE;
495 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) )))
497 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
498 return FALSE;
501 memcpy( recW, buffer, count * sizeof(*recW) );
502 input_records_AtoW( recW, count );
505 ret = WriteConsoleInputW( handle, recW, count, written );
506 HeapFree( GetProcessHeap(), 0, recW );
507 return ret;
511 /******************************************************************************
512 * WriteConsoleInputW [KERNEL32.@]
514 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
515 DWORD count, LPDWORD written )
517 DWORD events_written = 0;
518 BOOL ret;
520 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
522 if (count > 0 && !buffer)
524 SetLastError(ERROR_INVALID_ACCESS);
525 return FALSE;
528 SERVER_START_REQ( write_console_input )
530 req->handle = console_handle_unmap(handle);
531 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
532 if ((ret = !wine_server_call_err( req )))
533 events_written = reply->written;
535 SERVER_END_REQ;
537 if (written) *written = events_written;
538 else
540 SetLastError(ERROR_INVALID_ACCESS);
541 ret = FALSE;
543 return ret;
547 /***********************************************************************
548 * WriteConsoleOutputA (KERNEL32.@)
550 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
551 COORD size, COORD coord, LPSMALL_RECT region )
553 int y;
554 BOOL ret;
555 COORD new_size, new_coord;
556 CHAR_INFO *ciw;
558 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
559 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
561 if (new_size.X <= 0 || new_size.Y <= 0)
563 region->Bottom = region->Top + new_size.Y - 1;
564 region->Right = region->Left + new_size.X - 1;
565 return TRUE;
568 /* only copy the useful rectangle */
569 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
570 return FALSE;
571 for (y = 0; y < new_size.Y; y++)
573 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
574 new_size.X * sizeof(CHAR_INFO) );
575 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
577 new_coord.X = new_coord.Y = 0;
578 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
579 HeapFree( GetProcessHeap(), 0, ciw );
580 return ret;
584 /***********************************************************************
585 * WriteConsoleOutputW (KERNEL32.@)
587 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
588 COORD size, COORD coord, LPSMALL_RECT region )
590 int width, height, y;
591 BOOL ret = TRUE;
593 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
594 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
595 region->Left, region->Top, region->Right, region->Bottom);
597 width = min( region->Right - region->Left + 1, size.X - coord.X );
598 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
600 if (width > 0 && height > 0)
602 for (y = 0; y < height; y++)
604 SERVER_START_REQ( write_console_output )
606 req->handle = console_handle_unmap(hConsoleOutput);
607 req->x = region->Left;
608 req->y = region->Top + y;
609 req->mode = CHAR_INFO_MODE_TEXTATTR;
610 req->wrap = FALSE;
611 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
612 width * sizeof(CHAR_INFO));
613 if ((ret = !wine_server_call_err( req )))
615 width = min( width, reply->width - region->Left );
616 height = min( height, reply->height - region->Top );
619 SERVER_END_REQ;
620 if (!ret) break;
623 region->Bottom = region->Top + height - 1;
624 region->Right = region->Left + width - 1;
625 return ret;
629 /******************************************************************************
630 * WriteConsoleOutputCharacterA [KERNEL32.@]
632 * See WriteConsoleOutputCharacterW.
634 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
635 COORD coord, LPDWORD lpNumCharsWritten )
637 BOOL ret;
638 LPWSTR strW = NULL;
639 DWORD lenW = 0;
641 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
642 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
644 if (length > 0)
646 if (!str)
648 SetLastError( ERROR_INVALID_ACCESS );
649 return FALSE;
652 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
654 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
656 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
657 return FALSE;
660 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
663 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
664 HeapFree( GetProcessHeap(), 0, strW );
665 return ret;
669 /******************************************************************************
670 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
671 * the console screen buffer
673 * PARAMS
674 * hConsoleOutput [I] Handle to screen buffer
675 * attr [I] Pointer to buffer with write attributes
676 * length [I] Number of cells to write to
677 * coord [I] Coords of first cell
678 * lpNumAttrsWritten [O] Pointer to number of cells written
680 * RETURNS
681 * Success: TRUE
682 * Failure: FALSE
685 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, const WORD *attr, DWORD length,
686 COORD coord, LPDWORD lpNumAttrsWritten )
688 BOOL ret;
690 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
692 if ((length > 0 && !attr) || !lpNumAttrsWritten)
694 SetLastError(ERROR_INVALID_ACCESS);
695 return FALSE;
698 *lpNumAttrsWritten = 0;
700 SERVER_START_REQ( write_console_output )
702 req->handle = console_handle_unmap(hConsoleOutput);
703 req->x = coord.X;
704 req->y = coord.Y;
705 req->mode = CHAR_INFO_MODE_ATTR;
706 req->wrap = TRUE;
707 wine_server_add_data( req, attr, length * sizeof(WORD) );
708 if ((ret = !wine_server_call_err( req )))
709 *lpNumAttrsWritten = reply->written;
711 SERVER_END_REQ;
712 return ret;
716 /******************************************************************************
717 * FillConsoleOutputCharacterA [KERNEL32.@]
719 * See FillConsoleOutputCharacterW.
721 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
722 COORD coord, LPDWORD lpNumCharsWritten )
724 WCHAR wch;
726 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
727 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
731 /******************************************************************************
732 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
734 * PARAMS
735 * hConsoleOutput [I] Handle to screen buffer
736 * ch [I] Character to write
737 * length [I] Number of cells to write to
738 * coord [I] Coords of first cell
739 * lpNumCharsWritten [O] Pointer to number of cells written
741 * RETURNS
742 * Success: TRUE
743 * Failure: FALSE
745 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
746 COORD coord, LPDWORD lpNumCharsWritten)
748 BOOL ret;
750 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
751 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
753 if (!lpNumCharsWritten)
755 SetLastError(ERROR_INVALID_ACCESS);
756 return FALSE;
759 *lpNumCharsWritten = 0;
761 SERVER_START_REQ( fill_console_output )
763 req->handle = console_handle_unmap(hConsoleOutput);
764 req->x = coord.X;
765 req->y = coord.Y;
766 req->mode = CHAR_INFO_MODE_TEXT;
767 req->wrap = TRUE;
768 req->data.ch = ch;
769 req->count = length;
770 if ((ret = !wine_server_call_err( req )))
771 *lpNumCharsWritten = reply->written;
773 SERVER_END_REQ;
774 return ret;
778 /******************************************************************************
779 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
781 * PARAMS
782 * hConsoleOutput [I] Handle to screen buffer
783 * attr [I] Color attribute to write
784 * length [I] Number of cells to write to
785 * coord [I] Coords of first cell
786 * lpNumAttrsWritten [O] Pointer to number of cells written
788 * RETURNS
789 * Success: TRUE
790 * Failure: FALSE
792 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
793 COORD coord, LPDWORD lpNumAttrsWritten )
795 BOOL ret;
797 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
798 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
800 if (!lpNumAttrsWritten)
802 SetLastError(ERROR_INVALID_ACCESS);
803 return FALSE;
806 *lpNumAttrsWritten = 0;
808 SERVER_START_REQ( fill_console_output )
810 req->handle = console_handle_unmap(hConsoleOutput);
811 req->x = coord.X;
812 req->y = coord.Y;
813 req->mode = CHAR_INFO_MODE_ATTR;
814 req->wrap = TRUE;
815 req->data.attr = attr;
816 req->count = length;
817 if ((ret = !wine_server_call_err( req )))
818 *lpNumAttrsWritten = reply->written;
820 SERVER_END_REQ;
821 return ret;
825 /******************************************************************************
826 * ReadConsoleOutputCharacterA [KERNEL32.@]
829 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
830 COORD coord, LPDWORD read_count)
832 DWORD read;
833 BOOL ret;
834 LPWSTR wptr;
836 if (!read_count)
838 SetLastError(ERROR_INVALID_ACCESS);
839 return FALSE;
842 *read_count = 0;
844 if (!(wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR))))
846 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
847 return FALSE;
850 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
852 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
853 *read_count = read;
855 HeapFree( GetProcessHeap(), 0, wptr );
856 return ret;
860 /******************************************************************************
861 * ReadConsoleOutputCharacterW [KERNEL32.@]
864 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
865 COORD coord, LPDWORD read_count )
867 BOOL ret;
869 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
871 if (!read_count)
873 SetLastError(ERROR_INVALID_ACCESS);
874 return FALSE;
877 *read_count = 0;
879 SERVER_START_REQ( read_console_output )
881 req->handle = console_handle_unmap(hConsoleOutput);
882 req->x = coord.X;
883 req->y = coord.Y;
884 req->mode = CHAR_INFO_MODE_TEXT;
885 req->wrap = TRUE;
886 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
887 if ((ret = !wine_server_call_err( req )))
888 *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
890 SERVER_END_REQ;
891 return ret;
895 /******************************************************************************
896 * ReadConsoleOutputAttribute [KERNEL32.@]
898 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
899 COORD coord, LPDWORD read_count)
901 BOOL ret;
903 TRACE("(%p,%p,%d,%dx%d,%p)\n",
904 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
906 if (!read_count)
908 SetLastError(ERROR_INVALID_ACCESS);
909 return FALSE;
912 *read_count = 0;
914 SERVER_START_REQ( read_console_output )
916 req->handle = console_handle_unmap(hConsoleOutput);
917 req->x = coord.X;
918 req->y = coord.Y;
919 req->mode = CHAR_INFO_MODE_ATTR;
920 req->wrap = TRUE;
921 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
922 if ((ret = !wine_server_call_err( req )))
923 *read_count = wine_server_reply_size(reply) / sizeof(WORD);
925 SERVER_END_REQ;
926 return ret;
930 /******************************************************************************
931 * ReadConsoleOutputA [KERNEL32.@]
934 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
935 COORD coord, LPSMALL_RECT region )
937 BOOL ret;
938 int y;
940 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
941 if (ret && region->Right >= region->Left)
943 for (y = 0; y <= region->Bottom - region->Top; y++)
945 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
946 region->Right - region->Left + 1 );
949 return ret;
953 /******************************************************************************
954 * ReadConsoleOutputW [KERNEL32.@]
956 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
957 * think we need to be *that* compatible. -- AJ
959 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
960 COORD coord, LPSMALL_RECT region )
962 int width, height, y;
963 BOOL ret = TRUE;
965 width = min( region->Right - region->Left + 1, size.X - coord.X );
966 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
968 if (width > 0 && height > 0)
970 for (y = 0; y < height; y++)
972 SERVER_START_REQ( read_console_output )
974 req->handle = console_handle_unmap(hConsoleOutput);
975 req->x = region->Left;
976 req->y = region->Top + y;
977 req->mode = CHAR_INFO_MODE_TEXTATTR;
978 req->wrap = FALSE;
979 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
980 width * sizeof(CHAR_INFO) );
981 if ((ret = !wine_server_call_err( req )))
983 width = min( width, reply->width - region->Left );
984 height = min( height, reply->height - region->Top );
987 SERVER_END_REQ;
988 if (!ret) break;
991 region->Bottom = region->Top + height - 1;
992 region->Right = region->Left + width - 1;
993 return ret;
997 /******************************************************************************
998 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
1000 * PARAMS
1001 * handle [I] Handle to console input buffer
1002 * buffer [O] Address of buffer for read data
1003 * count [I] Number of records to read
1004 * pRead [O] Address of number of records read
1006 * RETURNS
1007 * Success: TRUE
1008 * Failure: FALSE
1010 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1012 DWORD read;
1014 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
1015 input_records_WtoA( buffer, read );
1016 if (pRead) *pRead = read;
1017 return TRUE;
1021 /***********************************************************************
1022 * PeekConsoleInputA (KERNEL32.@)
1024 * Gets 'count' first events (or less) from input queue.
1026 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1028 DWORD read;
1030 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
1031 input_records_WtoA( buffer, read );
1032 if (pRead) *pRead = read;
1033 return TRUE;
1037 /***********************************************************************
1038 * PeekConsoleInputW (KERNEL32.@)
1040 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
1042 BOOL ret;
1043 SERVER_START_REQ( read_console_input )
1045 req->handle = console_handle_unmap(handle);
1046 req->flush = FALSE;
1047 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1048 if ((ret = !wine_server_call_err( req )))
1050 if (read) *read = count ? reply->read : 0;
1053 SERVER_END_REQ;
1054 return ret;
1058 /***********************************************************************
1059 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1061 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1063 BOOL ret;
1064 SERVER_START_REQ( read_console_input )
1066 req->handle = console_handle_unmap(handle);
1067 req->flush = FALSE;
1068 if ((ret = !wine_server_call_err( req )))
1070 if (nrofevents)
1071 *nrofevents = reply->read;
1072 else
1074 SetLastError(ERROR_INVALID_ACCESS);
1075 ret = FALSE;
1079 SERVER_END_REQ;
1080 return ret;
1084 /******************************************************************************
1085 * read_console_input
1087 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1089 * Returns
1090 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1092 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1094 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1096 enum read_console_input_return ret;
1097 char input[8];
1098 WCHAR inputw[8];
1099 int i;
1100 size_t idx = 0, idxw;
1101 unsigned numEvent;
1102 INPUT_RECORD ir[8];
1103 DWORD written;
1104 struct pollfd pollfd;
1105 BOOL locked = FALSE, next_char;
1109 if (idx == sizeof(input))
1111 FIXME("buffer too small (%s)\n", wine_dbgstr_an(input, idx));
1112 ret = rci_error;
1113 break;
1115 pollfd.fd = fd;
1116 pollfd.events = POLLIN;
1117 pollfd.revents = 0;
1118 next_char = FALSE;
1120 switch (poll(&pollfd, 1, timeout))
1122 case 1:
1123 if (!locked)
1125 RtlEnterCriticalSection(&CONSOLE_CritSect);
1126 locked = TRUE;
1128 i = read(fd, &input[idx], 1);
1129 if (i < 0)
1131 ret = rci_error;
1132 break;
1134 if (i == 0)
1136 /* actually another thread likely beat us to reading the char
1137 * return rci_gotone, while not perfect, it should work in most of the cases (as the new event
1138 * should be now in the queue, fed from the other thread)
1140 ret = rci_gotone;
1141 break;
1144 idx++;
1145 numEvent = TERM_FillInputRecord(input, idx, ir);
1146 switch (numEvent)
1148 case 0:
1149 /* we need more char(s) to tell if it matches a key-db entry. wait 1/2s for next char */
1150 timeout = 500;
1151 next_char = TRUE;
1152 break;
1153 case -1:
1154 /* we haven't found the string into key-db, push full input string into server */
1155 idxw = MultiByteToWideChar(CP_UNIXCP, 0, input, idx, inputw, sizeof(inputw) / sizeof(inputw[0]));
1157 /* we cannot translate yet... likely we need more chars (wait max 1/2s for next char) */
1158 if (idxw == 0)
1160 timeout = 500;
1161 next_char = TRUE;
1162 break;
1164 for (i = 0; i < idxw; i++)
1166 numEvent = TERM_FillSimpleChar(inputw[i], ir);
1167 WriteConsoleInputW(handle, ir, numEvent, &written);
1169 ret = rci_gotone;
1170 break;
1171 default:
1172 /* we got a transformation from key-db... push this into server */
1173 ret = WriteConsoleInputW(handle, ir, numEvent, &written) ? rci_gotone : rci_error;
1174 break;
1176 break;
1177 case 0: ret = rci_timeout; break;
1178 default: ret = rci_error; break;
1180 } while (next_char);
1181 if (locked) RtlLeaveCriticalSection(&CONSOLE_CritSect);
1183 return ret;
1186 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1188 int fd;
1189 enum read_console_input_return ret;
1191 if ((fd = get_console_bare_fd(handle)) != -1)
1193 put_console_into_raw_mode(fd);
1194 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1196 ret = bare_console_fetch_input(handle, fd, timeout);
1198 else ret = rci_gotone;
1199 close(fd);
1200 if (ret != rci_gotone) return ret;
1202 else
1204 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1206 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1207 return rci_timeout;
1210 SERVER_START_REQ( read_console_input )
1212 req->handle = console_handle_unmap(handle);
1213 req->flush = TRUE;
1214 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1215 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1216 else ret = rci_gotone;
1218 SERVER_END_REQ;
1220 return ret;
1224 /***********************************************************************
1225 * FlushConsoleInputBuffer (KERNEL32.@)
1227 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1229 enum read_console_input_return last;
1230 INPUT_RECORD ir;
1232 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1234 return last == rci_timeout;
1238 /***********************************************************************
1239 * SetConsoleTitleA (KERNEL32.@)
1241 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1243 LPWSTR titleW;
1244 BOOL ret;
1246 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1247 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1248 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1249 ret = SetConsoleTitleW(titleW);
1250 HeapFree(GetProcessHeap(), 0, titleW);
1251 return ret;
1255 /***********************************************************************
1256 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1258 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1260 FIXME( "stub %p\n", layoutName);
1261 return TRUE;
1264 /***********************************************************************
1265 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1267 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1269 static int once;
1270 if (!once++)
1271 FIXME( "stub %p\n", layoutName);
1272 return TRUE;
1275 static WCHAR input_exe[MAX_PATH + 1];
1277 /***********************************************************************
1278 * GetConsoleInputExeNameW (KERNEL32.@)
1280 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1282 TRACE("%u %p\n", buflen, buffer);
1284 RtlEnterCriticalSection(&CONSOLE_CritSect);
1285 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1286 else SetLastError(ERROR_BUFFER_OVERFLOW);
1287 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1289 return TRUE;
1292 /***********************************************************************
1293 * GetConsoleInputExeNameA (KERNEL32.@)
1295 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1297 TRACE("%u %p\n", buflen, buffer);
1299 RtlEnterCriticalSection(&CONSOLE_CritSect);
1300 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1301 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1302 else SetLastError(ERROR_BUFFER_OVERFLOW);
1303 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1305 return TRUE;
1308 /***********************************************************************
1309 * GetConsoleTitleA (KERNEL32.@)
1311 * See GetConsoleTitleW.
1313 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1315 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1316 DWORD ret;
1318 if (!ptr) return 0;
1319 ret = GetConsoleTitleW( ptr, size );
1320 if (ret)
1322 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1323 ret = strlen(title);
1325 HeapFree(GetProcessHeap(), 0, ptr);
1326 return ret;
1330 /******************************************************************************
1331 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1333 * PARAMS
1334 * title [O] Address of buffer for title
1335 * size [I] Size of buffer
1337 * RETURNS
1338 * Success: Length of string copied
1339 * Failure: 0
1341 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1343 DWORD ret = 0;
1345 SERVER_START_REQ( get_console_input_info )
1347 req->handle = 0;
1348 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1349 if (!wine_server_call_err( req ))
1351 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1352 title[ret] = 0;
1355 SERVER_END_REQ;
1356 return ret;
1360 /***********************************************************************
1361 * GetLargestConsoleWindowSize (KERNEL32.@)
1363 * NOTE
1364 * This should return a COORD, but calling convention for returning
1365 * structures is different between Windows and gcc on i386.
1367 * VERSION: [i386]
1369 #ifdef __i386__
1370 #undef GetLargestConsoleWindowSize
1371 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1373 union {
1374 COORD c;
1375 DWORD w;
1376 } x;
1377 x.c.X = 80;
1378 x.c.Y = 24;
1379 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1380 return x.w;
1382 #endif /* defined(__i386__) */
1385 /***********************************************************************
1386 * GetLargestConsoleWindowSize (KERNEL32.@)
1388 * NOTE
1389 * This should return a COORD, but calling convention for returning
1390 * structures is different between Windows and gcc on i386.
1392 * VERSION: [!i386]
1394 #ifndef __i386__
1395 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1397 COORD c;
1398 c.X = 80;
1399 c.Y = 24;
1400 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1401 return c;
1403 #endif /* defined(__i386__) */
1405 static WCHAR* S_EditString /* = NULL */;
1406 static unsigned S_EditStrPos /* = 0 */;
1408 /***********************************************************************
1409 * FreeConsole (KERNEL32.@)
1411 BOOL WINAPI FreeConsole(VOID)
1413 BOOL ret;
1415 /* invalidate local copy of input event handle */
1416 console_wait_event = 0;
1418 SERVER_START_REQ(free_console)
1420 ret = !wine_server_call_err( req );
1422 SERVER_END_REQ;
1423 return ret;
1426 /******************************************************************
1427 * start_console_renderer
1429 * helper for AllocConsole
1430 * starts the renderer process
1432 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1433 HANDLE hEvent)
1435 char buffer[1024];
1436 int ret;
1437 PROCESS_INFORMATION pi;
1439 /* FIXME: use dynamic allocation for most of the buffers below */
1440 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1441 if ((ret > -1) && (ret < sizeof(buffer)) &&
1442 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1443 NULL, NULL, si, &pi))
1445 HANDLE wh[2];
1446 DWORD res;
1448 wh[0] = hEvent;
1449 wh[1] = pi.hProcess;
1450 res = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1452 CloseHandle(pi.hThread);
1453 CloseHandle(pi.hProcess);
1455 if (res != WAIT_OBJECT_0) return FALSE;
1457 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1458 pi.dwProcessId, pi.dwThreadId);
1460 return TRUE;
1462 return FALSE;
1465 static BOOL start_console_renderer(STARTUPINFOA* si)
1467 HANDLE hEvent = 0;
1468 LPSTR p;
1469 OBJECT_ATTRIBUTES attr;
1470 BOOL ret = FALSE;
1472 attr.Length = sizeof(attr);
1473 attr.RootDirectory = 0;
1474 attr.Attributes = OBJ_INHERIT;
1475 attr.ObjectName = NULL;
1476 attr.SecurityDescriptor = NULL;
1477 attr.SecurityQualityOfService = NULL;
1479 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1480 if (!hEvent) return FALSE;
1482 /* first try environment variable */
1483 if ((p = getenv("WINECONSOLE")) != NULL)
1485 ret = start_console_renderer_helper(p, si, hEvent);
1486 if (!ret)
1487 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1488 "trying default access\n", p);
1491 /* then try the regular PATH */
1492 if (!ret)
1493 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1495 CloseHandle(hEvent);
1496 return ret;
1499 /***********************************************************************
1500 * AllocConsole (KERNEL32.@)
1502 * creates an xterm with a pty to our program
1504 BOOL WINAPI AllocConsole(void)
1506 HANDLE handle_in = INVALID_HANDLE_VALUE;
1507 HANDLE handle_out = INVALID_HANDLE_VALUE;
1508 HANDLE handle_err = INVALID_HANDLE_VALUE;
1509 STARTUPINFOA siCurrent;
1510 STARTUPINFOA siConsole;
1511 char buffer[1024];
1513 TRACE("()\n");
1515 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1516 FALSE, OPEN_EXISTING );
1518 if (VerifyConsoleIoHandle(handle_in))
1520 /* we already have a console opened on this process, don't create a new one */
1521 CloseHandle(handle_in);
1522 return FALSE;
1525 /* invalidate local copy of input event handle */
1526 console_wait_event = 0;
1528 GetStartupInfoA(&siCurrent);
1530 memset(&siConsole, 0, sizeof(siConsole));
1531 siConsole.cb = sizeof(siConsole);
1532 /* setup a view arguments for wineconsole (it'll use them as default values) */
1533 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1535 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1536 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1537 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1539 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1541 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1542 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1544 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1546 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1547 siConsole.wShowWindow = siCurrent.wShowWindow;
1549 /* FIXME (should pass the unicode form) */
1550 if (siCurrent.lpTitle)
1551 siConsole.lpTitle = siCurrent.lpTitle;
1552 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1554 buffer[sizeof(buffer) - 1] = '\0';
1555 siConsole.lpTitle = buffer;
1558 if (!start_console_renderer(&siConsole))
1559 goto the_end;
1561 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1562 /* all std I/O handles are inheritable by default */
1563 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1564 TRUE, OPEN_EXISTING );
1565 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1567 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1568 TRUE, OPEN_EXISTING );
1569 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1571 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1572 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1573 goto the_end;
1574 } else {
1575 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1576 handle_in = siCurrent.hStdInput;
1577 handle_out = siCurrent.hStdOutput;
1578 handle_err = siCurrent.hStdError;
1581 /* NT resets the STD_*_HANDLEs on console alloc */
1582 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1583 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1584 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1586 SetLastError(ERROR_SUCCESS);
1588 return TRUE;
1590 the_end:
1591 ERR("Can't allocate console\n");
1592 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1593 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1594 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1595 FreeConsole();
1596 return FALSE;
1600 /***********************************************************************
1601 * ReadConsoleA (KERNEL32.@)
1603 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1604 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1606 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1607 DWORD ncr = 0;
1608 BOOL ret;
1610 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1611 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1613 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1614 HeapFree(GetProcessHeap(), 0, ptr);
1616 return ret;
1619 /***********************************************************************
1620 * ReadConsoleW (KERNEL32.@)
1622 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1623 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1625 DWORD charsread;
1626 LPWSTR xbuf = lpBuffer;
1627 DWORD mode;
1628 BOOL is_bare = FALSE;
1629 int fd;
1631 TRACE("(%p,%p,%d,%p,%p)\n",
1632 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1634 if (!GetConsoleMode(hConsoleInput, &mode))
1635 return FALSE;
1636 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1638 close(fd);
1639 is_bare = TRUE;
1641 if (mode & ENABLE_LINE_INPUT)
1643 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1645 HeapFree(GetProcessHeap(), 0, S_EditString);
1646 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1647 return FALSE;
1648 S_EditStrPos = 0;
1650 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1651 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1652 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1653 S_EditStrPos += charsread;
1655 else
1657 INPUT_RECORD ir;
1658 DWORD timeout = INFINITE;
1660 /* FIXME: should we read at least 1 char? The SDK does not say */
1661 /* wait for at least one available input record (it doesn't mean we'll have
1662 * chars stored in xbuf...)
1664 * Although SDK doc keeps silence about 1 char, SDK examples assume
1665 * that we should wait for at least one character (not key). --KS
1667 charsread = 0;
1670 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1671 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1672 ir.Event.KeyEvent.uChar.UnicodeChar)
1674 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1675 timeout = 0;
1677 } while (charsread < nNumberOfCharsToRead);
1678 /* nothing has been read */
1679 if (timeout == INFINITE) return FALSE;
1682 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1684 return TRUE;
1688 /***********************************************************************
1689 * ReadConsoleInputW (KERNEL32.@)
1691 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1692 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1694 DWORD idx = 0;
1695 DWORD timeout = INFINITE;
1697 if (!nLength)
1699 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1700 return TRUE;
1703 /* loop until we get at least one event */
1704 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1705 ++idx < nLength)
1706 timeout = 0;
1708 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1709 return idx != 0;
1713 /******************************************************************************
1714 * WriteConsoleOutputCharacterW [KERNEL32.@]
1716 * Copy character to consecutive cells in the console screen buffer.
1718 * PARAMS
1719 * hConsoleOutput [I] Handle to screen buffer
1720 * str [I] Pointer to buffer with chars to write
1721 * length [I] Number of cells to write to
1722 * coord [I] Coords of first cell
1723 * lpNumCharsWritten [O] Pointer to number of cells written
1725 * RETURNS
1726 * Success: TRUE
1727 * Failure: FALSE
1730 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1731 COORD coord, LPDWORD lpNumCharsWritten )
1733 BOOL ret;
1735 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1736 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1738 if ((length > 0 && !str) || !lpNumCharsWritten)
1740 SetLastError(ERROR_INVALID_ACCESS);
1741 return FALSE;
1744 *lpNumCharsWritten = 0;
1746 SERVER_START_REQ( write_console_output )
1748 req->handle = console_handle_unmap(hConsoleOutput);
1749 req->x = coord.X;
1750 req->y = coord.Y;
1751 req->mode = CHAR_INFO_MODE_TEXT;
1752 req->wrap = TRUE;
1753 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1754 if ((ret = !wine_server_call_err( req )))
1755 *lpNumCharsWritten = reply->written;
1757 SERVER_END_REQ;
1758 return ret;
1762 /******************************************************************************
1763 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1765 * PARAMS
1766 * title [I] Address of new title
1768 * RETURNS
1769 * Success: TRUE
1770 * Failure: FALSE
1772 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1774 BOOL ret;
1776 TRACE("(%s)\n", debugstr_w(title));
1777 SERVER_START_REQ( set_console_input_info )
1779 req->handle = 0;
1780 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1781 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1782 ret = !wine_server_call_err( req );
1784 SERVER_END_REQ;
1785 return ret;
1789 /***********************************************************************
1790 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1792 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1794 FIXME("(%p): stub\n", nrofbuttons);
1795 *nrofbuttons = 2;
1796 return TRUE;
1799 /******************************************************************************
1800 * SetConsoleInputExeNameW [KERNEL32.@]
1802 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1804 TRACE("(%s)\n", debugstr_w(name));
1806 if (!name || !name[0])
1808 SetLastError(ERROR_INVALID_PARAMETER);
1809 return FALSE;
1812 RtlEnterCriticalSection(&CONSOLE_CritSect);
1813 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1814 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1816 return TRUE;
1819 /******************************************************************************
1820 * SetConsoleInputExeNameA [KERNEL32.@]
1822 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1824 int len;
1825 LPWSTR nameW;
1826 BOOL ret;
1828 if (!name || !name[0])
1830 SetLastError(ERROR_INVALID_PARAMETER);
1831 return FALSE;
1834 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1835 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1837 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1838 ret = SetConsoleInputExeNameW(nameW);
1839 HeapFree(GetProcessHeap(), 0, nameW);
1841 return ret;
1844 /******************************************************************
1845 * CONSOLE_DefaultHandler
1847 * Final control event handler
1849 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1851 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1852 ExitProcess(0);
1853 /* should never go here */
1854 return TRUE;
1857 /******************************************************************************
1858 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1860 * PARAMS
1861 * func [I] Address of handler function
1862 * add [I] Handler to add or remove
1864 * RETURNS
1865 * Success: TRUE
1866 * Failure: FALSE
1869 struct ConsoleHandler
1871 PHANDLER_ROUTINE handler;
1872 struct ConsoleHandler* next;
1875 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1876 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1878 /*****************************************************************************/
1880 /******************************************************************
1881 * SetConsoleCtrlHandler (KERNEL32.@)
1883 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1885 BOOL ret = TRUE;
1887 TRACE("(%p,%i)\n", func, add);
1889 if (!func)
1891 RtlEnterCriticalSection(&CONSOLE_CritSect);
1892 if (add)
1893 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1894 else
1895 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1896 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1898 else if (add)
1900 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1902 if (!ch) return FALSE;
1903 ch->handler = func;
1904 RtlEnterCriticalSection(&CONSOLE_CritSect);
1905 ch->next = CONSOLE_Handlers;
1906 CONSOLE_Handlers = ch;
1907 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1909 else
1911 struct ConsoleHandler** ch;
1912 RtlEnterCriticalSection(&CONSOLE_CritSect);
1913 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1915 if ((*ch)->handler == func) break;
1917 if (*ch)
1919 struct ConsoleHandler* rch = *ch;
1921 /* sanity check */
1922 if (rch == &CONSOLE_DefaultConsoleHandler)
1924 ERR("Who's trying to remove default handler???\n");
1925 SetLastError(ERROR_INVALID_PARAMETER);
1926 ret = FALSE;
1928 else
1930 *ch = rch->next;
1931 HeapFree(GetProcessHeap(), 0, rch);
1934 else
1936 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1937 SetLastError(ERROR_INVALID_PARAMETER);
1938 ret = FALSE;
1940 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1942 return ret;
1945 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1947 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1948 return EXCEPTION_EXECUTE_HANDLER;
1951 /******************************************************************
1952 * CONSOLE_SendEventThread
1954 * Internal helper to pass an event to the list on installed handlers
1956 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1958 DWORD_PTR event = (DWORD_PTR)pmt;
1959 struct ConsoleHandler* ch;
1961 if (event == CTRL_C_EVENT)
1963 BOOL caught_by_dbg = TRUE;
1964 /* First, try to pass the ctrl-C event to the debugger (if any)
1965 * If it continues, there's nothing more to do
1966 * Otherwise, we need to send the ctrl-C event to the handlers
1968 __TRY
1970 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1972 __EXCEPT(CONSOLE_CtrlEventHandler)
1974 caught_by_dbg = FALSE;
1976 __ENDTRY;
1977 if (caught_by_dbg) return 0;
1978 /* the debugger didn't continue... so, pass to ctrl handlers */
1980 RtlEnterCriticalSection(&CONSOLE_CritSect);
1981 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1983 if (ch->handler(event)) break;
1985 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1986 return 1;
1989 /******************************************************************
1990 * CONSOLE_HandleCtrlC
1992 * Check whether the shall manipulate CtrlC events
1994 int CONSOLE_HandleCtrlC(unsigned sig)
1996 HANDLE thread;
1998 /* FIXME: better test whether a console is attached to this process ??? */
1999 extern unsigned CONSOLE_GetNumHistoryEntries(void);
2000 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
2002 /* check if we have to ignore ctrl-C events */
2003 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
2005 /* Create a separate thread to signal all the events.
2006 * This is needed because:
2007 * - this function can be called in an Unix signal handler (hence on an
2008 * different stack than the thread that's running). This breaks the
2009 * Win32 exception mechanisms (where the thread's stack is checked).
2010 * - since the current thread, while processing the signal, can hold the
2011 * console critical section, we need another execution environment where
2012 * we can wait on this critical section
2014 thread = CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2015 if (thread == NULL)
2016 return 0;
2018 CloseHandle(thread);
2020 return 1;
2023 /******************************************************************************
2024 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2026 * PARAMS
2027 * dwCtrlEvent [I] Type of event
2028 * dwProcessGroupID [I] Process group ID to send event to
2030 * RETURNS
2031 * Success: True
2032 * Failure: False (and *should* [but doesn't] set LastError)
2034 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2035 DWORD dwProcessGroupID)
2037 BOOL ret;
2039 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2041 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2043 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2044 return FALSE;
2047 SERVER_START_REQ( send_console_signal )
2049 req->signal = dwCtrlEvent;
2050 req->group_id = dwProcessGroupID;
2051 ret = !wine_server_call_err( req );
2053 SERVER_END_REQ;
2055 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2056 * have been handled by all processes in the given group?
2057 * As of today, we don't wait...
2059 return ret;
2063 /******************************************************************************
2064 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2066 * PARAMS
2067 * dwDesiredAccess [I] Access flag
2068 * dwShareMode [I] Buffer share mode
2069 * sa [I] Security attributes
2070 * dwFlags [I] Type of buffer to create
2071 * lpScreenBufferData [I] Reserved
2073 * NOTES
2074 * Should call SetLastError
2076 * RETURNS
2077 * Success: Handle to new console screen buffer
2078 * Failure: INVALID_HANDLE_VALUE
2080 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2081 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2082 LPVOID lpScreenBufferData)
2084 HANDLE ret = INVALID_HANDLE_VALUE;
2086 TRACE("(%d,%d,%p,%d,%p)\n",
2087 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2089 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2091 SetLastError(ERROR_INVALID_PARAMETER);
2092 return INVALID_HANDLE_VALUE;
2095 SERVER_START_REQ(create_console_output)
2097 req->handle_in = 0;
2098 req->access = dwDesiredAccess;
2099 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2100 req->share = dwShareMode;
2101 req->fd = -1;
2102 if (!wine_server_call_err( req ))
2103 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2105 SERVER_END_REQ;
2107 return ret;
2111 /***********************************************************************
2112 * GetConsoleScreenBufferInfo (KERNEL32.@)
2114 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2116 BOOL ret;
2118 SERVER_START_REQ(get_console_output_info)
2120 req->handle = console_handle_unmap(hConsoleOutput);
2121 if ((ret = !wine_server_call_err( req )))
2123 csbi->dwSize.X = reply->width;
2124 csbi->dwSize.Y = reply->height;
2125 csbi->dwCursorPosition.X = reply->cursor_x;
2126 csbi->dwCursorPosition.Y = reply->cursor_y;
2127 csbi->wAttributes = reply->attr;
2128 csbi->srWindow.Left = reply->win_left;
2129 csbi->srWindow.Right = reply->win_right;
2130 csbi->srWindow.Top = reply->win_top;
2131 csbi->srWindow.Bottom = reply->win_bottom;
2132 csbi->dwMaximumWindowSize.X = reply->max_width;
2133 csbi->dwMaximumWindowSize.Y = reply->max_height;
2136 SERVER_END_REQ;
2138 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2139 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2140 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2141 csbi->wAttributes,
2142 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2143 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2145 return ret;
2149 /******************************************************************************
2150 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2152 * RETURNS
2153 * Success: TRUE
2154 * Failure: FALSE
2156 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2158 BOOL ret;
2160 TRACE("(%p)\n", hConsoleOutput);
2162 SERVER_START_REQ( set_console_input_info )
2164 req->handle = 0;
2165 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2166 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2167 ret = !wine_server_call_err( req );
2169 SERVER_END_REQ;
2170 return ret;
2174 /***********************************************************************
2175 * GetConsoleMode (KERNEL32.@)
2177 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2179 BOOL ret;
2181 SERVER_START_REQ( get_console_mode )
2183 req->handle = console_handle_unmap(hcon);
2184 if ((ret = !wine_server_call_err( req )))
2186 if (mode) *mode = reply->mode;
2189 SERVER_END_REQ;
2190 return ret;
2194 /******************************************************************************
2195 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2197 * PARAMS
2198 * hcon [I] Handle to console input or screen buffer
2199 * mode [I] Input or output mode to set
2201 * RETURNS
2202 * Success: TRUE
2203 * Failure: FALSE
2205 * mode:
2206 * ENABLE_PROCESSED_INPUT 0x01
2207 * ENABLE_LINE_INPUT 0x02
2208 * ENABLE_ECHO_INPUT 0x04
2209 * ENABLE_WINDOW_INPUT 0x08
2210 * ENABLE_MOUSE_INPUT 0x10
2212 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2214 BOOL ret;
2216 SERVER_START_REQ(set_console_mode)
2218 req->handle = console_handle_unmap(hcon);
2219 req->mode = mode;
2220 ret = !wine_server_call_err( req );
2222 SERVER_END_REQ;
2223 /* FIXME: when resetting a console input to editline mode, I think we should
2224 * empty the S_EditString buffer
2227 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2229 return ret;
2233 /******************************************************************
2234 * CONSOLE_WriteChars
2236 * WriteConsoleOutput helper: hides server call semantics
2237 * writes a string at a given pos with standard attribute
2239 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2241 int written = -1;
2243 if (!nc) return 0;
2245 SERVER_START_REQ( write_console_output )
2247 req->handle = console_handle_unmap(hCon);
2248 req->x = pos->X;
2249 req->y = pos->Y;
2250 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2251 req->wrap = FALSE;
2252 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2253 if (!wine_server_call_err( req )) written = reply->written;
2255 SERVER_END_REQ;
2257 if (written > 0) pos->X += written;
2258 return written;
2261 /******************************************************************
2262 * next_line
2264 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2267 static BOOL next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2269 SMALL_RECT src;
2270 CHAR_INFO ci;
2271 COORD dst;
2273 csbi->dwCursorPosition.X = 0;
2274 csbi->dwCursorPosition.Y++;
2276 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return TRUE;
2278 src.Top = 1;
2279 src.Bottom = csbi->dwSize.Y - 1;
2280 src.Left = 0;
2281 src.Right = csbi->dwSize.X - 1;
2283 dst.X = 0;
2284 dst.Y = 0;
2286 ci.Attributes = csbi->wAttributes;
2287 ci.Char.UnicodeChar = ' ';
2289 csbi->dwCursorPosition.Y--;
2290 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2291 return FALSE;
2292 return TRUE;
2295 /******************************************************************
2296 * write_block
2298 * WriteConsoleOutput helper: writes a block of non special characters
2299 * Block can spread on several lines, and wrapping, if needed, is
2300 * handled
2303 static BOOL write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2304 DWORD mode, LPCWSTR ptr, int len)
2306 int blk; /* number of chars to write on current line */
2307 int done; /* number of chars already written */
2309 if (len <= 0) return TRUE;
2311 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2313 for (done = 0; done < len; done += blk)
2315 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2317 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2318 return FALSE;
2319 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2320 return FALSE;
2323 else
2325 int pos = csbi->dwCursorPosition.X;
2326 /* FIXME: we could reduce the number of loops
2327 * but, in most cases we wouldn't gain lots of time (it would only
2328 * happen if we're asked to overwrite more than twice the part of the line,
2329 * which is unlikely
2331 for (done = 0; done < len; done += blk)
2333 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2335 csbi->dwCursorPosition.X = pos;
2336 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2337 return FALSE;
2341 return TRUE;
2344 /***********************************************************************
2345 * WriteConsoleW (KERNEL32.@)
2347 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2348 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2350 DWORD mode;
2351 DWORD nw = 0;
2352 const WCHAR* psz = lpBuffer;
2353 CONSOLE_SCREEN_BUFFER_INFO csbi;
2354 int k, first = 0, fd;
2356 TRACE("%p %s %d %p %p\n",
2357 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2358 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2360 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2362 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2364 char* ptr;
2365 unsigned len;
2366 HANDLE hFile;
2367 NTSTATUS status;
2368 IO_STATUS_BLOCK iosb;
2370 close(fd);
2371 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2372 * to do the job
2374 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2375 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2376 return FALSE;
2378 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2379 hFile = wine_server_ptr_handle(console_handle_unmap(hConsoleOutput));
2380 status = NtWriteFile(hFile, NULL, NULL, NULL, &iosb, ptr, len, 0, NULL);
2381 if (status == STATUS_PENDING)
2383 WaitForSingleObject(hFile, INFINITE);
2384 status = iosb.u.Status;
2387 if (status != STATUS_PENDING && lpNumberOfCharsWritten)
2389 if (iosb.Information == len)
2390 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2391 else
2392 FIXME("Conversion not supported yet\n");
2394 HeapFree(GetProcessHeap(), 0, ptr);
2395 if (status != STATUS_SUCCESS)
2397 SetLastError(RtlNtStatusToDosError(status));
2398 return FALSE;
2400 return TRUE;
2403 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2404 return FALSE;
2406 if (!nNumberOfCharsToWrite) return TRUE;
2408 if (mode & ENABLE_PROCESSED_OUTPUT)
2410 unsigned int i;
2412 for (i = 0; i < nNumberOfCharsToWrite; i++)
2414 switch (psz[i])
2416 case '\b': case '\t': case '\n': case '\a': case '\r':
2417 /* don't handle here the i-th char... done below */
2418 if ((k = i - first) > 0)
2420 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2421 goto the_end;
2422 nw += k;
2424 first = i + 1;
2425 nw++;
2427 switch (psz[i])
2429 case '\b':
2430 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2431 break;
2432 case '\t':
2434 static const WCHAR tmp[] = {' ',' ',' ',' ',' ',' ',' ',' '};
2435 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2436 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2437 goto the_end;
2439 break;
2440 case '\n':
2441 next_line(hConsoleOutput, &csbi);
2442 break;
2443 case '\a':
2444 Beep(400, 300);
2445 break;
2446 case '\r':
2447 csbi.dwCursorPosition.X = 0;
2448 break;
2449 default:
2450 break;
2455 /* write the remaining block (if any) if processed output is enabled, or the
2456 * entire buffer otherwise
2458 if ((k = nNumberOfCharsToWrite - first) > 0)
2460 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2461 goto the_end;
2462 nw += k;
2465 the_end:
2466 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2467 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2468 return nw != 0;
2472 /***********************************************************************
2473 * WriteConsoleA (KERNEL32.@)
2475 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2476 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2478 BOOL ret;
2479 LPWSTR xstring;
2480 DWORD n;
2482 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2484 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2485 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2486 if (!xstring) return FALSE;
2488 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2490 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2492 HeapFree(GetProcessHeap(), 0, xstring);
2494 return ret;
2497 /******************************************************************************
2498 * SetConsoleCursorPosition [KERNEL32.@]
2499 * Sets the cursor position in console
2501 * PARAMS
2502 * hConsoleOutput [I] Handle of console screen buffer
2503 * dwCursorPosition [I] New cursor position coordinates
2505 * RETURNS
2506 * Success: TRUE
2507 * Failure: FALSE
2509 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2511 BOOL ret;
2512 CONSOLE_SCREEN_BUFFER_INFO csbi;
2513 int do_move = 0;
2514 int w, h;
2516 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2518 SERVER_START_REQ(set_console_output_info)
2520 req->handle = console_handle_unmap(hcon);
2521 req->cursor_x = pos.X;
2522 req->cursor_y = pos.Y;
2523 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2524 ret = !wine_server_call_err( req );
2526 SERVER_END_REQ;
2528 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2529 return FALSE;
2531 /* if cursor is no longer visible, scroll the visible window... */
2532 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2533 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2534 if (pos.X < csbi.srWindow.Left)
2536 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2537 do_move++;
2539 else if (pos.X > csbi.srWindow.Right)
2541 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2542 do_move++;
2544 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2546 if (pos.Y < csbi.srWindow.Top)
2548 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2549 do_move++;
2551 else if (pos.Y > csbi.srWindow.Bottom)
2553 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2554 do_move++;
2556 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2558 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2560 return ret;
2563 /******************************************************************************
2564 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2566 * PARAMS
2567 * hcon [I] Handle to console screen buffer
2568 * cinfo [O] Address of cursor information
2570 * RETURNS
2571 * Success: TRUE
2572 * Failure: FALSE
2574 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2576 BOOL ret;
2578 SERVER_START_REQ(get_console_output_info)
2580 req->handle = console_handle_unmap(hCon);
2581 ret = !wine_server_call_err( req );
2582 if (ret && cinfo)
2584 cinfo->dwSize = reply->cursor_size;
2585 cinfo->bVisible = reply->cursor_visible;
2588 SERVER_END_REQ;
2590 if (!ret) return FALSE;
2592 if (!cinfo)
2594 SetLastError(ERROR_INVALID_ACCESS);
2595 ret = FALSE;
2597 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2599 return ret;
2603 /******************************************************************************
2604 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2606 * PARAMS
2607 * hcon [I] Handle to console screen buffer
2608 * cinfo [I] Address of cursor information
2609 * RETURNS
2610 * Success: TRUE
2611 * Failure: FALSE
2613 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2615 BOOL ret;
2617 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2618 SERVER_START_REQ(set_console_output_info)
2620 req->handle = console_handle_unmap(hCon);
2621 req->cursor_size = cinfo->dwSize;
2622 req->cursor_visible = cinfo->bVisible;
2623 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2624 ret = !wine_server_call_err( req );
2626 SERVER_END_REQ;
2627 return ret;
2631 /******************************************************************************
2632 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2634 * PARAMS
2635 * hcon [I] Handle to console screen buffer
2636 * bAbsolute [I] Coordinate type flag
2637 * window [I] Address of new window rectangle
2638 * RETURNS
2639 * Success: TRUE
2640 * Failure: FALSE
2642 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2644 SMALL_RECT p = *window;
2645 BOOL ret;
2647 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2649 if (!bAbsolute)
2651 CONSOLE_SCREEN_BUFFER_INFO csbi;
2653 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2654 return FALSE;
2655 p.Left += csbi.srWindow.Left;
2656 p.Top += csbi.srWindow.Top;
2657 p.Right += csbi.srWindow.Right;
2658 p.Bottom += csbi.srWindow.Bottom;
2660 SERVER_START_REQ(set_console_output_info)
2662 req->handle = console_handle_unmap(hCon);
2663 req->win_left = p.Left;
2664 req->win_top = p.Top;
2665 req->win_right = p.Right;
2666 req->win_bottom = p.Bottom;
2667 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2668 ret = !wine_server_call_err( req );
2670 SERVER_END_REQ;
2672 return ret;
2676 /******************************************************************************
2677 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2679 * Sets the foreground and background color attributes of characters
2680 * written to the screen buffer.
2682 * RETURNS
2683 * Success: TRUE
2684 * Failure: FALSE
2686 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2688 BOOL ret;
2690 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2691 SERVER_START_REQ(set_console_output_info)
2693 req->handle = console_handle_unmap(hConsoleOutput);
2694 req->attr = wAttr;
2695 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2696 ret = !wine_server_call_err( req );
2698 SERVER_END_REQ;
2699 return ret;
2703 /******************************************************************************
2704 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2706 * PARAMS
2707 * hConsoleOutput [I] Handle to console screen buffer
2708 * dwSize [I] New size in character rows and cols
2710 * RETURNS
2711 * Success: TRUE
2712 * Failure: FALSE
2714 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2716 BOOL ret;
2718 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2719 SERVER_START_REQ(set_console_output_info)
2721 req->handle = console_handle_unmap(hConsoleOutput);
2722 req->width = dwSize.X;
2723 req->height = dwSize.Y;
2724 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2725 ret = !wine_server_call_err( req );
2727 SERVER_END_REQ;
2728 return ret;
2732 /******************************************************************************
2733 * ScrollConsoleScreenBufferA [KERNEL32.@]
2736 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2737 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2738 LPCHAR_INFO lpFill)
2740 CHAR_INFO ciw;
2742 ciw.Attributes = lpFill->Attributes;
2743 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2745 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2746 dwDestOrigin, &ciw);
2749 /******************************************************************
2750 * CONSOLE_FillLineUniform
2752 * Helper function for ScrollConsoleScreenBufferW
2753 * Fills a part of a line with a constant character info
2755 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2757 SERVER_START_REQ( fill_console_output )
2759 req->handle = console_handle_unmap(hConsoleOutput);
2760 req->mode = CHAR_INFO_MODE_TEXTATTR;
2761 req->x = i;
2762 req->y = j;
2763 req->count = len;
2764 req->wrap = FALSE;
2765 req->data.ch = lpFill->Char.UnicodeChar;
2766 req->data.attr = lpFill->Attributes;
2767 wine_server_call_err( req );
2769 SERVER_END_REQ;
2772 /******************************************************************************
2773 * ScrollConsoleScreenBufferW [KERNEL32.@]
2777 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2778 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2779 LPCHAR_INFO lpFill)
2781 SMALL_RECT dst;
2782 DWORD ret;
2783 int i, j;
2784 int start = -1;
2785 SMALL_RECT clip;
2786 CONSOLE_SCREEN_BUFFER_INFO csbi;
2787 BOOL inside;
2788 COORD src;
2790 if (lpClipRect)
2791 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2792 lpScrollRect->Left, lpScrollRect->Top,
2793 lpScrollRect->Right, lpScrollRect->Bottom,
2794 lpClipRect->Left, lpClipRect->Top,
2795 lpClipRect->Right, lpClipRect->Bottom,
2796 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2797 else
2798 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2799 lpScrollRect->Left, lpScrollRect->Top,
2800 lpScrollRect->Right, lpScrollRect->Bottom,
2801 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2803 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2804 return FALSE;
2806 src.X = lpScrollRect->Left;
2807 src.Y = lpScrollRect->Top;
2809 /* step 1: get dst rect */
2810 dst.Left = dwDestOrigin.X;
2811 dst.Top = dwDestOrigin.Y;
2812 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2813 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2815 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2816 if (lpClipRect)
2818 clip.Left = max(0, lpClipRect->Left);
2819 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2820 clip.Top = max(0, lpClipRect->Top);
2821 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2823 else
2825 clip.Left = 0;
2826 clip.Right = csbi.dwSize.X - 1;
2827 clip.Top = 0;
2828 clip.Bottom = csbi.dwSize.Y - 1;
2830 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2832 /* step 2b: clip dst rect */
2833 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2834 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2835 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2836 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2838 /* step 3: transfer the bits */
2839 SERVER_START_REQ(move_console_output)
2841 req->handle = console_handle_unmap(hConsoleOutput);
2842 req->x_src = src.X;
2843 req->y_src = src.Y;
2844 req->x_dst = dst.Left;
2845 req->y_dst = dst.Top;
2846 req->w = dst.Right - dst.Left + 1;
2847 req->h = dst.Bottom - dst.Top + 1;
2848 ret = !wine_server_call_err( req );
2850 SERVER_END_REQ;
2852 if (!ret) return FALSE;
2854 /* step 4: clean out the exposed part */
2856 /* have to write cell [i,j] if it is not in dst rect (because it has already
2857 * been written to by the scroll) and is in clip (we shall not write
2858 * outside of clip)
2860 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2862 inside = dst.Top <= j && j <= dst.Bottom;
2863 start = -1;
2864 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2866 if (inside && dst.Left <= i && i <= dst.Right)
2868 if (start != -1)
2870 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2871 start = -1;
2874 else
2876 if (start == -1) start = i;
2879 if (start != -1)
2880 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2883 return TRUE;
2886 /******************************************************************
2887 * AttachConsole (KERNEL32.@)
2889 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2891 FIXME("stub %x\n",dwProcessId);
2892 return TRUE;
2895 /******************************************************************
2896 * GetConsoleDisplayMode (KERNEL32.@)
2898 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2900 TRACE("semi-stub: %p\n", lpModeFlags);
2901 /* It is safe to successfully report windowed mode */
2902 *lpModeFlags = 0;
2903 return TRUE;
2906 /******************************************************************
2907 * SetConsoleDisplayMode (KERNEL32.@)
2909 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2910 COORD *lpNewScreenBufferDimensions)
2912 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2913 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2914 if (dwFlags == 1)
2916 /* We cannot switch to fullscreen */
2917 return FALSE;
2919 return TRUE;
2923 /* ====================================================================
2925 * Console manipulation functions
2927 * ====================================================================*/
2929 /* some missing functions...
2930 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2931 * should get the right API and implement them
2932 * SetConsoleCommandHistoryMode
2933 * SetConsoleNumberOfCommands[AW]
2935 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2937 int len = 0;
2939 SERVER_START_REQ( get_console_input_history )
2941 req->handle = 0;
2942 req->index = idx;
2943 if (buf && buf_len > 1)
2945 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2947 if (!wine_server_call_err( req ))
2949 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2950 len = reply->total / sizeof(WCHAR) + 1;
2953 SERVER_END_REQ;
2954 return len;
2957 /******************************************************************
2958 * CONSOLE_AppendHistory
2962 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2964 size_t len = strlenW(ptr);
2965 BOOL ret;
2967 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2968 if (!len) return FALSE;
2970 SERVER_START_REQ( append_console_input_history )
2972 req->handle = 0;
2973 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2974 ret = !wine_server_call_err( req );
2976 SERVER_END_REQ;
2977 return ret;
2980 /******************************************************************
2981 * CONSOLE_GetNumHistoryEntries
2985 unsigned CONSOLE_GetNumHistoryEntries(void)
2987 unsigned ret = -1;
2988 SERVER_START_REQ(get_console_input_info)
2990 req->handle = 0;
2991 if (!wine_server_call_err( req )) ret = reply->history_index;
2993 SERVER_END_REQ;
2994 return ret;
2997 /******************************************************************
2998 * CONSOLE_GetEditionMode
3002 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
3004 unsigned ret = 0;
3005 SERVER_START_REQ(get_console_input_info)
3007 req->handle = console_handle_unmap(hConIn);
3008 if ((ret = !wine_server_call_err( req )))
3009 *mode = reply->edition_mode;
3011 SERVER_END_REQ;
3012 return ret;
3015 /******************************************************************
3016 * GetConsoleAliasW
3019 * RETURNS
3020 * 0 if an error occurred, non-zero for success
3023 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3024 DWORD TargetBufferLength, LPWSTR lpExename)
3026 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3027 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3028 return 0;
3031 /******************************************************************
3032 * GetConsoleProcessList (KERNEL32.@)
3034 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3036 FIXME("(%p,%d): stub\n", processlist, processcount);
3038 if (!processlist || processcount < 1)
3040 SetLastError(ERROR_INVALID_PARAMETER);
3041 return 0;
3044 return 0;
3047 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3049 memset(&S_termios, 0, sizeof(S_termios));
3050 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3052 HANDLE conin;
3054 /* FIXME: to be done even if program is a GUI ? */
3055 /* This is wine specific: we have no parent (we're started from unix)
3056 * so, create a simple console with bare handles
3058 TERM_Init();
3059 wine_server_send_fd(0);
3060 SERVER_START_REQ( alloc_console )
3062 req->access = GENERIC_READ | GENERIC_WRITE;
3063 req->attributes = OBJ_INHERIT;
3064 req->pid = 0xffffffff;
3065 req->input_fd = 0;
3066 wine_server_call( req );
3067 conin = wine_server_ptr_handle( reply->handle_in );
3068 /* reply->event shouldn't be created by server */
3070 SERVER_END_REQ;
3072 if (!params->hStdInput)
3073 params->hStdInput = conin;
3075 if (!params->hStdOutput)
3077 wine_server_send_fd(1);
3078 SERVER_START_REQ( create_console_output )
3080 req->handle_in = wine_server_obj_handle(conin);
3081 req->access = GENERIC_WRITE|GENERIC_READ;
3082 req->attributes = OBJ_INHERIT;
3083 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3084 req->fd = 1;
3085 wine_server_call(req);
3086 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3088 SERVER_END_REQ;
3090 if (!params->hStdError)
3092 wine_server_send_fd(2);
3093 SERVER_START_REQ( create_console_output )
3095 req->handle_in = wine_server_obj_handle(conin);
3096 req->access = GENERIC_WRITE|GENERIC_READ;
3097 req->attributes = OBJ_INHERIT;
3098 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3099 req->fd = 2;
3100 wine_server_call(req);
3101 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3103 SERVER_END_REQ;
3107 /* convert value from server:
3108 * + 0 => INVALID_HANDLE_VALUE
3109 * + console handle needs to be mapped
3111 if (!params->hStdInput)
3112 params->hStdInput = INVALID_HANDLE_VALUE;
3113 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3115 params->hStdInput = console_handle_map(params->hStdInput);
3116 save_console_mode(params->hStdInput);
3119 if (!params->hStdOutput)
3120 params->hStdOutput = INVALID_HANDLE_VALUE;
3121 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3122 params->hStdOutput = console_handle_map(params->hStdOutput);
3124 if (!params->hStdError)
3125 params->hStdError = INVALID_HANDLE_VALUE;
3126 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3127 params->hStdError = console_handle_map(params->hStdError);
3129 return TRUE;
3132 BOOL CONSOLE_Exit(void)
3134 /* the console is in raw mode, put it back in cooked mode */
3135 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));
3138 /* Undocumented, called by native doskey.exe */
3139 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3140 DWORD WINAPI GetConsoleCommandHistoryA(DWORD unknown1, DWORD unknown2, DWORD unknown3)
3142 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
3143 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3144 return 0;
3147 /* Undocumented, called by native doskey.exe */
3148 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3149 DWORD WINAPI GetConsoleCommandHistoryW(DWORD unknown1, DWORD unknown2, DWORD unknown3)
3151 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
3152 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3153 return 0;
3156 /* Undocumented, called by native doskey.exe */
3157 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3158 DWORD WINAPI GetConsoleCommandHistoryLengthA(LPCSTR unknown)
3160 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3161 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3162 return 0;
3165 /* Undocumented, called by native doskey.exe */
3166 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3167 DWORD WINAPI GetConsoleCommandHistoryLengthW(LPCWSTR unknown)
3169 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3170 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3171 return 0;
3174 DWORD WINAPI GetConsoleAliasesLengthA(LPSTR unknown)
3176 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3177 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3178 return 0;
3181 DWORD WINAPI GetConsoleAliasesLengthW(LPWSTR unknown)
3183 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3184 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3185 return 0;
3188 VOID WINAPI ExpungeConsoleCommandHistoryA(LPCSTR unknown)
3190 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3191 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3194 VOID WINAPI ExpungeConsoleCommandHistoryW(LPCWSTR unknown)
3196 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3197 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3200 BOOL WINAPI AddConsoleAliasA(LPSTR source, LPSTR target, LPSTR exename)
3202 FIXME(": (%s, %s, %s) stub!\n", debugstr_a(source), debugstr_a(target), debugstr_a(exename));
3203 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3204 return FALSE;
3207 BOOL WINAPI AddConsoleAliasW(LPWSTR source, LPWSTR target, LPWSTR exename)
3209 FIXME(": (%s, %s, %s) stub!\n", debugstr_w(source), debugstr_w(target), debugstr_w(exename));
3210 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3211 return FALSE;
3215 BOOL WINAPI SetConsoleIcon(HICON icon)
3217 FIXME(": (%p) stub!\n", icon);
3218 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3219 return FALSE;
3222 BOOL WINAPI GetCurrentConsoleFont(HANDLE hConsole, BOOL maxwindow, LPCONSOLE_FONT_INFO fontinfo)
3224 FIXME(": (%p, %d, %p) stub!\n", hConsole, maxwindow, fontinfo);
3225 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3226 return FALSE;
3229 #ifdef __i386__
3230 #undef GetConsoleFontSize
3231 DWORD WINAPI GetConsoleFontSize(HANDLE hConsole, DWORD font)
3233 union {
3234 COORD c;
3235 DWORD w;
3236 } x;
3238 FIXME(": (%p, %d) stub!\n", hConsole, font);
3239 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3241 x.c.X = 0;
3242 x.c.Y = 0;
3243 return x.w;
3245 #endif /* defined(__i386__) */
3248 #ifndef __i386__
3249 COORD WINAPI GetConsoleFontSize(HANDLE hConsole, DWORD font)
3251 COORD c;
3252 c.X = 80;
3253 c.Y = 24;
3254 FIXME(": (%p, %d) stub!\n", hConsole, font);
3255 return c;
3257 #endif /* defined(__i386__) */