d3drm: Implement IDirect3DRMMesh_GetVertices.
[wine/multimedia.git] / dlls / kernel32 / console.c
blob4410a31badbc7108bcffa30f499c044dd770f3ed
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)
387 SetLastError(ERROR_INVALID_PARAMETER);
388 return INVALID_HANDLE_VALUE;
390 else if (creation != OPEN_EXISTING)
392 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
393 SetLastError(ERROR_SHARING_VIOLATION);
394 else
395 SetLastError(ERROR_INVALID_PARAMETER);
396 return INVALID_HANDLE_VALUE;
399 SERVER_START_REQ( open_console )
401 req->from = wine_server_obj_handle( output );
402 req->access = access;
403 req->attributes = inherit ? OBJ_INHERIT : 0;
404 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
405 wine_server_call_err( req );
406 ret = wine_server_ptr_handle( reply->handle );
408 SERVER_END_REQ;
409 if (ret)
410 ret = console_handle_map(ret);
412 return ret;
415 /******************************************************************
416 * VerifyConsoleIoHandle (KERNEL32.@)
418 * Undocumented
420 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
422 BOOL ret;
424 if (!is_console_handle(handle)) return FALSE;
425 SERVER_START_REQ(get_console_mode)
427 req->handle = console_handle_unmap(handle);
428 ret = !wine_server_call( req );
430 SERVER_END_REQ;
431 return ret;
434 /******************************************************************
435 * DuplicateConsoleHandle (KERNEL32.@)
437 * Undocumented
439 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
440 DWORD options)
442 HANDLE ret;
444 if (!is_console_handle(handle) ||
445 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
446 GetCurrentProcess(), &ret, access, inherit, options))
447 return INVALID_HANDLE_VALUE;
448 return console_handle_map(ret);
451 /******************************************************************
452 * CloseConsoleHandle (KERNEL32.@)
454 * Undocumented
456 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
458 if (!is_console_handle(handle))
460 SetLastError(ERROR_INVALID_PARAMETER);
461 return FALSE;
463 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
466 /******************************************************************
467 * GetConsoleInputWaitHandle (KERNEL32.@)
469 * Undocumented
471 HANDLE WINAPI GetConsoleInputWaitHandle(void)
473 if (!console_wait_event)
475 SERVER_START_REQ(get_console_wait_event)
477 if (!wine_server_call_err( req ))
478 console_wait_event = wine_server_ptr_handle( reply->handle );
480 SERVER_END_REQ;
482 return console_wait_event;
486 /******************************************************************************
487 * WriteConsoleInputA [KERNEL32.@]
489 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
490 DWORD count, LPDWORD written )
492 INPUT_RECORD *recW = NULL;
493 BOOL ret;
495 if (count > 0)
497 if (!buffer)
499 SetLastError( ERROR_INVALID_ACCESS );
500 return FALSE;
503 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) )))
505 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
506 return FALSE;
509 memcpy( recW, buffer, count * sizeof(*recW) );
510 input_records_AtoW( recW, count );
513 ret = WriteConsoleInputW( handle, recW, count, written );
514 HeapFree( GetProcessHeap(), 0, recW );
515 return ret;
519 /******************************************************************************
520 * WriteConsoleInputW [KERNEL32.@]
522 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
523 DWORD count, LPDWORD written )
525 DWORD events_written = 0;
526 BOOL ret;
528 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
530 if (count > 0 && !buffer)
532 SetLastError(ERROR_INVALID_ACCESS);
533 return FALSE;
536 SERVER_START_REQ( write_console_input )
538 req->handle = console_handle_unmap(handle);
539 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
540 if ((ret = !wine_server_call_err( req )))
541 events_written = reply->written;
543 SERVER_END_REQ;
545 if (written) *written = events_written;
546 else
548 SetLastError(ERROR_INVALID_ACCESS);
549 ret = FALSE;
551 return ret;
555 /***********************************************************************
556 * WriteConsoleOutputA (KERNEL32.@)
558 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
559 COORD size, COORD coord, LPSMALL_RECT region )
561 int y;
562 BOOL ret;
563 COORD new_size, new_coord;
564 CHAR_INFO *ciw;
566 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
567 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
569 if (new_size.X <= 0 || new_size.Y <= 0)
571 region->Bottom = region->Top + new_size.Y - 1;
572 region->Right = region->Left + new_size.X - 1;
573 return TRUE;
576 /* only copy the useful rectangle */
577 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
578 return FALSE;
579 for (y = 0; y < new_size.Y; y++)
581 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
582 new_size.X * sizeof(CHAR_INFO) );
583 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
585 new_coord.X = new_coord.Y = 0;
586 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
587 HeapFree( GetProcessHeap(), 0, ciw );
588 return ret;
592 /***********************************************************************
593 * WriteConsoleOutputW (KERNEL32.@)
595 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
596 COORD size, COORD coord, LPSMALL_RECT region )
598 int width, height, y;
599 BOOL ret = TRUE;
601 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
602 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
603 region->Left, region->Top, region->Right, region->Bottom);
605 width = min( region->Right - region->Left + 1, size.X - coord.X );
606 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
608 if (width > 0 && height > 0)
610 for (y = 0; y < height; y++)
612 SERVER_START_REQ( write_console_output )
614 req->handle = console_handle_unmap(hConsoleOutput);
615 req->x = region->Left;
616 req->y = region->Top + y;
617 req->mode = CHAR_INFO_MODE_TEXTATTR;
618 req->wrap = FALSE;
619 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
620 width * sizeof(CHAR_INFO));
621 if ((ret = !wine_server_call_err( req )))
623 width = min( width, reply->width - region->Left );
624 height = min( height, reply->height - region->Top );
627 SERVER_END_REQ;
628 if (!ret) break;
631 region->Bottom = region->Top + height - 1;
632 region->Right = region->Left + width - 1;
633 return ret;
637 /******************************************************************************
638 * WriteConsoleOutputCharacterA [KERNEL32.@]
640 * See WriteConsoleOutputCharacterW.
642 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
643 COORD coord, LPDWORD lpNumCharsWritten )
645 BOOL ret;
646 LPWSTR strW = NULL;
647 DWORD lenW = 0;
649 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
650 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
652 if (length > 0)
654 if (!str)
656 SetLastError( ERROR_INVALID_ACCESS );
657 return FALSE;
660 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
662 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
664 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
665 return FALSE;
668 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
671 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
672 HeapFree( GetProcessHeap(), 0, strW );
673 return ret;
677 /******************************************************************************
678 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
679 * the console screen buffer
681 * PARAMS
682 * hConsoleOutput [I] Handle to screen buffer
683 * attr [I] Pointer to buffer with write attributes
684 * length [I] Number of cells to write to
685 * coord [I] Coords of first cell
686 * lpNumAttrsWritten [O] Pointer to number of cells written
688 * RETURNS
689 * Success: TRUE
690 * Failure: FALSE
693 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
694 COORD coord, LPDWORD lpNumAttrsWritten )
696 BOOL ret;
698 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
700 if ((length > 0 && !attr) || !lpNumAttrsWritten)
702 SetLastError(ERROR_INVALID_ACCESS);
703 return FALSE;
706 *lpNumAttrsWritten = 0;
708 SERVER_START_REQ( write_console_output )
710 req->handle = console_handle_unmap(hConsoleOutput);
711 req->x = coord.X;
712 req->y = coord.Y;
713 req->mode = CHAR_INFO_MODE_ATTR;
714 req->wrap = TRUE;
715 wine_server_add_data( req, attr, length * sizeof(WORD) );
716 if ((ret = !wine_server_call_err( req )))
717 *lpNumAttrsWritten = reply->written;
719 SERVER_END_REQ;
720 return ret;
724 /******************************************************************************
725 * FillConsoleOutputCharacterA [KERNEL32.@]
727 * See FillConsoleOutputCharacterW.
729 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
730 COORD coord, LPDWORD lpNumCharsWritten )
732 WCHAR wch;
734 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
735 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
739 /******************************************************************************
740 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
742 * PARAMS
743 * hConsoleOutput [I] Handle to screen buffer
744 * ch [I] Character to write
745 * length [I] Number of cells to write to
746 * coord [I] Coords of first cell
747 * lpNumCharsWritten [O] Pointer to number of cells written
749 * RETURNS
750 * Success: TRUE
751 * Failure: FALSE
753 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
754 COORD coord, LPDWORD lpNumCharsWritten)
756 BOOL ret;
758 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
759 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
761 if (!lpNumCharsWritten)
763 SetLastError(ERROR_INVALID_ACCESS);
764 return FALSE;
767 *lpNumCharsWritten = 0;
769 SERVER_START_REQ( fill_console_output )
771 req->handle = console_handle_unmap(hConsoleOutput);
772 req->x = coord.X;
773 req->y = coord.Y;
774 req->mode = CHAR_INFO_MODE_TEXT;
775 req->wrap = TRUE;
776 req->data.ch = ch;
777 req->count = length;
778 if ((ret = !wine_server_call_err( req )))
779 *lpNumCharsWritten = reply->written;
781 SERVER_END_REQ;
782 return ret;
786 /******************************************************************************
787 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
789 * PARAMS
790 * hConsoleOutput [I] Handle to screen buffer
791 * attr [I] Color attribute to write
792 * length [I] Number of cells to write to
793 * coord [I] Coords of first cell
794 * lpNumAttrsWritten [O] Pointer to number of cells written
796 * RETURNS
797 * Success: TRUE
798 * Failure: FALSE
800 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
801 COORD coord, LPDWORD lpNumAttrsWritten )
803 BOOL ret;
805 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
806 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
808 if (!lpNumAttrsWritten)
810 SetLastError(ERROR_INVALID_ACCESS);
811 return FALSE;
814 *lpNumAttrsWritten = 0;
816 SERVER_START_REQ( fill_console_output )
818 req->handle = console_handle_unmap(hConsoleOutput);
819 req->x = coord.X;
820 req->y = coord.Y;
821 req->mode = CHAR_INFO_MODE_ATTR;
822 req->wrap = TRUE;
823 req->data.attr = attr;
824 req->count = length;
825 if ((ret = !wine_server_call_err( req )))
826 *lpNumAttrsWritten = reply->written;
828 SERVER_END_REQ;
829 return ret;
833 /******************************************************************************
834 * ReadConsoleOutputCharacterA [KERNEL32.@]
837 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
838 COORD coord, LPDWORD read_count)
840 DWORD read;
841 BOOL ret;
842 LPWSTR wptr;
844 if (!read_count)
846 SetLastError(ERROR_INVALID_ACCESS);
847 return FALSE;
850 *read_count = 0;
852 if (!(wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR))))
854 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
855 return FALSE;
858 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
860 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
861 *read_count = read;
863 HeapFree( GetProcessHeap(), 0, wptr );
864 return ret;
868 /******************************************************************************
869 * ReadConsoleOutputCharacterW [KERNEL32.@]
872 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
873 COORD coord, LPDWORD read_count )
875 BOOL ret;
877 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
879 if (!read_count)
881 SetLastError(ERROR_INVALID_ACCESS);
882 return FALSE;
885 *read_count = 0;
887 SERVER_START_REQ( read_console_output )
889 req->handle = console_handle_unmap(hConsoleOutput);
890 req->x = coord.X;
891 req->y = coord.Y;
892 req->mode = CHAR_INFO_MODE_TEXT;
893 req->wrap = TRUE;
894 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
895 if ((ret = !wine_server_call_err( req )))
896 *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
898 SERVER_END_REQ;
899 return ret;
903 /******************************************************************************
904 * ReadConsoleOutputAttribute [KERNEL32.@]
906 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
907 COORD coord, LPDWORD read_count)
909 BOOL ret;
911 TRACE("(%p,%p,%d,%dx%d,%p)\n",
912 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
914 if (!read_count)
916 SetLastError(ERROR_INVALID_ACCESS);
917 return FALSE;
920 *read_count = 0;
922 SERVER_START_REQ( read_console_output )
924 req->handle = console_handle_unmap(hConsoleOutput);
925 req->x = coord.X;
926 req->y = coord.Y;
927 req->mode = CHAR_INFO_MODE_ATTR;
928 req->wrap = TRUE;
929 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
930 if ((ret = !wine_server_call_err( req )))
931 *read_count = wine_server_reply_size(reply) / sizeof(WORD);
933 SERVER_END_REQ;
934 return ret;
938 /******************************************************************************
939 * ReadConsoleOutputA [KERNEL32.@]
942 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
943 COORD coord, LPSMALL_RECT region )
945 BOOL ret;
946 int y;
948 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
949 if (ret && region->Right >= region->Left)
951 for (y = 0; y <= region->Bottom - region->Top; y++)
953 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
954 region->Right - region->Left + 1 );
957 return ret;
961 /******************************************************************************
962 * ReadConsoleOutputW [KERNEL32.@]
964 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
965 * think we need to be *that* compatible. -- AJ
967 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
968 COORD coord, LPSMALL_RECT region )
970 int width, height, y;
971 BOOL ret = TRUE;
973 width = min( region->Right - region->Left + 1, size.X - coord.X );
974 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
976 if (width > 0 && height > 0)
978 for (y = 0; y < height; y++)
980 SERVER_START_REQ( read_console_output )
982 req->handle = console_handle_unmap(hConsoleOutput);
983 req->x = region->Left;
984 req->y = region->Top + y;
985 req->mode = CHAR_INFO_MODE_TEXTATTR;
986 req->wrap = FALSE;
987 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
988 width * sizeof(CHAR_INFO) );
989 if ((ret = !wine_server_call_err( req )))
991 width = min( width, reply->width - region->Left );
992 height = min( height, reply->height - region->Top );
995 SERVER_END_REQ;
996 if (!ret) break;
999 region->Bottom = region->Top + height - 1;
1000 region->Right = region->Left + width - 1;
1001 return ret;
1005 /******************************************************************************
1006 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
1008 * PARAMS
1009 * handle [I] Handle to console input buffer
1010 * buffer [O] Address of buffer for read data
1011 * count [I] Number of records to read
1012 * pRead [O] Address of number of records read
1014 * RETURNS
1015 * Success: TRUE
1016 * Failure: FALSE
1018 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1020 DWORD read;
1022 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
1023 input_records_WtoA( buffer, read );
1024 if (pRead) *pRead = read;
1025 return TRUE;
1029 /***********************************************************************
1030 * PeekConsoleInputA (KERNEL32.@)
1032 * Gets 'count' first events (or less) from input queue.
1034 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
1036 DWORD read;
1038 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
1039 input_records_WtoA( buffer, read );
1040 if (pRead) *pRead = read;
1041 return TRUE;
1045 /***********************************************************************
1046 * PeekConsoleInputW (KERNEL32.@)
1048 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
1050 BOOL ret;
1051 SERVER_START_REQ( read_console_input )
1053 req->handle = console_handle_unmap(handle);
1054 req->flush = FALSE;
1055 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
1056 if ((ret = !wine_server_call_err( req )))
1058 if (read) *read = count ? reply->read : 0;
1061 SERVER_END_REQ;
1062 return ret;
1066 /***********************************************************************
1067 * GetNumberOfConsoleInputEvents (KERNEL32.@)
1069 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1071 BOOL ret;
1072 SERVER_START_REQ( read_console_input )
1074 req->handle = console_handle_unmap(handle);
1075 req->flush = FALSE;
1076 if ((ret = !wine_server_call_err( req )))
1078 if (nrofevents)
1079 *nrofevents = reply->read;
1080 else
1082 SetLastError(ERROR_INVALID_ACCESS);
1083 ret = FALSE;
1087 SERVER_END_REQ;
1088 return ret;
1092 /******************************************************************************
1093 * read_console_input
1095 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1097 * Returns
1098 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1100 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1102 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
1104 enum read_console_input_return ret;
1105 char input[8];
1106 WCHAR inputw[8];
1107 int i;
1108 size_t idx = 0, idxw;
1109 unsigned numEvent;
1110 INPUT_RECORD ir[8];
1111 DWORD written;
1112 struct pollfd pollfd;
1113 BOOL locked = FALSE, next_char;
1117 if (idx == sizeof(input))
1119 FIXME("buffer too small (%s)\n", wine_dbgstr_an(input, idx));
1120 ret = rci_error;
1121 break;
1123 pollfd.fd = fd;
1124 pollfd.events = POLLIN;
1125 pollfd.revents = 0;
1126 next_char = FALSE;
1128 switch (poll(&pollfd, 1, timeout))
1130 case 1:
1131 if (!locked)
1133 RtlEnterCriticalSection(&CONSOLE_CritSect);
1134 locked = TRUE;
1136 i = read(fd, &input[idx], 1);
1137 if (i < 0)
1139 ret = rci_error;
1140 break;
1142 if (i == 0)
1144 /* actually another thread likely beat us to reading the char
1145 * return rci_gotone, while not perfect, it should work in most of the cases (as the new event
1146 * should be now in the queue, fed from the other thread)
1148 ret = rci_gotone;
1149 break;
1152 idx++;
1153 numEvent = TERM_FillInputRecord(input, idx, ir);
1154 switch (numEvent)
1156 case 0:
1157 /* we need more char(s) to tell if it matches a key-db entry. wait 1/2s for next char */
1158 timeout = 500;
1159 next_char = TRUE;
1160 break;
1161 case -1:
1162 /* we haven't found the string into key-db, push full input string into server */
1163 idxw = MultiByteToWideChar(CP_UNIXCP, 0, input, idx, inputw, sizeof(inputw) / sizeof(inputw[0]));
1165 /* we cannot translate yet... likely we need more chars (wait max 1/2s for next char) */
1166 if (idxw == 0)
1168 timeout = 500;
1169 next_char = TRUE;
1170 break;
1172 for (i = 0; i < idxw; i++)
1174 numEvent = TERM_FillSimpleChar(inputw[i], ir);
1175 WriteConsoleInputW(handle, ir, numEvent, &written);
1177 ret = rci_gotone;
1178 break;
1179 default:
1180 /* we got a transformation from key-db... push this into server */
1181 ret = WriteConsoleInputW(handle, ir, numEvent, &written) ? rci_gotone : rci_error;
1182 break;
1184 break;
1185 case 0: ret = rci_timeout; break;
1186 default: ret = rci_error; break;
1188 } while (next_char);
1189 if (locked) RtlLeaveCriticalSection(&CONSOLE_CritSect);
1191 return ret;
1194 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1196 int fd;
1197 enum read_console_input_return ret;
1199 if ((fd = get_console_bare_fd(handle)) != -1)
1201 put_console_into_raw_mode(fd);
1202 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1204 ret = bare_console_fetch_input(handle, fd, timeout);
1206 else ret = rci_gotone;
1207 close(fd);
1208 if (ret != rci_gotone) return ret;
1210 else
1212 if (!VerifyConsoleIoHandle(handle)) return rci_error;
1214 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1215 return rci_timeout;
1218 SERVER_START_REQ( read_console_input )
1220 req->handle = console_handle_unmap(handle);
1221 req->flush = TRUE;
1222 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1223 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1224 else ret = rci_gotone;
1226 SERVER_END_REQ;
1228 return ret;
1232 /***********************************************************************
1233 * FlushConsoleInputBuffer (KERNEL32.@)
1235 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1237 enum read_console_input_return last;
1238 INPUT_RECORD ir;
1240 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1242 return last == rci_timeout;
1246 /***********************************************************************
1247 * SetConsoleTitleA (KERNEL32.@)
1249 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1251 LPWSTR titleW;
1252 BOOL ret;
1254 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1255 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1256 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1257 ret = SetConsoleTitleW(titleW);
1258 HeapFree(GetProcessHeap(), 0, titleW);
1259 return ret;
1263 /***********************************************************************
1264 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1266 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1268 FIXME( "stub %p\n", layoutName);
1269 return TRUE;
1272 /***********************************************************************
1273 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1275 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1277 FIXME( "stub %p\n", layoutName);
1278 return TRUE;
1281 static WCHAR input_exe[MAX_PATH + 1];
1283 /***********************************************************************
1284 * GetConsoleInputExeNameW (KERNEL32.@)
1286 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1288 TRACE("%u %p\n", buflen, buffer);
1290 RtlEnterCriticalSection(&CONSOLE_CritSect);
1291 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1292 else SetLastError(ERROR_BUFFER_OVERFLOW);
1293 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1295 return TRUE;
1298 /***********************************************************************
1299 * GetConsoleInputExeNameA (KERNEL32.@)
1301 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1303 TRACE("%u %p\n", buflen, buffer);
1305 RtlEnterCriticalSection(&CONSOLE_CritSect);
1306 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1307 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1308 else SetLastError(ERROR_BUFFER_OVERFLOW);
1309 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1311 return TRUE;
1314 /***********************************************************************
1315 * GetConsoleTitleA (KERNEL32.@)
1317 * See GetConsoleTitleW.
1319 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1321 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1322 DWORD ret;
1324 if (!ptr) return 0;
1325 ret = GetConsoleTitleW( ptr, size );
1326 if (ret)
1328 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1329 ret = strlen(title);
1331 HeapFree(GetProcessHeap(), 0, ptr);
1332 return ret;
1336 /******************************************************************************
1337 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1339 * PARAMS
1340 * title [O] Address of buffer for title
1341 * size [I] Size of buffer
1343 * RETURNS
1344 * Success: Length of string copied
1345 * Failure: 0
1347 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1349 DWORD ret = 0;
1351 SERVER_START_REQ( get_console_input_info )
1353 req->handle = 0;
1354 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1355 if (!wine_server_call_err( req ))
1357 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1358 title[ret] = 0;
1361 SERVER_END_REQ;
1362 return ret;
1366 /***********************************************************************
1367 * GetLargestConsoleWindowSize (KERNEL32.@)
1369 * NOTE
1370 * This should return a COORD, but calling convention for returning
1371 * structures is different between Windows and gcc on i386.
1373 * VERSION: [i386]
1375 #ifdef __i386__
1376 #undef GetLargestConsoleWindowSize
1377 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1379 union {
1380 COORD c;
1381 DWORD w;
1382 } x;
1383 x.c.X = 80;
1384 x.c.Y = 24;
1385 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1386 return x.w;
1388 #endif /* defined(__i386__) */
1391 /***********************************************************************
1392 * GetLargestConsoleWindowSize (KERNEL32.@)
1394 * NOTE
1395 * This should return a COORD, but calling convention for returning
1396 * structures is different between Windows and gcc on i386.
1398 * VERSION: [!i386]
1400 #ifndef __i386__
1401 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1403 COORD c;
1404 c.X = 80;
1405 c.Y = 24;
1406 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1407 return c;
1409 #endif /* defined(__i386__) */
1411 static WCHAR* S_EditString /* = NULL */;
1412 static unsigned S_EditStrPos /* = 0 */;
1414 /***********************************************************************
1415 * FreeConsole (KERNEL32.@)
1417 BOOL WINAPI FreeConsole(VOID)
1419 BOOL ret;
1421 /* invalidate local copy of input event handle */
1422 console_wait_event = 0;
1424 SERVER_START_REQ(free_console)
1426 ret = !wine_server_call_err( req );
1428 SERVER_END_REQ;
1429 return ret;
1432 /******************************************************************
1433 * start_console_renderer
1435 * helper for AllocConsole
1436 * starts the renderer process
1438 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1439 HANDLE hEvent)
1441 char buffer[1024];
1442 int ret;
1443 PROCESS_INFORMATION pi;
1445 /* FIXME: use dynamic allocation for most of the buffers below */
1446 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1447 if ((ret > -1) && (ret < sizeof(buffer)) &&
1448 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1449 NULL, NULL, si, &pi))
1451 HANDLE wh[2];
1452 DWORD res;
1454 wh[0] = hEvent;
1455 wh[1] = pi.hProcess;
1456 res = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1458 CloseHandle(pi.hThread);
1459 CloseHandle(pi.hProcess);
1461 if (res != WAIT_OBJECT_0) return FALSE;
1463 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1464 pi.dwProcessId, pi.dwThreadId);
1466 return TRUE;
1468 return FALSE;
1471 static BOOL start_console_renderer(STARTUPINFOA* si)
1473 HANDLE hEvent = 0;
1474 LPSTR p;
1475 OBJECT_ATTRIBUTES attr;
1476 BOOL ret = FALSE;
1478 attr.Length = sizeof(attr);
1479 attr.RootDirectory = 0;
1480 attr.Attributes = OBJ_INHERIT;
1481 attr.ObjectName = NULL;
1482 attr.SecurityDescriptor = NULL;
1483 attr.SecurityQualityOfService = NULL;
1485 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1486 if (!hEvent) return FALSE;
1488 /* first try environment variable */
1489 if ((p = getenv("WINECONSOLE")) != NULL)
1491 ret = start_console_renderer_helper(p, si, hEvent);
1492 if (!ret)
1493 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1494 "trying default access\n", p);
1497 /* then try the regular PATH */
1498 if (!ret)
1499 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1501 CloseHandle(hEvent);
1502 return ret;
1505 /***********************************************************************
1506 * AllocConsole (KERNEL32.@)
1508 * creates an xterm with a pty to our program
1510 BOOL WINAPI AllocConsole(void)
1512 HANDLE handle_in = INVALID_HANDLE_VALUE;
1513 HANDLE handle_out = INVALID_HANDLE_VALUE;
1514 HANDLE handle_err = INVALID_HANDLE_VALUE;
1515 STARTUPINFOA siCurrent;
1516 STARTUPINFOA siConsole;
1517 char buffer[1024];
1519 TRACE("()\n");
1521 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1522 FALSE, OPEN_EXISTING );
1524 if (VerifyConsoleIoHandle(handle_in))
1526 /* we already have a console opened on this process, don't create a new one */
1527 CloseHandle(handle_in);
1528 return FALSE;
1531 /* invalidate local copy of input event handle */
1532 console_wait_event = 0;
1534 GetStartupInfoA(&siCurrent);
1536 memset(&siConsole, 0, sizeof(siConsole));
1537 siConsole.cb = sizeof(siConsole);
1538 /* setup a view arguments for wineconsole (it'll use them as default values) */
1539 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1541 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1542 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1543 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1545 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1547 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1548 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1550 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1552 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1553 siConsole.wShowWindow = siCurrent.wShowWindow;
1555 /* FIXME (should pass the unicode form) */
1556 if (siCurrent.lpTitle)
1557 siConsole.lpTitle = siCurrent.lpTitle;
1558 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1560 buffer[sizeof(buffer) - 1] = '\0';
1561 siConsole.lpTitle = buffer;
1564 if (!start_console_renderer(&siConsole))
1565 goto the_end;
1567 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1568 /* all std I/O handles are inheritable by default */
1569 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1570 TRUE, OPEN_EXISTING );
1571 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1573 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1574 TRUE, OPEN_EXISTING );
1575 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1577 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1578 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1579 goto the_end;
1580 } else {
1581 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1582 handle_in = siCurrent.hStdInput;
1583 handle_out = siCurrent.hStdOutput;
1584 handle_err = siCurrent.hStdError;
1587 /* NT resets the STD_*_HANDLEs on console alloc */
1588 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1589 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1590 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1592 SetLastError(ERROR_SUCCESS);
1594 return TRUE;
1596 the_end:
1597 ERR("Can't allocate console\n");
1598 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1599 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1600 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1601 FreeConsole();
1602 return FALSE;
1606 /***********************************************************************
1607 * ReadConsoleA (KERNEL32.@)
1609 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1610 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1612 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1613 DWORD ncr = 0;
1614 BOOL ret;
1616 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1617 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1619 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1620 HeapFree(GetProcessHeap(), 0, ptr);
1622 return ret;
1625 /***********************************************************************
1626 * ReadConsoleW (KERNEL32.@)
1628 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1629 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1631 DWORD charsread;
1632 LPWSTR xbuf = lpBuffer;
1633 DWORD mode;
1634 BOOL is_bare = FALSE;
1635 int fd;
1637 TRACE("(%p,%p,%d,%p,%p)\n",
1638 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1640 if (!GetConsoleMode(hConsoleInput, &mode))
1641 return FALSE;
1642 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
1644 close(fd);
1645 is_bare = TRUE;
1647 if (mode & ENABLE_LINE_INPUT)
1649 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1651 HeapFree(GetProcessHeap(), 0, S_EditString);
1652 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1653 return FALSE;
1654 S_EditStrPos = 0;
1656 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1657 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1658 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1659 S_EditStrPos += charsread;
1661 else
1663 INPUT_RECORD ir;
1664 DWORD timeout = INFINITE;
1666 /* FIXME: should we read at least 1 char? The SDK does not say */
1667 /* wait for at least one available input record (it doesn't mean we'll have
1668 * chars stored in xbuf...)
1670 * Although SDK doc keeps silence about 1 char, SDK examples assume
1671 * that we should wait for at least one character (not key). --KS
1673 charsread = 0;
1676 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1677 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1678 ir.Event.KeyEvent.uChar.UnicodeChar)
1680 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1681 timeout = 0;
1683 } while (charsread < nNumberOfCharsToRead);
1684 /* nothing has been read */
1685 if (timeout == INFINITE) return FALSE;
1688 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1690 return TRUE;
1694 /***********************************************************************
1695 * ReadConsoleInputW (KERNEL32.@)
1697 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1698 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1700 DWORD idx = 0;
1701 DWORD timeout = INFINITE;
1703 if (!nLength)
1705 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1706 return TRUE;
1709 /* loop until we get at least one event */
1710 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1711 ++idx < nLength)
1712 timeout = 0;
1714 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1715 return idx != 0;
1719 /******************************************************************************
1720 * WriteConsoleOutputCharacterW [KERNEL32.@]
1722 * Copy character to consecutive cells in the console screen buffer.
1724 * PARAMS
1725 * hConsoleOutput [I] Handle to screen buffer
1726 * str [I] Pointer to buffer with chars to write
1727 * length [I] Number of cells to write to
1728 * coord [I] Coords of first cell
1729 * lpNumCharsWritten [O] Pointer to number of cells written
1731 * RETURNS
1732 * Success: TRUE
1733 * Failure: FALSE
1736 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1737 COORD coord, LPDWORD lpNumCharsWritten )
1739 BOOL ret;
1741 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1742 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1744 if ((length > 0 && !str) || !lpNumCharsWritten)
1746 SetLastError(ERROR_INVALID_ACCESS);
1747 return FALSE;
1750 *lpNumCharsWritten = 0;
1752 SERVER_START_REQ( write_console_output )
1754 req->handle = console_handle_unmap(hConsoleOutput);
1755 req->x = coord.X;
1756 req->y = coord.Y;
1757 req->mode = CHAR_INFO_MODE_TEXT;
1758 req->wrap = TRUE;
1759 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1760 if ((ret = !wine_server_call_err( req )))
1761 *lpNumCharsWritten = reply->written;
1763 SERVER_END_REQ;
1764 return ret;
1768 /******************************************************************************
1769 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1771 * PARAMS
1772 * title [I] Address of new title
1774 * RETURNS
1775 * Success: TRUE
1776 * Failure: FALSE
1778 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1780 BOOL ret;
1782 TRACE("(%s)\n", debugstr_w(title));
1783 SERVER_START_REQ( set_console_input_info )
1785 req->handle = 0;
1786 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1787 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1788 ret = !wine_server_call_err( req );
1790 SERVER_END_REQ;
1791 return ret;
1795 /***********************************************************************
1796 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1798 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1800 FIXME("(%p): stub\n", nrofbuttons);
1801 *nrofbuttons = 2;
1802 return TRUE;
1805 /******************************************************************************
1806 * SetConsoleInputExeNameW [KERNEL32.@]
1808 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1810 TRACE("(%s)\n", debugstr_w(name));
1812 if (!name || !name[0])
1814 SetLastError(ERROR_INVALID_PARAMETER);
1815 return FALSE;
1818 RtlEnterCriticalSection(&CONSOLE_CritSect);
1819 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1820 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1822 return TRUE;
1825 /******************************************************************************
1826 * SetConsoleInputExeNameA [KERNEL32.@]
1828 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1830 int len;
1831 LPWSTR nameW;
1832 BOOL ret;
1834 if (!name || !name[0])
1836 SetLastError(ERROR_INVALID_PARAMETER);
1837 return FALSE;
1840 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1841 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1843 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1844 ret = SetConsoleInputExeNameW(nameW);
1845 HeapFree(GetProcessHeap(), 0, nameW);
1847 return ret;
1850 /******************************************************************
1851 * CONSOLE_DefaultHandler
1853 * Final control event handler
1855 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1857 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1858 ExitProcess(0);
1859 /* should never go here */
1860 return TRUE;
1863 /******************************************************************************
1864 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1866 * PARAMS
1867 * func [I] Address of handler function
1868 * add [I] Handler to add or remove
1870 * RETURNS
1871 * Success: TRUE
1872 * Failure: FALSE
1875 struct ConsoleHandler
1877 PHANDLER_ROUTINE handler;
1878 struct ConsoleHandler* next;
1881 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1882 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1884 /*****************************************************************************/
1886 /******************************************************************
1887 * SetConsoleCtrlHandler (KERNEL32.@)
1889 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1891 BOOL ret = TRUE;
1893 TRACE("(%p,%i)\n", func, add);
1895 if (!func)
1897 RtlEnterCriticalSection(&CONSOLE_CritSect);
1898 if (add)
1899 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1900 else
1901 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1902 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1904 else if (add)
1906 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1908 if (!ch) return FALSE;
1909 ch->handler = func;
1910 RtlEnterCriticalSection(&CONSOLE_CritSect);
1911 ch->next = CONSOLE_Handlers;
1912 CONSOLE_Handlers = ch;
1913 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1915 else
1917 struct ConsoleHandler** ch;
1918 RtlEnterCriticalSection(&CONSOLE_CritSect);
1919 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1921 if ((*ch)->handler == func) break;
1923 if (*ch)
1925 struct ConsoleHandler* rch = *ch;
1927 /* sanity check */
1928 if (rch == &CONSOLE_DefaultConsoleHandler)
1930 ERR("Who's trying to remove default handler???\n");
1931 SetLastError(ERROR_INVALID_PARAMETER);
1932 ret = FALSE;
1934 else
1936 *ch = rch->next;
1937 HeapFree(GetProcessHeap(), 0, rch);
1940 else
1942 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1943 SetLastError(ERROR_INVALID_PARAMETER);
1944 ret = FALSE;
1946 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1948 return ret;
1951 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1953 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1954 return EXCEPTION_EXECUTE_HANDLER;
1957 /******************************************************************
1958 * CONSOLE_SendEventThread
1960 * Internal helper to pass an event to the list on installed handlers
1962 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1964 DWORD_PTR event = (DWORD_PTR)pmt;
1965 struct ConsoleHandler* ch;
1967 if (event == CTRL_C_EVENT)
1969 BOOL caught_by_dbg = TRUE;
1970 /* First, try to pass the ctrl-C event to the debugger (if any)
1971 * If it continues, there's nothing more to do
1972 * Otherwise, we need to send the ctrl-C event to the handlers
1974 __TRY
1976 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1978 __EXCEPT(CONSOLE_CtrlEventHandler)
1980 caught_by_dbg = FALSE;
1982 __ENDTRY;
1983 if (caught_by_dbg) return 0;
1984 /* the debugger didn't continue... so, pass to ctrl handlers */
1986 RtlEnterCriticalSection(&CONSOLE_CritSect);
1987 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1989 if (ch->handler(event)) break;
1991 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1992 return 1;
1995 /******************************************************************
1996 * CONSOLE_HandleCtrlC
1998 * Check whether the shall manipulate CtrlC events
2000 int CONSOLE_HandleCtrlC(unsigned sig)
2002 HANDLE thread;
2004 /* FIXME: better test whether a console is attached to this process ??? */
2005 extern unsigned CONSOLE_GetNumHistoryEntries(void);
2006 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
2008 /* check if we have to ignore ctrl-C events */
2009 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
2011 /* Create a separate thread to signal all the events.
2012 * This is needed because:
2013 * - this function can be called in an Unix signal handler (hence on an
2014 * different stack than the thread that's running). This breaks the
2015 * Win32 exception mechanisms (where the thread's stack is checked).
2016 * - since the current thread, while processing the signal, can hold the
2017 * console critical section, we need another execution environment where
2018 * we can wait on this critical section
2020 thread = CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
2021 if (thread == NULL)
2022 return 0;
2024 CloseHandle(thread);
2026 return 1;
2029 /******************************************************************************
2030 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
2032 * PARAMS
2033 * dwCtrlEvent [I] Type of event
2034 * dwProcessGroupID [I] Process group ID to send event to
2036 * RETURNS
2037 * Success: True
2038 * Failure: False (and *should* [but doesn't] set LastError)
2040 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
2041 DWORD dwProcessGroupID)
2043 BOOL ret;
2045 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2047 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2049 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2050 return FALSE;
2053 SERVER_START_REQ( send_console_signal )
2055 req->signal = dwCtrlEvent;
2056 req->group_id = dwProcessGroupID;
2057 ret = !wine_server_call_err( req );
2059 SERVER_END_REQ;
2061 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2062 * have been handled by all processes in the given group?
2063 * As of today, we don't wait...
2065 return ret;
2069 /******************************************************************************
2070 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2072 * PARAMS
2073 * dwDesiredAccess [I] Access flag
2074 * dwShareMode [I] Buffer share mode
2075 * sa [I] Security attributes
2076 * dwFlags [I] Type of buffer to create
2077 * lpScreenBufferData [I] Reserved
2079 * NOTES
2080 * Should call SetLastError
2082 * RETURNS
2083 * Success: Handle to new console screen buffer
2084 * Failure: INVALID_HANDLE_VALUE
2086 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2087 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2088 LPVOID lpScreenBufferData)
2090 HANDLE ret = INVALID_HANDLE_VALUE;
2092 TRACE("(%d,%d,%p,%d,%p)\n",
2093 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2095 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2097 SetLastError(ERROR_INVALID_PARAMETER);
2098 return INVALID_HANDLE_VALUE;
2101 SERVER_START_REQ(create_console_output)
2103 req->handle_in = 0;
2104 req->access = dwDesiredAccess;
2105 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2106 req->share = dwShareMode;
2107 req->fd = -1;
2108 if (!wine_server_call_err( req ))
2109 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2111 SERVER_END_REQ;
2113 return ret;
2117 /***********************************************************************
2118 * GetConsoleScreenBufferInfo (KERNEL32.@)
2120 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2122 BOOL ret;
2124 SERVER_START_REQ(get_console_output_info)
2126 req->handle = console_handle_unmap(hConsoleOutput);
2127 if ((ret = !wine_server_call_err( req )))
2129 csbi->dwSize.X = reply->width;
2130 csbi->dwSize.Y = reply->height;
2131 csbi->dwCursorPosition.X = reply->cursor_x;
2132 csbi->dwCursorPosition.Y = reply->cursor_y;
2133 csbi->wAttributes = reply->attr;
2134 csbi->srWindow.Left = reply->win_left;
2135 csbi->srWindow.Right = reply->win_right;
2136 csbi->srWindow.Top = reply->win_top;
2137 csbi->srWindow.Bottom = reply->win_bottom;
2138 csbi->dwMaximumWindowSize.X = reply->max_width;
2139 csbi->dwMaximumWindowSize.Y = reply->max_height;
2142 SERVER_END_REQ;
2144 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2145 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2146 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2147 csbi->wAttributes,
2148 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2149 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2151 return ret;
2155 /******************************************************************************
2156 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2158 * RETURNS
2159 * Success: TRUE
2160 * Failure: FALSE
2162 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2164 BOOL ret;
2166 TRACE("(%p)\n", hConsoleOutput);
2168 SERVER_START_REQ( set_console_input_info )
2170 req->handle = 0;
2171 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2172 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2173 ret = !wine_server_call_err( req );
2175 SERVER_END_REQ;
2176 return ret;
2180 /***********************************************************************
2181 * GetConsoleMode (KERNEL32.@)
2183 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2185 BOOL ret;
2187 SERVER_START_REQ( get_console_mode )
2189 req->handle = console_handle_unmap(hcon);
2190 if ((ret = !wine_server_call_err( req )))
2192 if (mode) *mode = reply->mode;
2195 SERVER_END_REQ;
2196 return ret;
2200 /******************************************************************************
2201 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2203 * PARAMS
2204 * hcon [I] Handle to console input or screen buffer
2205 * mode [I] Input or output mode to set
2207 * RETURNS
2208 * Success: TRUE
2209 * Failure: FALSE
2211 * mode:
2212 * ENABLE_PROCESSED_INPUT 0x01
2213 * ENABLE_LINE_INPUT 0x02
2214 * ENABLE_ECHO_INPUT 0x04
2215 * ENABLE_WINDOW_INPUT 0x08
2216 * ENABLE_MOUSE_INPUT 0x10
2218 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2220 BOOL ret;
2222 SERVER_START_REQ(set_console_mode)
2224 req->handle = console_handle_unmap(hcon);
2225 req->mode = mode;
2226 ret = !wine_server_call_err( req );
2228 SERVER_END_REQ;
2229 /* FIXME: when resetting a console input to editline mode, I think we should
2230 * empty the S_EditString buffer
2233 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2235 return ret;
2239 /******************************************************************
2240 * CONSOLE_WriteChars
2242 * WriteConsoleOutput helper: hides server call semantics
2243 * writes a string at a given pos with standard attribute
2245 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2247 int written = -1;
2249 if (!nc) return 0;
2251 SERVER_START_REQ( write_console_output )
2253 req->handle = console_handle_unmap(hCon);
2254 req->x = pos->X;
2255 req->y = pos->Y;
2256 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2257 req->wrap = FALSE;
2258 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2259 if (!wine_server_call_err( req )) written = reply->written;
2261 SERVER_END_REQ;
2263 if (written > 0) pos->X += written;
2264 return written;
2267 /******************************************************************
2268 * next_line
2270 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2273 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2275 SMALL_RECT src;
2276 CHAR_INFO ci;
2277 COORD dst;
2279 csbi->dwCursorPosition.X = 0;
2280 csbi->dwCursorPosition.Y++;
2282 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2284 src.Top = 1;
2285 src.Bottom = csbi->dwSize.Y - 1;
2286 src.Left = 0;
2287 src.Right = csbi->dwSize.X - 1;
2289 dst.X = 0;
2290 dst.Y = 0;
2292 ci.Attributes = csbi->wAttributes;
2293 ci.Char.UnicodeChar = ' ';
2295 csbi->dwCursorPosition.Y--;
2296 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2297 return 0;
2298 return 1;
2301 /******************************************************************
2302 * write_block
2304 * WriteConsoleOutput helper: writes a block of non special characters
2305 * Block can spread on several lines, and wrapping, if needed, is
2306 * handled
2309 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2310 DWORD mode, LPCWSTR ptr, int len)
2312 int blk; /* number of chars to write on current line */
2313 int done; /* number of chars already written */
2315 if (len <= 0) return 1;
2317 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2319 for (done = 0; done < len; done += blk)
2321 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2323 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2324 return 0;
2325 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2326 return 0;
2329 else
2331 int pos = csbi->dwCursorPosition.X;
2332 /* FIXME: we could reduce the number of loops
2333 * but, in most cases we wouldn't gain lots of time (it would only
2334 * happen if we're asked to overwrite more than twice the part of the line,
2335 * which is unlikely
2337 for (done = 0; done < len; done += blk)
2339 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2341 csbi->dwCursorPosition.X = pos;
2342 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2343 return 0;
2347 return 1;
2350 /***********************************************************************
2351 * WriteConsoleW (KERNEL32.@)
2353 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2354 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2356 DWORD mode;
2357 DWORD nw = 0;
2358 const WCHAR* psz = lpBuffer;
2359 CONSOLE_SCREEN_BUFFER_INFO csbi;
2360 int k, first = 0, fd;
2362 TRACE("%p %s %d %p %p\n",
2363 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2364 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2366 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2368 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2370 char* ptr;
2371 unsigned len;
2372 HANDLE hFile;
2373 NTSTATUS status;
2374 IO_STATUS_BLOCK iosb;
2376 close(fd);
2377 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2378 * to do the job
2380 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2381 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2382 return FALSE;
2384 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2385 hFile = wine_server_ptr_handle(console_handle_unmap(hConsoleOutput));
2386 status = NtWriteFile(hFile, NULL, NULL, NULL, &iosb, ptr, len, 0, NULL);
2387 if (status == STATUS_PENDING)
2389 WaitForSingleObject(hFile, INFINITE);
2390 status = iosb.u.Status;
2393 if (status != STATUS_PENDING && lpNumberOfCharsWritten)
2395 if (iosb.Information == len)
2396 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2397 else
2398 FIXME("Conversion not supported yet\n");
2400 HeapFree(GetProcessHeap(), 0, ptr);
2401 if (status != STATUS_SUCCESS)
2403 SetLastError(RtlNtStatusToDosError(status));
2404 return FALSE;
2406 return TRUE;
2409 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2410 return FALSE;
2412 if (!nNumberOfCharsToWrite) return TRUE;
2414 if (mode & ENABLE_PROCESSED_OUTPUT)
2416 unsigned int i;
2418 for (i = 0; i < nNumberOfCharsToWrite; i++)
2420 switch (psz[i])
2422 case '\b': case '\t': case '\n': case '\a': case '\r':
2423 /* don't handle here the i-th char... done below */
2424 if ((k = i - first) > 0)
2426 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2427 goto the_end;
2428 nw += k;
2430 first = i + 1;
2431 nw++;
2433 switch (psz[i])
2435 case '\b':
2436 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2437 break;
2438 case '\t':
2440 static const WCHAR tmp[] = {' ',' ',' ',' ',' ',' ',' ',' '};
2441 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2442 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2443 goto the_end;
2445 break;
2446 case '\n':
2447 next_line(hConsoleOutput, &csbi);
2448 break;
2449 case '\a':
2450 Beep(400, 300);
2451 break;
2452 case '\r':
2453 csbi.dwCursorPosition.X = 0;
2454 break;
2455 default:
2456 break;
2461 /* write the remaining block (if any) if processed output is enabled, or the
2462 * entire buffer otherwise
2464 if ((k = nNumberOfCharsToWrite - first) > 0)
2466 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2467 goto the_end;
2468 nw += k;
2471 the_end:
2472 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2473 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2474 return nw != 0;
2478 /***********************************************************************
2479 * WriteConsoleA (KERNEL32.@)
2481 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2482 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2484 BOOL ret;
2485 LPWSTR xstring;
2486 DWORD n;
2488 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2490 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2491 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2492 if (!xstring) return 0;
2494 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2496 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2498 HeapFree(GetProcessHeap(), 0, xstring);
2500 return ret;
2503 /******************************************************************************
2504 * SetConsoleCursorPosition [KERNEL32.@]
2505 * Sets the cursor position in console
2507 * PARAMS
2508 * hConsoleOutput [I] Handle of console screen buffer
2509 * dwCursorPosition [I] New cursor position coordinates
2511 * RETURNS
2512 * Success: TRUE
2513 * Failure: FALSE
2515 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2517 BOOL ret;
2518 CONSOLE_SCREEN_BUFFER_INFO csbi;
2519 int do_move = 0;
2520 int w, h;
2522 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2524 SERVER_START_REQ(set_console_output_info)
2526 req->handle = console_handle_unmap(hcon);
2527 req->cursor_x = pos.X;
2528 req->cursor_y = pos.Y;
2529 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2530 ret = !wine_server_call_err( req );
2532 SERVER_END_REQ;
2534 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2535 return FALSE;
2537 /* if cursor is no longer visible, scroll the visible window... */
2538 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2539 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2540 if (pos.X < csbi.srWindow.Left)
2542 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2543 do_move++;
2545 else if (pos.X > csbi.srWindow.Right)
2547 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2548 do_move++;
2550 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2552 if (pos.Y < csbi.srWindow.Top)
2554 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2555 do_move++;
2557 else if (pos.Y > csbi.srWindow.Bottom)
2559 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2560 do_move++;
2562 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2564 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2566 return ret;
2569 /******************************************************************************
2570 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2572 * PARAMS
2573 * hcon [I] Handle to console screen buffer
2574 * cinfo [O] Address of cursor information
2576 * RETURNS
2577 * Success: TRUE
2578 * Failure: FALSE
2580 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2582 BOOL ret;
2584 SERVER_START_REQ(get_console_output_info)
2586 req->handle = console_handle_unmap(hCon);
2587 ret = !wine_server_call_err( req );
2588 if (ret && cinfo)
2590 cinfo->dwSize = reply->cursor_size;
2591 cinfo->bVisible = reply->cursor_visible;
2594 SERVER_END_REQ;
2596 if (!ret) return FALSE;
2598 if (!cinfo)
2600 SetLastError(ERROR_INVALID_ACCESS);
2601 ret = FALSE;
2603 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2605 return ret;
2609 /******************************************************************************
2610 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2612 * PARAMS
2613 * hcon [I] Handle to console screen buffer
2614 * cinfo [I] Address of cursor information
2615 * RETURNS
2616 * Success: TRUE
2617 * Failure: FALSE
2619 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2621 BOOL ret;
2623 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2624 SERVER_START_REQ(set_console_output_info)
2626 req->handle = console_handle_unmap(hCon);
2627 req->cursor_size = cinfo->dwSize;
2628 req->cursor_visible = cinfo->bVisible;
2629 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2630 ret = !wine_server_call_err( req );
2632 SERVER_END_REQ;
2633 return ret;
2637 /******************************************************************************
2638 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2640 * PARAMS
2641 * hcon [I] Handle to console screen buffer
2642 * bAbsolute [I] Coordinate type flag
2643 * window [I] Address of new window rectangle
2644 * RETURNS
2645 * Success: TRUE
2646 * Failure: FALSE
2648 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2650 SMALL_RECT p = *window;
2651 BOOL ret;
2653 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2655 if (!bAbsolute)
2657 CONSOLE_SCREEN_BUFFER_INFO csbi;
2659 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2660 return FALSE;
2661 p.Left += csbi.srWindow.Left;
2662 p.Top += csbi.srWindow.Top;
2663 p.Right += csbi.srWindow.Right;
2664 p.Bottom += csbi.srWindow.Bottom;
2666 SERVER_START_REQ(set_console_output_info)
2668 req->handle = console_handle_unmap(hCon);
2669 req->win_left = p.Left;
2670 req->win_top = p.Top;
2671 req->win_right = p.Right;
2672 req->win_bottom = p.Bottom;
2673 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2674 ret = !wine_server_call_err( req );
2676 SERVER_END_REQ;
2678 return ret;
2682 /******************************************************************************
2683 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2685 * Sets the foreground and background color attributes of characters
2686 * written to the screen buffer.
2688 * RETURNS
2689 * Success: TRUE
2690 * Failure: FALSE
2692 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2694 BOOL ret;
2696 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2697 SERVER_START_REQ(set_console_output_info)
2699 req->handle = console_handle_unmap(hConsoleOutput);
2700 req->attr = wAttr;
2701 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2702 ret = !wine_server_call_err( req );
2704 SERVER_END_REQ;
2705 return ret;
2709 /******************************************************************************
2710 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2712 * PARAMS
2713 * hConsoleOutput [I] Handle to console screen buffer
2714 * dwSize [I] New size in character rows and cols
2716 * RETURNS
2717 * Success: TRUE
2718 * Failure: FALSE
2720 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2722 BOOL ret;
2724 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2725 SERVER_START_REQ(set_console_output_info)
2727 req->handle = console_handle_unmap(hConsoleOutput);
2728 req->width = dwSize.X;
2729 req->height = dwSize.Y;
2730 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2731 ret = !wine_server_call_err( req );
2733 SERVER_END_REQ;
2734 return ret;
2738 /******************************************************************************
2739 * ScrollConsoleScreenBufferA [KERNEL32.@]
2742 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2743 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2744 LPCHAR_INFO lpFill)
2746 CHAR_INFO ciw;
2748 ciw.Attributes = lpFill->Attributes;
2749 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2751 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2752 dwDestOrigin, &ciw);
2755 /******************************************************************
2756 * CONSOLE_FillLineUniform
2758 * Helper function for ScrollConsoleScreenBufferW
2759 * Fills a part of a line with a constant character info
2761 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2763 SERVER_START_REQ( fill_console_output )
2765 req->handle = console_handle_unmap(hConsoleOutput);
2766 req->mode = CHAR_INFO_MODE_TEXTATTR;
2767 req->x = i;
2768 req->y = j;
2769 req->count = len;
2770 req->wrap = FALSE;
2771 req->data.ch = lpFill->Char.UnicodeChar;
2772 req->data.attr = lpFill->Attributes;
2773 wine_server_call_err( req );
2775 SERVER_END_REQ;
2778 /******************************************************************************
2779 * ScrollConsoleScreenBufferW [KERNEL32.@]
2783 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2784 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2785 LPCHAR_INFO lpFill)
2787 SMALL_RECT dst;
2788 DWORD ret;
2789 int i, j;
2790 int start = -1;
2791 SMALL_RECT clip;
2792 CONSOLE_SCREEN_BUFFER_INFO csbi;
2793 BOOL inside;
2794 COORD src;
2796 if (lpClipRect)
2797 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2798 lpScrollRect->Left, lpScrollRect->Top,
2799 lpScrollRect->Right, lpScrollRect->Bottom,
2800 lpClipRect->Left, lpClipRect->Top,
2801 lpClipRect->Right, lpClipRect->Bottom,
2802 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2803 else
2804 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2805 lpScrollRect->Left, lpScrollRect->Top,
2806 lpScrollRect->Right, lpScrollRect->Bottom,
2807 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2809 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2810 return FALSE;
2812 src.X = lpScrollRect->Left;
2813 src.Y = lpScrollRect->Top;
2815 /* step 1: get dst rect */
2816 dst.Left = dwDestOrigin.X;
2817 dst.Top = dwDestOrigin.Y;
2818 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2819 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2821 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2822 if (lpClipRect)
2824 clip.Left = max(0, lpClipRect->Left);
2825 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2826 clip.Top = max(0, lpClipRect->Top);
2827 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2829 else
2831 clip.Left = 0;
2832 clip.Right = csbi.dwSize.X - 1;
2833 clip.Top = 0;
2834 clip.Bottom = csbi.dwSize.Y - 1;
2836 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2838 /* step 2b: clip dst rect */
2839 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2840 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2841 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2842 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2844 /* step 3: transfer the bits */
2845 SERVER_START_REQ(move_console_output)
2847 req->handle = console_handle_unmap(hConsoleOutput);
2848 req->x_src = src.X;
2849 req->y_src = src.Y;
2850 req->x_dst = dst.Left;
2851 req->y_dst = dst.Top;
2852 req->w = dst.Right - dst.Left + 1;
2853 req->h = dst.Bottom - dst.Top + 1;
2854 ret = !wine_server_call_err( req );
2856 SERVER_END_REQ;
2858 if (!ret) return FALSE;
2860 /* step 4: clean out the exposed part */
2862 /* have to write cell [i,j] if it is not in dst rect (because it has already
2863 * been written to by the scroll) and is in clip (we shall not write
2864 * outside of clip)
2866 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2868 inside = dst.Top <= j && j <= dst.Bottom;
2869 start = -1;
2870 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2872 if (inside && dst.Left <= i && i <= dst.Right)
2874 if (start != -1)
2876 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2877 start = -1;
2880 else
2882 if (start == -1) start = i;
2885 if (start != -1)
2886 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2889 return TRUE;
2892 /******************************************************************
2893 * AttachConsole (KERNEL32.@)
2895 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2897 FIXME("stub %x\n",dwProcessId);
2898 return TRUE;
2901 /******************************************************************
2902 * GetConsoleDisplayMode (KERNEL32.@)
2904 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2906 TRACE("semi-stub: %p\n", lpModeFlags);
2907 /* It is safe to successfully report windowed mode */
2908 *lpModeFlags = 0;
2909 return TRUE;
2912 /******************************************************************
2913 * SetConsoleDisplayMode (KERNEL32.@)
2915 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2916 COORD *lpNewScreenBufferDimensions)
2918 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2919 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2920 if (dwFlags == 1)
2922 /* We cannot switch to fullscreen */
2923 return FALSE;
2925 return TRUE;
2929 /* ====================================================================
2931 * Console manipulation functions
2933 * ====================================================================*/
2935 /* some missing functions...
2936 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2937 * should get the right API and implement them
2938 * SetConsoleCommandHistoryMode
2939 * SetConsoleNumberOfCommands[AW]
2941 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2943 int len = 0;
2945 SERVER_START_REQ( get_console_input_history )
2947 req->handle = 0;
2948 req->index = idx;
2949 if (buf && buf_len > 1)
2951 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2953 if (!wine_server_call_err( req ))
2955 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2956 len = reply->total / sizeof(WCHAR) + 1;
2959 SERVER_END_REQ;
2960 return len;
2963 /******************************************************************
2964 * CONSOLE_AppendHistory
2968 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2970 size_t len = strlenW(ptr);
2971 BOOL ret;
2973 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2974 if (!len) return FALSE;
2976 SERVER_START_REQ( append_console_input_history )
2978 req->handle = 0;
2979 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2980 ret = !wine_server_call_err( req );
2982 SERVER_END_REQ;
2983 return ret;
2986 /******************************************************************
2987 * CONSOLE_GetNumHistoryEntries
2991 unsigned CONSOLE_GetNumHistoryEntries(void)
2993 unsigned ret = -1;
2994 SERVER_START_REQ(get_console_input_info)
2996 req->handle = 0;
2997 if (!wine_server_call_err( req )) ret = reply->history_index;
2999 SERVER_END_REQ;
3000 return ret;
3003 /******************************************************************
3004 * CONSOLE_GetEditionMode
3008 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
3010 unsigned ret = FALSE;
3011 SERVER_START_REQ(get_console_input_info)
3013 req->handle = console_handle_unmap(hConIn);
3014 if ((ret = !wine_server_call_err( req )))
3015 *mode = reply->edition_mode;
3017 SERVER_END_REQ;
3018 return ret;
3021 /******************************************************************
3022 * GetConsoleAliasW
3025 * RETURNS
3026 * 0 if an error occurred, non-zero for success
3029 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
3030 DWORD TargetBufferLength, LPWSTR lpExename)
3032 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
3033 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3034 return 0;
3037 /******************************************************************
3038 * GetConsoleProcessList (KERNEL32.@)
3040 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
3042 FIXME("(%p,%d): stub\n", processlist, processcount);
3044 if (!processlist || processcount < 1)
3046 SetLastError(ERROR_INVALID_PARAMETER);
3047 return 0;
3050 return 0;
3053 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
3055 memset(&S_termios, 0, sizeof(S_termios));
3056 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
3058 HANDLE conin;
3060 /* FIXME: to be done even if program is a GUI ? */
3061 /* This is wine specific: we have no parent (we're started from unix)
3062 * so, create a simple console with bare handles
3064 TERM_Init();
3065 wine_server_send_fd(0);
3066 SERVER_START_REQ( alloc_console )
3068 req->access = GENERIC_READ | GENERIC_WRITE;
3069 req->attributes = OBJ_INHERIT;
3070 req->pid = 0xffffffff;
3071 req->input_fd = 0;
3072 wine_server_call( req );
3073 conin = wine_server_ptr_handle( reply->handle_in );
3074 /* reply->event shouldn't be created by server */
3076 SERVER_END_REQ;
3078 if (!params->hStdInput)
3079 params->hStdInput = conin;
3081 if (!params->hStdOutput)
3083 wine_server_send_fd(1);
3084 SERVER_START_REQ( create_console_output )
3086 req->handle_in = wine_server_obj_handle(conin);
3087 req->access = GENERIC_WRITE|GENERIC_READ;
3088 req->attributes = OBJ_INHERIT;
3089 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3090 req->fd = 1;
3091 wine_server_call(req);
3092 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3094 SERVER_END_REQ;
3096 if (!params->hStdError)
3098 wine_server_send_fd(2);
3099 SERVER_START_REQ( create_console_output )
3101 req->handle_in = wine_server_obj_handle(conin);
3102 req->access = GENERIC_WRITE|GENERIC_READ;
3103 req->attributes = OBJ_INHERIT;
3104 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3105 req->fd = 2;
3106 wine_server_call(req);
3107 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3109 SERVER_END_REQ;
3113 /* convert value from server:
3114 * + 0 => INVALID_HANDLE_VALUE
3115 * + console handle needs to be mapped
3117 if (!params->hStdInput)
3118 params->hStdInput = INVALID_HANDLE_VALUE;
3119 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3121 params->hStdInput = console_handle_map(params->hStdInput);
3122 save_console_mode(params->hStdInput);
3125 if (!params->hStdOutput)
3126 params->hStdOutput = INVALID_HANDLE_VALUE;
3127 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3128 params->hStdOutput = console_handle_map(params->hStdOutput);
3130 if (!params->hStdError)
3131 params->hStdError = INVALID_HANDLE_VALUE;
3132 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3133 params->hStdError = console_handle_map(params->hStdError);
3135 return TRUE;
3138 BOOL CONSOLE_Exit(void)
3140 /* the console is in raw mode, put it back in cooked mode */
3141 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));
3144 /* Undocumented, called by native doskey.exe */
3145 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3146 DWORD WINAPI GetConsoleCommandHistoryA(DWORD unknown1, DWORD unknown2, DWORD unknown3)
3148 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
3149 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3150 return 0;
3153 /* Undocumented, called by native doskey.exe */
3154 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3155 DWORD WINAPI GetConsoleCommandHistoryW(DWORD unknown1, DWORD unknown2, DWORD unknown3)
3157 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
3158 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3159 return 0;
3162 /* Undocumented, called by native doskey.exe */
3163 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3164 DWORD WINAPI GetConsoleCommandHistoryLengthA(LPCSTR unknown)
3166 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3167 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3168 return 0;
3171 /* Undocumented, called by native doskey.exe */
3172 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
3173 DWORD WINAPI GetConsoleCommandHistoryLengthW(LPCWSTR unknown)
3175 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3176 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3177 return 0;
3180 DWORD WINAPI GetConsoleAliasesLengthA(LPSTR unknown)
3182 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3183 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3184 return 0;
3187 DWORD WINAPI GetConsoleAliasesLengthW(LPWSTR unknown)
3189 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3190 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3191 return 0;
3194 VOID WINAPI ExpungeConsoleCommandHistoryA(LPCSTR unknown)
3196 FIXME(": (%s) stub!\n", debugstr_a(unknown));
3197 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3200 VOID WINAPI ExpungeConsoleCommandHistoryW(LPCWSTR unknown)
3202 FIXME(": (%s) stub!\n", debugstr_w(unknown));
3203 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3206 BOOL WINAPI AddConsoleAliasA(LPSTR source, LPSTR target, LPSTR exename)
3208 FIXME(": (%s, %s, %s) stub!\n", debugstr_a(source), debugstr_a(target), debugstr_a(exename));
3209 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3210 return FALSE;
3213 BOOL WINAPI AddConsoleAliasW(LPWSTR source, LPWSTR target, LPWSTR exename)
3215 FIXME(": (%s, %s, %s) stub!\n", debugstr_w(source), debugstr_w(target), debugstr_w(exename));
3216 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3217 return FALSE;