kernel32: Use fd availability for testing whether a console handle refers to a bare...
[wine.git] / dlls / kernel32 / console.c
blob2ea1cd84828fa2afe608501e2dc02d7f73fef8b5
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 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
45 #include "ntstatus.h"
46 #define WIN32_NO_STATUS
47 #include "windef.h"
48 #include "winbase.h"
49 #include "winnls.h"
50 #include "winerror.h"
51 #include "wincon.h"
52 #include "wine/server.h"
53 #include "wine/exception.h"
54 #include "wine/unicode.h"
55 #include "wine/debug.h"
56 #include "excpt.h"
57 #include "console_private.h"
58 #include "kernel_private.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(console);
62 static CRITICAL_SECTION CONSOLE_CritSect;
63 static CRITICAL_SECTION_DEBUG critsect_debug =
65 0, 0, &CONSOLE_CritSect,
66 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
67 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
69 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
71 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
72 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
74 /* FIXME: this is not thread safe */
75 static HANDLE console_wait_event;
77 /* map input records to ASCII */
78 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
80 int i;
81 char ch;
83 for (i = 0; i < count; i++)
85 if (buffer[i].EventType != KEY_EVENT) continue;
86 WideCharToMultiByte( GetConsoleCP(), 0,
87 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
88 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
92 /* map input records to Unicode */
93 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
95 int i;
96 WCHAR ch;
98 for (i = 0; i < count; i++)
100 if (buffer[i].EventType != KEY_EVENT) continue;
101 MultiByteToWideChar( GetConsoleCP(), 0,
102 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
103 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
107 /* map char infos to ASCII */
108 static void char_info_WtoA( CHAR_INFO *buffer, int count )
110 char ch;
112 while (count-- > 0)
114 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
115 &ch, 1, NULL, NULL );
116 buffer->Char.AsciiChar = ch;
117 buffer++;
121 /* map char infos to Unicode */
122 static void char_info_AtoW( CHAR_INFO *buffer, int count )
124 WCHAR ch;
126 while (count-- > 0)
128 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
129 buffer->Char.UnicodeChar = ch;
130 buffer++;
134 static BOOL get_console_mode(HANDLE conin, DWORD* mode, BOOL* bare)
136 BOOL ret;
138 SERVER_START_REQ( get_console_mode )
140 req->handle = console_handle_unmap(conin);
141 if ((ret = !wine_server_call_err( req )))
143 if (mode) *mode = reply->mode;
144 if (bare) *bare = reply->is_bare;
147 SERVER_END_REQ;
148 return ret;
151 static struct termios S_termios; /* saved termios for bare consoles */
152 static BOOL S_termios_raw /* = FALSE */;
154 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
155 * - a bare console is created for all CUI programs started from command line (without
156 * wineconsole) (let's call those PS)
157 * - of course, every child of a PS which requires console inheritance will get it
158 * - the console termios attributes are saved at the start of program which is attached to be
159 * bare console
160 * - if any program attached to a bare console requests input from console, the console is
161 * turned into raw mode
162 * - when the program which created the bare console (the program started from command line)
163 * exits, it will restore the console termios attributes it saved at startup (this
164 * will put back the console into cooked mode if it had been put in raw mode)
165 * - if any other program attached to this bare console is still alive, the Unix shell will put
166 * it in the background, hence forbidding access to the console. Therefore, reading console
167 * input will not be available when the bare console creator has died.
168 * FIXME: This is a limitation of current implementation
171 /* returns the fd for a bare console (-1 otherwise) */
172 static int get_console_bare_fd(HANDLE hin)
174 int fd;
176 if (wine_server_handle_to_fd(hin, 0, &fd, NULL) == STATUS_SUCCESS)
177 return fd;
178 return -1;
181 static BOOL save_console_mode(HANDLE hin)
183 int fd;
184 BOOL ret;
186 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
187 ret = tcgetattr(fd, &S_termios) >= 0;
188 close(fd);
189 return ret;
192 static BOOL put_console_into_raw_mode(int fd)
194 RtlEnterCriticalSection(&CONSOLE_CritSect);
195 if (!S_termios_raw)
197 struct termios term = S_termios;
199 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
200 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
201 term.c_cflag &= ~(CSIZE | PARENB);
202 term.c_cflag |= CS8;
203 /* FIXME: we should actually disable output processing here
204 * and let kernel32/console.c do the job (with support of enable/disable of
205 * processed output)
207 /* term.c_oflag &= ~(OPOST); */
208 term.c_cc[VMIN] = 1;
209 term.c_cc[VTIME] = 0;
210 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
212 RtlLeaveCriticalSection(&CONSOLE_CritSect);
214 return S_termios_raw;
217 /* put back the console in cooked mode iff we're the process which created the bare console
218 * we don't test if thie process has set the console in raw mode as it could be one of its
219 * child who did it
221 static BOOL restore_console_mode(HANDLE hin)
223 int fd;
224 BOOL ret;
226 if (!S_termios_raw ||
227 RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle != KERNEL32_CONSOLE_SHELL)
228 return TRUE;
229 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
230 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
231 close(fd);
232 return ret;
235 /******************************************************************************
236 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
238 * RETURNS
239 * Success: hwnd of the console window.
240 * Failure: NULL
242 HWND WINAPI GetConsoleWindow(VOID)
244 HWND hWnd = NULL;
246 SERVER_START_REQ(get_console_input_info)
248 req->handle = 0;
249 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
251 SERVER_END_REQ;
253 return hWnd;
257 /******************************************************************************
258 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
260 * RETURNS
261 * Code page code
263 UINT WINAPI GetConsoleCP(VOID)
265 BOOL ret;
266 UINT codepage = GetOEMCP(); /* default value */
268 SERVER_START_REQ(get_console_input_info)
270 req->handle = 0;
271 ret = !wine_server_call_err(req);
272 if (ret && reply->input_cp)
273 codepage = reply->input_cp;
275 SERVER_END_REQ;
277 return codepage;
281 /******************************************************************************
282 * SetConsoleCP [KERNEL32.@]
284 BOOL WINAPI SetConsoleCP(UINT cp)
286 BOOL ret;
288 if (!IsValidCodePage(cp))
290 SetLastError(ERROR_INVALID_PARAMETER);
291 return FALSE;
294 SERVER_START_REQ(set_console_input_info)
296 req->handle = 0;
297 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
298 req->input_cp = cp;
299 ret = !wine_server_call_err(req);
301 SERVER_END_REQ;
303 return ret;
307 /***********************************************************************
308 * GetConsoleOutputCP (KERNEL32.@)
310 UINT WINAPI GetConsoleOutputCP(VOID)
312 BOOL ret;
313 UINT codepage = GetOEMCP(); /* default value */
315 SERVER_START_REQ(get_console_input_info)
317 req->handle = 0;
318 ret = !wine_server_call_err(req);
319 if (ret && reply->output_cp)
320 codepage = reply->output_cp;
322 SERVER_END_REQ;
324 return codepage;
328 /******************************************************************************
329 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
331 * PARAMS
332 * cp [I] code page to set
334 * RETURNS
335 * Success: TRUE
336 * Failure: FALSE
338 BOOL WINAPI SetConsoleOutputCP(UINT cp)
340 BOOL ret;
342 if (!IsValidCodePage(cp))
344 SetLastError(ERROR_INVALID_PARAMETER);
345 return FALSE;
348 SERVER_START_REQ(set_console_input_info)
350 req->handle = 0;
351 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
352 req->output_cp = cp;
353 ret = !wine_server_call_err(req);
355 SERVER_END_REQ;
357 return ret;
361 /***********************************************************************
362 * Beep (KERNEL32.@)
364 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
366 static const char beep = '\a';
367 /* dwFreq and dwDur are ignored by Win95 */
368 if (isatty(2)) write( 2, &beep, 1 );
369 return TRUE;
373 /******************************************************************
374 * OpenConsoleW (KERNEL32.@)
376 * Undocumented
377 * Open a handle to the current process console.
378 * Returns INVALID_HANDLE_VALUE on failure.
380 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
382 HANDLE output = INVALID_HANDLE_VALUE;
383 HANDLE ret;
385 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
387 if (name)
389 if (strcmpiW(coninW, name) == 0)
390 output = (HANDLE) FALSE;
391 else if (strcmpiW(conoutW, name) == 0)
392 output = (HANDLE) TRUE;
395 if (output == INVALID_HANDLE_VALUE)
397 SetLastError(ERROR_INVALID_PARAMETER);
398 return INVALID_HANDLE_VALUE;
400 else if (creation != OPEN_EXISTING)
402 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
403 SetLastError(ERROR_SHARING_VIOLATION);
404 else
405 SetLastError(ERROR_INVALID_PARAMETER);
406 return INVALID_HANDLE_VALUE;
409 SERVER_START_REQ( open_console )
411 req->from = wine_server_obj_handle( output );
412 req->access = access;
413 req->attributes = inherit ? OBJ_INHERIT : 0;
414 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
415 wine_server_call_err( req );
416 ret = wine_server_ptr_handle( reply->handle );
418 SERVER_END_REQ;
419 if (ret)
420 ret = console_handle_map(ret);
422 return ret;
425 /******************************************************************
426 * VerifyConsoleIoHandle (KERNEL32.@)
428 * Undocumented
430 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
432 BOOL ret;
434 if (!is_console_handle(handle)) return FALSE;
435 SERVER_START_REQ(get_console_mode)
437 req->handle = console_handle_unmap(handle);
438 ret = !wine_server_call( req );
440 SERVER_END_REQ;
441 return ret;
444 /******************************************************************
445 * DuplicateConsoleHandle (KERNEL32.@)
447 * Undocumented
449 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
450 DWORD options)
452 HANDLE ret;
454 if (!is_console_handle(handle) ||
455 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
456 GetCurrentProcess(), &ret, access, inherit, options))
457 return INVALID_HANDLE_VALUE;
458 return console_handle_map(ret);
461 /******************************************************************
462 * CloseConsoleHandle (KERNEL32.@)
464 * Undocumented
466 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
468 if (!is_console_handle(handle))
470 SetLastError(ERROR_INVALID_PARAMETER);
471 return FALSE;
473 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
476 /******************************************************************
477 * GetConsoleInputWaitHandle (KERNEL32.@)
479 * Undocumented
481 HANDLE WINAPI GetConsoleInputWaitHandle(void)
483 if (!console_wait_event)
485 SERVER_START_REQ(get_console_wait_event)
487 if (!wine_server_call_err( req ))
488 console_wait_event = wine_server_ptr_handle( reply->handle );
490 SERVER_END_REQ;
492 return console_wait_event;
496 /******************************************************************************
497 * WriteConsoleInputA [KERNEL32.@]
499 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
500 DWORD count, LPDWORD written )
502 INPUT_RECORD *recW;
503 BOOL ret;
505 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
506 memcpy( recW, buffer, count*sizeof(*recW) );
507 input_records_AtoW( recW, count );
508 ret = WriteConsoleInputW( handle, recW, count, written );
509 HeapFree( GetProcessHeap(), 0, recW );
510 return ret;
514 /******************************************************************************
515 * WriteConsoleInputW [KERNEL32.@]
517 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
518 DWORD count, LPDWORD written )
520 BOOL ret;
522 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
524 if (written) *written = 0;
525 SERVER_START_REQ( write_console_input )
527 req->handle = console_handle_unmap(handle);
528 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
529 if ((ret = !wine_server_call_err( req )) && written)
530 *written = reply->written;
532 SERVER_END_REQ;
534 return ret;
538 /***********************************************************************
539 * WriteConsoleOutputA (KERNEL32.@)
541 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
542 COORD size, COORD coord, LPSMALL_RECT region )
544 int y;
545 BOOL ret;
546 COORD new_size, new_coord;
547 CHAR_INFO *ciw;
549 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
550 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
552 if (new_size.X <= 0 || new_size.Y <= 0)
554 region->Bottom = region->Top + new_size.Y - 1;
555 region->Right = region->Left + new_size.X - 1;
556 return TRUE;
559 /* only copy the useful rectangle */
560 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
561 return FALSE;
562 for (y = 0; y < new_size.Y; y++)
564 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
565 new_size.X * sizeof(CHAR_INFO) );
566 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
568 new_coord.X = new_coord.Y = 0;
569 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
570 HeapFree( GetProcessHeap(), 0, ciw );
571 return ret;
575 /***********************************************************************
576 * WriteConsoleOutputW (KERNEL32.@)
578 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
579 COORD size, COORD coord, LPSMALL_RECT region )
581 int width, height, y;
582 BOOL ret = TRUE;
584 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
585 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
586 region->Left, region->Top, region->Right, region->Bottom);
588 width = min( region->Right - region->Left + 1, size.X - coord.X );
589 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
591 if (width > 0 && height > 0)
593 for (y = 0; y < height; y++)
595 SERVER_START_REQ( write_console_output )
597 req->handle = console_handle_unmap(hConsoleOutput);
598 req->x = region->Left;
599 req->y = region->Top + y;
600 req->mode = CHAR_INFO_MODE_TEXTATTR;
601 req->wrap = FALSE;
602 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
603 width * sizeof(CHAR_INFO));
604 if ((ret = !wine_server_call_err( req )))
606 width = min( width, reply->width - region->Left );
607 height = min( height, reply->height - region->Top );
610 SERVER_END_REQ;
611 if (!ret) break;
614 region->Bottom = region->Top + height - 1;
615 region->Right = region->Left + width - 1;
616 return ret;
620 /******************************************************************************
621 * WriteConsoleOutputCharacterA [KERNEL32.@]
623 * See WriteConsoleOutputCharacterW.
625 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
626 COORD coord, LPDWORD lpNumCharsWritten )
628 BOOL ret;
629 LPWSTR strW;
630 DWORD lenW;
632 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
633 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
635 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
637 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
639 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
640 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
642 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
643 HeapFree( GetProcessHeap(), 0, strW );
644 return ret;
648 /******************************************************************************
649 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
650 * the console screen buffer
652 * PARAMS
653 * hConsoleOutput [I] Handle to screen buffer
654 * attr [I] Pointer to buffer with write attributes
655 * length [I] Number of cells to write to
656 * coord [I] Coords of first cell
657 * lpNumAttrsWritten [O] Pointer to number of cells written
659 * RETURNS
660 * Success: TRUE
661 * Failure: FALSE
664 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
665 COORD coord, LPDWORD lpNumAttrsWritten )
667 BOOL ret;
669 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
671 SERVER_START_REQ( write_console_output )
673 req->handle = console_handle_unmap(hConsoleOutput);
674 req->x = coord.X;
675 req->y = coord.Y;
676 req->mode = CHAR_INFO_MODE_ATTR;
677 req->wrap = TRUE;
678 wine_server_add_data( req, attr, length * sizeof(WORD) );
679 if ((ret = !wine_server_call_err( req )))
681 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
684 SERVER_END_REQ;
685 return ret;
689 /******************************************************************************
690 * FillConsoleOutputCharacterA [KERNEL32.@]
692 * See FillConsoleOutputCharacterW.
694 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
695 COORD coord, LPDWORD lpNumCharsWritten )
697 WCHAR wch;
699 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
700 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
704 /******************************************************************************
705 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
707 * PARAMS
708 * hConsoleOutput [I] Handle to screen buffer
709 * ch [I] Character to write
710 * length [I] Number of cells to write to
711 * coord [I] Coords of first cell
712 * lpNumCharsWritten [O] Pointer to number of cells written
714 * RETURNS
715 * Success: TRUE
716 * Failure: FALSE
718 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
719 COORD coord, LPDWORD lpNumCharsWritten)
721 BOOL ret;
723 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
724 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
726 SERVER_START_REQ( fill_console_output )
728 req->handle = console_handle_unmap(hConsoleOutput);
729 req->x = coord.X;
730 req->y = coord.Y;
731 req->mode = CHAR_INFO_MODE_TEXT;
732 req->wrap = TRUE;
733 req->data.ch = ch;
734 req->count = length;
735 if ((ret = !wine_server_call_err( req )))
737 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
740 SERVER_END_REQ;
741 return ret;
745 /******************************************************************************
746 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
748 * PARAMS
749 * hConsoleOutput [I] Handle to screen buffer
750 * attr [I] Color attribute to write
751 * length [I] Number of cells to write to
752 * coord [I] Coords of first cell
753 * lpNumAttrsWritten [O] Pointer to number of cells written
755 * RETURNS
756 * Success: TRUE
757 * Failure: FALSE
759 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
760 COORD coord, LPDWORD lpNumAttrsWritten )
762 BOOL ret;
764 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
765 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
767 SERVER_START_REQ( fill_console_output )
769 req->handle = console_handle_unmap(hConsoleOutput);
770 req->x = coord.X;
771 req->y = coord.Y;
772 req->mode = CHAR_INFO_MODE_ATTR;
773 req->wrap = TRUE;
774 req->data.attr = attr;
775 req->count = length;
776 if ((ret = !wine_server_call_err( req )))
778 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
781 SERVER_END_REQ;
782 return ret;
786 /******************************************************************************
787 * ReadConsoleOutputCharacterA [KERNEL32.@]
790 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
791 COORD coord, LPDWORD read_count)
793 DWORD read;
794 BOOL ret;
795 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
797 if (read_count) *read_count = 0;
798 if (!wptr) return FALSE;
800 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
802 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
803 if (read_count) *read_count = read;
805 HeapFree( GetProcessHeap(), 0, wptr );
806 return ret;
810 /******************************************************************************
811 * ReadConsoleOutputCharacterW [KERNEL32.@]
814 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
815 COORD coord, LPDWORD read_count )
817 BOOL ret;
819 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
821 SERVER_START_REQ( read_console_output )
823 req->handle = console_handle_unmap(hConsoleOutput);
824 req->x = coord.X;
825 req->y = coord.Y;
826 req->mode = CHAR_INFO_MODE_TEXT;
827 req->wrap = TRUE;
828 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
829 if ((ret = !wine_server_call_err( req )))
831 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
834 SERVER_END_REQ;
835 return ret;
839 /******************************************************************************
840 * ReadConsoleOutputAttribute [KERNEL32.@]
842 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
843 COORD coord, LPDWORD read_count)
845 BOOL ret;
847 TRACE("(%p,%p,%d,%dx%d,%p)\n",
848 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
850 SERVER_START_REQ( read_console_output )
852 req->handle = console_handle_unmap(hConsoleOutput);
853 req->x = coord.X;
854 req->y = coord.Y;
855 req->mode = CHAR_INFO_MODE_ATTR;
856 req->wrap = TRUE;
857 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
858 if ((ret = !wine_server_call_err( req )))
860 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
863 SERVER_END_REQ;
864 return ret;
868 /******************************************************************************
869 * ReadConsoleOutputA [KERNEL32.@]
872 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
873 COORD coord, LPSMALL_RECT region )
875 BOOL ret;
876 int y;
878 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
879 if (ret && region->Right >= region->Left)
881 for (y = 0; y <= region->Bottom - region->Top; y++)
883 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
884 region->Right - region->Left + 1 );
887 return ret;
891 /******************************************************************************
892 * ReadConsoleOutputW [KERNEL32.@]
894 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
895 * think we need to be *that* compatible. -- AJ
897 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
898 COORD coord, LPSMALL_RECT region )
900 int width, height, y;
901 BOOL ret = TRUE;
903 width = min( region->Right - region->Left + 1, size.X - coord.X );
904 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
906 if (width > 0 && height > 0)
908 for (y = 0; y < height; y++)
910 SERVER_START_REQ( read_console_output )
912 req->handle = console_handle_unmap(hConsoleOutput);
913 req->x = region->Left;
914 req->y = region->Top + y;
915 req->mode = CHAR_INFO_MODE_TEXTATTR;
916 req->wrap = FALSE;
917 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
918 width * sizeof(CHAR_INFO) );
919 if ((ret = !wine_server_call_err( req )))
921 width = min( width, reply->width - region->Left );
922 height = min( height, reply->height - region->Top );
925 SERVER_END_REQ;
926 if (!ret) break;
929 region->Bottom = region->Top + height - 1;
930 region->Right = region->Left + width - 1;
931 return ret;
935 /******************************************************************************
936 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
938 * PARAMS
939 * handle [I] Handle to console input buffer
940 * buffer [O] Address of buffer for read data
941 * count [I] Number of records to read
942 * pRead [O] Address of number of records read
944 * RETURNS
945 * Success: TRUE
946 * Failure: FALSE
948 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
950 DWORD read;
952 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
953 input_records_WtoA( buffer, read );
954 if (pRead) *pRead = read;
955 return TRUE;
959 /***********************************************************************
960 * PeekConsoleInputA (KERNEL32.@)
962 * Gets 'count' first events (or less) from input queue.
964 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
966 DWORD read;
968 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
969 input_records_WtoA( buffer, read );
970 if (pRead) *pRead = read;
971 return TRUE;
975 /***********************************************************************
976 * PeekConsoleInputW (KERNEL32.@)
978 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
980 BOOL ret;
981 SERVER_START_REQ( read_console_input )
983 req->handle = console_handle_unmap(handle);
984 req->flush = FALSE;
985 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
986 if ((ret = !wine_server_call_err( req )))
988 if (read) *read = count ? reply->read : 0;
991 SERVER_END_REQ;
992 return ret;
996 /***********************************************************************
997 * GetNumberOfConsoleInputEvents (KERNEL32.@)
999 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
1001 BOOL ret;
1002 SERVER_START_REQ( read_console_input )
1004 req->handle = console_handle_unmap(handle);
1005 req->flush = FALSE;
1006 if ((ret = !wine_server_call_err( req )))
1008 if (nrofevents) *nrofevents = reply->read;
1011 SERVER_END_REQ;
1012 return ret;
1016 /******************************************************************************
1017 * read_console_input
1019 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
1021 * Returns
1022 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
1024 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
1025 static const int vkkeyscan_table[256] =
1027 0,0,0,0,0,0,0,0,8,9,0,0,0,13,0,0,0,0,0,19,145,556,0,0,0,0,0,27,0,0,0,
1028 0,32,305,478,307,308,309,311,222,313,304,312,443,188,189,190,191,48,
1029 49,50,51,52,53,54,55,56,57,442,186,444,187,446,447,306,321,322,323,
1030 324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,
1031 341,342,343,344,345,346,219,220,221,310,445,192,65,66,67,68,69,70,71,
1032 72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,475,476,477,
1033 448,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1034 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1035 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1036 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,400,0,0,0,0,0,0
1039 static const int mapvkey_0[256] =
1041 0,0,0,0,0,0,0,0,14,15,0,0,0,28,0,0,42,29,56,69,58,0,0,0,0,0,0,1,0,0,
1042 0,0,57,73,81,79,71,75,72,77,80,0,0,0,55,82,83,0,11,2,3,4,5,6,7,8,9,
1043 10,0,0,0,0,0,0,0,30,48,46,32,18,33,34,35,23,36,37,38,50,49,24,25,16,
1044 19,31,20,22,47,17,45,21,44,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,55,78,0,74,
1045 0,53,59,60,61,62,63,64,65,66,67,68,87,88,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1046 0,0,0,0,0,0,69,70,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1047 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,39,13,51,12,52,53,41,0,0,0,0,0,0,0,0,0,
1048 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,43,27,40,76,96,0,0,0,0,0,0,0,0,
1049 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
1052 static inline void init_complex_char(INPUT_RECORD* ir, BOOL down, WORD vk, WORD kc, DWORD cks)
1054 ir->EventType = KEY_EVENT;
1055 ir->Event.KeyEvent.bKeyDown = down;
1056 ir->Event.KeyEvent.wRepeatCount = 1;
1057 ir->Event.KeyEvent.wVirtualScanCode = vk;
1058 ir->Event.KeyEvent.wVirtualKeyCode = kc;
1059 ir->Event.KeyEvent.dwControlKeyState = cks;
1060 ir->Event.KeyEvent.uChar.UnicodeChar = 0;
1063 /******************************************************************
1064 * handle_simple_char
1068 static BOOL handle_simple_char(HANDLE conin, unsigned real_inchar)
1070 unsigned vk;
1071 unsigned inchar;
1072 char ch;
1073 unsigned numEvent = 0;
1074 DWORD cks = 0, written;
1075 INPUT_RECORD ir[8];
1077 switch (real_inchar)
1079 case 9: inchar = real_inchar;
1080 real_inchar = 27; /* so that we don't think key is ctrl- something */
1081 break;
1082 case 13:
1083 case 10: inchar = '\r';
1084 real_inchar = 27; /* Fixme: so that we don't think key is ctrl- something */
1085 break;
1086 case 127: inchar = '\b';
1087 break;
1088 default:
1089 inchar = real_inchar;
1090 break;
1092 if ((inchar & ~0xFF) != 0) FIXME("What a char (%u)\n", inchar);
1093 vk = vkkeyscan_table[inchar];
1094 if (vk & 0x0100)
1095 init_complex_char(&ir[numEvent++], 1, 0x2a, 0x10, SHIFT_PRESSED);
1096 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1097 init_complex_char(&ir[numEvent++], 1, 0x1d, 0x11, LEFT_CTRL_PRESSED);
1098 if (vk & 0x0400)
1099 init_complex_char(&ir[numEvent++], 1, 0x38, 0x12, LEFT_ALT_PRESSED);
1101 ir[numEvent].EventType = KEY_EVENT;
1102 ir[numEvent].Event.KeyEvent.bKeyDown = 1;
1103 ir[numEvent].Event.KeyEvent.wRepeatCount = 1;
1104 ir[numEvent].Event.KeyEvent.dwControlKeyState = cks;
1105 if (vk & 0x0100)
1106 ir[numEvent].Event.KeyEvent.dwControlKeyState |= SHIFT_PRESSED;
1107 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1108 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_CTRL_PRESSED;
1109 if (vk & 0x0400)
1110 ir[numEvent].Event.KeyEvent.dwControlKeyState |= LEFT_ALT_PRESSED;
1111 ir[numEvent].Event.KeyEvent.wVirtualKeyCode = vk;
1112 ir[numEvent].Event.KeyEvent.wVirtualScanCode = mapvkey_0[vk & 0x00ff]; /* VirtualKeyCodes to ScanCode */
1114 ch = inchar;
1115 MultiByteToWideChar(CP_UNIXCP, 0, &ch, 1, &ir[numEvent].Event.KeyEvent.uChar.UnicodeChar, 1);
1116 ir[numEvent + 1] = ir[numEvent];
1117 ir[numEvent + 1].Event.KeyEvent.bKeyDown = 0;
1119 numEvent += 2;
1121 if (vk & 0x0400)
1122 init_complex_char(&ir[numEvent++], 0, 0x38, 0x12, LEFT_ALT_PRESSED);
1123 if ((vk & 0x0200) || (unsigned char)real_inchar <= 26)
1124 init_complex_char(&ir[numEvent++], 0, 0x1d, 0x11, 0);
1125 if (vk & 0x0100)
1126 init_complex_char(&ir[numEvent++], 0, 0x2a, 0x10, 0);
1128 return WriteConsoleInputW(conin, ir, numEvent, &written);
1131 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, DWORD timeout)
1133 OVERLAPPED ov;
1134 enum read_console_input_return ret;
1135 char ch;
1137 /* get the real handle to the console object */
1138 handle = wine_server_ptr_handle(console_handle_unmap(handle));
1140 memset(&ov, 0, sizeof(ov));
1141 ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1143 if (ReadFile(handle, &ch, 1, NULL, &ov) ||
1144 (GetLastError() == ERROR_IO_PENDING &&
1145 WaitForSingleObject(ov.hEvent, timeout) == WAIT_OBJECT_0 &&
1146 GetOverlappedResult(handle, &ov, NULL, FALSE)))
1148 ret = handle_simple_char(handle, ch) ? rci_gotone : rci_error;
1150 else
1152 WARN("Failed read %x\n", GetLastError());
1153 ret = rci_error;
1155 CloseHandle(ov.hEvent);
1157 return ret;
1160 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
1162 int fd;
1163 enum read_console_input_return ret;
1165 if ((fd = get_console_bare_fd(handle)) != -1)
1167 put_console_into_raw_mode(fd);
1168 close(fd);
1169 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
1171 ret = bare_console_fetch_input(handle, timeout);
1172 if (ret != rci_gotone) return ret;
1175 else
1177 if (!get_console_mode(handle, NULL, NULL)) return rci_error;
1179 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
1180 return rci_timeout;
1183 SERVER_START_REQ( read_console_input )
1185 req->handle = console_handle_unmap(handle);
1186 req->flush = TRUE;
1187 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
1188 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
1189 else ret = rci_gotone;
1191 SERVER_END_REQ;
1193 return ret;
1197 /***********************************************************************
1198 * FlushConsoleInputBuffer (KERNEL32.@)
1200 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
1202 enum read_console_input_return last;
1203 INPUT_RECORD ir;
1205 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
1207 return last == rci_timeout;
1211 /***********************************************************************
1212 * SetConsoleTitleA (KERNEL32.@)
1214 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
1216 LPWSTR titleW;
1217 BOOL ret;
1219 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
1220 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1221 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
1222 ret = SetConsoleTitleW(titleW);
1223 HeapFree(GetProcessHeap(), 0, titleW);
1224 return ret;
1228 /***********************************************************************
1229 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
1231 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
1233 FIXME( "stub %p\n", layoutName);
1234 return TRUE;
1237 /***********************************************************************
1238 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
1240 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
1242 FIXME( "stub %p\n", layoutName);
1243 return TRUE;
1246 static WCHAR input_exe[MAX_PATH + 1];
1248 /***********************************************************************
1249 * GetConsoleInputExeNameW (KERNEL32.@)
1251 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1253 TRACE("%u %p\n", buflen, buffer);
1255 RtlEnterCriticalSection(&CONSOLE_CritSect);
1256 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1257 else SetLastError(ERROR_BUFFER_OVERFLOW);
1258 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1260 return TRUE;
1263 /***********************************************************************
1264 * GetConsoleInputExeNameA (KERNEL32.@)
1266 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1268 TRACE("%u %p\n", buflen, buffer);
1270 RtlEnterCriticalSection(&CONSOLE_CritSect);
1271 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1272 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1273 else SetLastError(ERROR_BUFFER_OVERFLOW);
1274 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1276 return TRUE;
1279 /***********************************************************************
1280 * GetConsoleTitleA (KERNEL32.@)
1282 * See GetConsoleTitleW.
1284 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1286 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1287 DWORD ret;
1289 if (!ptr) return 0;
1290 ret = GetConsoleTitleW( ptr, size );
1291 if (ret)
1293 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1294 ret = strlen(title);
1296 HeapFree(GetProcessHeap(), 0, ptr);
1297 return ret;
1301 /******************************************************************************
1302 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1304 * PARAMS
1305 * title [O] Address of buffer for title
1306 * size [I] Size of buffer
1308 * RETURNS
1309 * Success: Length of string copied
1310 * Failure: 0
1312 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1314 DWORD ret = 0;
1316 SERVER_START_REQ( get_console_input_info )
1318 req->handle = 0;
1319 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1320 if (!wine_server_call_err( req ))
1322 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1323 title[ret] = 0;
1326 SERVER_END_REQ;
1327 return ret;
1331 /***********************************************************************
1332 * GetLargestConsoleWindowSize (KERNEL32.@)
1334 * NOTE
1335 * This should return a COORD, but calling convention for returning
1336 * structures is different between Windows and gcc on i386.
1338 * VERSION: [i386]
1340 #ifdef __i386__
1341 #undef GetLargestConsoleWindowSize
1342 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1344 union {
1345 COORD c;
1346 DWORD w;
1347 } x;
1348 x.c.X = 80;
1349 x.c.Y = 24;
1350 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1351 return x.w;
1353 #endif /* defined(__i386__) */
1356 /***********************************************************************
1357 * GetLargestConsoleWindowSize (KERNEL32.@)
1359 * NOTE
1360 * This should return a COORD, but calling convention for returning
1361 * structures is different between Windows and gcc on i386.
1363 * VERSION: [!i386]
1365 #ifndef __i386__
1366 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1368 COORD c;
1369 c.X = 80;
1370 c.Y = 24;
1371 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1372 return c;
1374 #endif /* defined(__i386__) */
1376 static WCHAR* S_EditString /* = NULL */;
1377 static unsigned S_EditStrPos /* = 0 */;
1379 /***********************************************************************
1380 * FreeConsole (KERNEL32.@)
1382 BOOL WINAPI FreeConsole(VOID)
1384 BOOL ret;
1386 /* invalidate local copy of input event handle */
1387 console_wait_event = 0;
1389 SERVER_START_REQ(free_console)
1391 ret = !wine_server_call_err( req );
1393 SERVER_END_REQ;
1394 return ret;
1397 /******************************************************************
1398 * start_console_renderer
1400 * helper for AllocConsole
1401 * starts the renderer process
1403 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1404 HANDLE hEvent)
1406 char buffer[1024];
1407 int ret;
1408 PROCESS_INFORMATION pi;
1410 /* FIXME: use dynamic allocation for most of the buffers below */
1411 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1412 if ((ret > -1) && (ret < sizeof(buffer)) &&
1413 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1414 NULL, NULL, si, &pi))
1416 HANDLE wh[2];
1417 DWORD ret;
1419 wh[0] = hEvent;
1420 wh[1] = pi.hProcess;
1421 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1423 CloseHandle(pi.hThread);
1424 CloseHandle(pi.hProcess);
1426 if (ret != WAIT_OBJECT_0) return FALSE;
1428 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1429 pi.dwProcessId, pi.dwThreadId);
1431 return TRUE;
1433 return FALSE;
1436 static BOOL start_console_renderer(STARTUPINFOA* si)
1438 HANDLE hEvent = 0;
1439 LPSTR p;
1440 OBJECT_ATTRIBUTES attr;
1441 BOOL ret = FALSE;
1443 attr.Length = sizeof(attr);
1444 attr.RootDirectory = 0;
1445 attr.Attributes = OBJ_INHERIT;
1446 attr.ObjectName = NULL;
1447 attr.SecurityDescriptor = NULL;
1448 attr.SecurityQualityOfService = NULL;
1450 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1451 if (!hEvent) return FALSE;
1453 /* first try environment variable */
1454 if ((p = getenv("WINECONSOLE")) != NULL)
1456 ret = start_console_renderer_helper(p, si, hEvent);
1457 if (!ret)
1458 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1459 "trying default access\n", p);
1462 /* then try the regular PATH */
1463 if (!ret)
1464 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1466 CloseHandle(hEvent);
1467 return ret;
1470 /***********************************************************************
1471 * AllocConsole (KERNEL32.@)
1473 * creates an xterm with a pty to our program
1475 BOOL WINAPI AllocConsole(void)
1477 HANDLE handle_in = INVALID_HANDLE_VALUE;
1478 HANDLE handle_out = INVALID_HANDLE_VALUE;
1479 HANDLE handle_err = INVALID_HANDLE_VALUE;
1480 STARTUPINFOA siCurrent;
1481 STARTUPINFOA siConsole;
1482 char buffer[1024];
1484 TRACE("()\n");
1486 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1487 FALSE, OPEN_EXISTING );
1489 if (VerifyConsoleIoHandle(handle_in))
1491 /* we already have a console opened on this process, don't create a new one */
1492 CloseHandle(handle_in);
1493 return FALSE;
1496 /* invalidate local copy of input event handle */
1497 console_wait_event = 0;
1499 GetStartupInfoA(&siCurrent);
1501 memset(&siConsole, 0, sizeof(siConsole));
1502 siConsole.cb = sizeof(siConsole);
1503 /* setup a view arguments for wineconsole (it'll use them as default values) */
1504 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1506 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1507 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1508 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1510 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1512 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1513 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1515 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1517 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1518 siConsole.wShowWindow = siCurrent.wShowWindow;
1520 /* FIXME (should pass the unicode form) */
1521 if (siCurrent.lpTitle)
1522 siConsole.lpTitle = siCurrent.lpTitle;
1523 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1525 buffer[sizeof(buffer) - 1] = '\0';
1526 siConsole.lpTitle = buffer;
1529 if (!start_console_renderer(&siConsole))
1530 goto the_end;
1532 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1533 /* all std I/O handles are inheritable by default */
1534 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1535 TRUE, OPEN_EXISTING );
1536 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1538 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1539 TRUE, OPEN_EXISTING );
1540 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1542 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1543 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1544 goto the_end;
1545 } else {
1546 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1547 handle_in = siCurrent.hStdInput;
1548 handle_out = siCurrent.hStdOutput;
1549 handle_err = siCurrent.hStdError;
1552 /* NT resets the STD_*_HANDLEs on console alloc */
1553 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1554 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1555 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1557 SetLastError(ERROR_SUCCESS);
1559 return TRUE;
1561 the_end:
1562 ERR("Can't allocate console\n");
1563 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1564 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1565 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1566 FreeConsole();
1567 return FALSE;
1571 /***********************************************************************
1572 * ReadConsoleA (KERNEL32.@)
1574 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1575 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1577 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1578 DWORD ncr = 0;
1579 BOOL ret;
1581 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1582 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1584 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1585 HeapFree(GetProcessHeap(), 0, ptr);
1587 return ret;
1590 /***********************************************************************
1591 * ReadConsoleW (KERNEL32.@)
1593 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1594 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1596 DWORD charsread;
1597 LPWSTR xbuf = lpBuffer;
1598 DWORD mode;
1599 BOOL is_bare = FALSE;
1600 int fd;
1602 TRACE("(%p,%p,%d,%p,%p)\n",
1603 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1605 if (!GetConsoleMode(hConsoleInput, &mode))
1606 return FALSE;
1607 if ((fd == get_console_bare_fd(hConsoleInput)) == -1)
1609 close(fd);
1610 is_bare = TRUE;
1612 if (mode & ENABLE_LINE_INPUT)
1614 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1616 HeapFree(GetProcessHeap(), 0, S_EditString);
1617 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
1618 return FALSE;
1619 S_EditStrPos = 0;
1621 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1622 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1623 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1624 S_EditStrPos += charsread;
1626 else
1628 INPUT_RECORD ir;
1629 DWORD timeout = INFINITE;
1631 /* FIXME: should we read at least 1 char? The SDK does not say */
1632 /* wait for at least one available input record (it doesn't mean we'll have
1633 * chars stored in xbuf...)
1635 * Although SDK doc keeps silence about 1 char, SDK examples assume
1636 * that we should wait for at least one character (not key). --KS
1638 charsread = 0;
1641 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1642 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1643 ir.Event.KeyEvent.uChar.UnicodeChar)
1645 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1646 timeout = 0;
1648 } while (charsread < nNumberOfCharsToRead);
1649 /* nothing has been read */
1650 if (timeout == INFINITE) return FALSE;
1653 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1655 return TRUE;
1659 /***********************************************************************
1660 * ReadConsoleInputW (KERNEL32.@)
1662 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1663 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1665 DWORD idx = 0;
1666 DWORD timeout = INFINITE;
1668 if (!nLength)
1670 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1671 return TRUE;
1674 /* loop until we get at least one event */
1675 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1676 ++idx < nLength)
1677 timeout = 0;
1679 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1680 return idx != 0;
1684 /******************************************************************************
1685 * WriteConsoleOutputCharacterW [KERNEL32.@]
1687 * Copy character to consecutive cells in the console screen buffer.
1689 * PARAMS
1690 * hConsoleOutput [I] Handle to screen buffer
1691 * str [I] Pointer to buffer with chars to write
1692 * length [I] Number of cells to write to
1693 * coord [I] Coords of first cell
1694 * lpNumCharsWritten [O] Pointer to number of cells written
1696 * RETURNS
1697 * Success: TRUE
1698 * Failure: FALSE
1701 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1702 COORD coord, LPDWORD lpNumCharsWritten )
1704 BOOL ret;
1706 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1707 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1709 SERVER_START_REQ( write_console_output )
1711 req->handle = console_handle_unmap(hConsoleOutput);
1712 req->x = coord.X;
1713 req->y = coord.Y;
1714 req->mode = CHAR_INFO_MODE_TEXT;
1715 req->wrap = TRUE;
1716 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1717 if ((ret = !wine_server_call_err( req )))
1719 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1722 SERVER_END_REQ;
1723 return ret;
1727 /******************************************************************************
1728 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1730 * PARAMS
1731 * title [I] Address of new title
1733 * RETURNS
1734 * Success: TRUE
1735 * Failure: FALSE
1737 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1739 BOOL ret;
1741 TRACE("(%s)\n", debugstr_w(title));
1742 SERVER_START_REQ( set_console_input_info )
1744 req->handle = 0;
1745 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1746 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1747 ret = !wine_server_call_err( req );
1749 SERVER_END_REQ;
1750 return ret;
1754 /***********************************************************************
1755 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1757 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1759 FIXME("(%p): stub\n", nrofbuttons);
1760 *nrofbuttons = 2;
1761 return TRUE;
1764 /******************************************************************************
1765 * SetConsoleInputExeNameW [KERNEL32.@]
1767 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1769 TRACE("(%s)\n", debugstr_w(name));
1771 if (!name || !name[0])
1773 SetLastError(ERROR_INVALID_PARAMETER);
1774 return FALSE;
1777 RtlEnterCriticalSection(&CONSOLE_CritSect);
1778 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1779 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1781 return TRUE;
1784 /******************************************************************************
1785 * SetConsoleInputExeNameA [KERNEL32.@]
1787 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1789 int len;
1790 LPWSTR nameW;
1791 BOOL ret;
1793 if (!name || !name[0])
1795 SetLastError(ERROR_INVALID_PARAMETER);
1796 return FALSE;
1799 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1800 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1802 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1803 ret = SetConsoleInputExeNameW(nameW);
1804 HeapFree(GetProcessHeap(), 0, nameW);
1806 return ret;
1809 /******************************************************************
1810 * CONSOLE_DefaultHandler
1812 * Final control event handler
1814 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1816 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1817 ExitProcess(0);
1818 /* should never go here */
1819 return TRUE;
1822 /******************************************************************************
1823 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1825 * PARAMS
1826 * func [I] Address of handler function
1827 * add [I] Handler to add or remove
1829 * RETURNS
1830 * Success: TRUE
1831 * Failure: FALSE
1834 struct ConsoleHandler
1836 PHANDLER_ROUTINE handler;
1837 struct ConsoleHandler* next;
1840 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1841 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1843 /*****************************************************************************/
1845 /******************************************************************
1846 * SetConsoleCtrlHandler (KERNEL32.@)
1848 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1850 BOOL ret = TRUE;
1852 TRACE("(%p,%i)\n", func, add);
1854 if (!func)
1856 RtlEnterCriticalSection(&CONSOLE_CritSect);
1857 if (add)
1858 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1859 else
1860 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1861 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1863 else if (add)
1865 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1867 if (!ch) return FALSE;
1868 ch->handler = func;
1869 RtlEnterCriticalSection(&CONSOLE_CritSect);
1870 ch->next = CONSOLE_Handlers;
1871 CONSOLE_Handlers = ch;
1872 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1874 else
1876 struct ConsoleHandler** ch;
1877 RtlEnterCriticalSection(&CONSOLE_CritSect);
1878 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1880 if ((*ch)->handler == func) break;
1882 if (*ch)
1884 struct ConsoleHandler* rch = *ch;
1886 /* sanity check */
1887 if (rch == &CONSOLE_DefaultConsoleHandler)
1889 ERR("Who's trying to remove default handler???\n");
1890 SetLastError(ERROR_INVALID_PARAMETER);
1891 ret = FALSE;
1893 else
1895 *ch = rch->next;
1896 HeapFree(GetProcessHeap(), 0, rch);
1899 else
1901 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1902 SetLastError(ERROR_INVALID_PARAMETER);
1903 ret = FALSE;
1905 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1907 return ret;
1910 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1912 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1913 return EXCEPTION_EXECUTE_HANDLER;
1916 /******************************************************************
1917 * CONSOLE_SendEventThread
1919 * Internal helper to pass an event to the list on installed handlers
1921 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1923 DWORD_PTR event = (DWORD_PTR)pmt;
1924 struct ConsoleHandler* ch;
1926 if (event == CTRL_C_EVENT)
1928 BOOL caught_by_dbg = TRUE;
1929 /* First, try to pass the ctrl-C event to the debugger (if any)
1930 * If it continues, there's nothing more to do
1931 * Otherwise, we need to send the ctrl-C event to the handlers
1933 __TRY
1935 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1937 __EXCEPT(CONSOLE_CtrlEventHandler)
1939 caught_by_dbg = FALSE;
1941 __ENDTRY;
1942 if (caught_by_dbg) return 0;
1943 /* the debugger didn't continue... so, pass to ctrl handlers */
1945 RtlEnterCriticalSection(&CONSOLE_CritSect);
1946 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1948 if (ch->handler(event)) break;
1950 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1951 return 1;
1954 /******************************************************************
1955 * CONSOLE_HandleCtrlC
1957 * Check whether the shall manipulate CtrlC events
1959 int CONSOLE_HandleCtrlC(unsigned sig)
1961 /* FIXME: better test whether a console is attached to this process ??? */
1962 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1963 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1965 /* check if we have to ignore ctrl-C events */
1966 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1968 /* Create a separate thread to signal all the events.
1969 * This is needed because:
1970 * - this function can be called in an Unix signal handler (hence on an
1971 * different stack than the thread that's running). This breaks the
1972 * Win32 exception mechanisms (where the thread's stack is checked).
1973 * - since the current thread, while processing the signal, can hold the
1974 * console critical section, we need another execution environment where
1975 * we can wait on this critical section
1977 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1979 return 1;
1982 /******************************************************************************
1983 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1985 * PARAMS
1986 * dwCtrlEvent [I] Type of event
1987 * dwProcessGroupID [I] Process group ID to send event to
1989 * RETURNS
1990 * Success: True
1991 * Failure: False (and *should* [but doesn't] set LastError)
1993 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1994 DWORD dwProcessGroupID)
1996 BOOL ret;
1998 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
2000 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
2002 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
2003 return FALSE;
2006 SERVER_START_REQ( send_console_signal )
2008 req->signal = dwCtrlEvent;
2009 req->group_id = dwProcessGroupID;
2010 ret = !wine_server_call_err( req );
2012 SERVER_END_REQ;
2014 /* FIXME: Shall this function be synchronous, i.e., only return when all events
2015 * have been handled by all processes in the given group?
2016 * As of today, we don't wait...
2018 return ret;
2022 /******************************************************************************
2023 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
2025 * PARAMS
2026 * dwDesiredAccess [I] Access flag
2027 * dwShareMode [I] Buffer share mode
2028 * sa [I] Security attributes
2029 * dwFlags [I] Type of buffer to create
2030 * lpScreenBufferData [I] Reserved
2032 * NOTES
2033 * Should call SetLastError
2035 * RETURNS
2036 * Success: Handle to new console screen buffer
2037 * Failure: INVALID_HANDLE_VALUE
2039 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
2040 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
2041 LPVOID lpScreenBufferData)
2043 HANDLE ret = INVALID_HANDLE_VALUE;
2045 TRACE("(%d,%d,%p,%d,%p)\n",
2046 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
2048 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
2050 SetLastError(ERROR_INVALID_PARAMETER);
2051 return INVALID_HANDLE_VALUE;
2054 SERVER_START_REQ(create_console_output)
2056 req->handle_in = 0;
2057 req->access = dwDesiredAccess;
2058 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
2059 req->share = dwShareMode;
2060 req->fd = -1;
2061 if (!wine_server_call_err( req ))
2062 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
2064 SERVER_END_REQ;
2066 return ret;
2070 /***********************************************************************
2071 * GetConsoleScreenBufferInfo (KERNEL32.@)
2073 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
2075 BOOL ret;
2077 SERVER_START_REQ(get_console_output_info)
2079 req->handle = console_handle_unmap(hConsoleOutput);
2080 if ((ret = !wine_server_call_err( req )))
2082 csbi->dwSize.X = reply->width;
2083 csbi->dwSize.Y = reply->height;
2084 csbi->dwCursorPosition.X = reply->cursor_x;
2085 csbi->dwCursorPosition.Y = reply->cursor_y;
2086 csbi->wAttributes = reply->attr;
2087 csbi->srWindow.Left = reply->win_left;
2088 csbi->srWindow.Right = reply->win_right;
2089 csbi->srWindow.Top = reply->win_top;
2090 csbi->srWindow.Bottom = reply->win_bottom;
2091 csbi->dwMaximumWindowSize.X = reply->max_width;
2092 csbi->dwMaximumWindowSize.Y = reply->max_height;
2095 SERVER_END_REQ;
2097 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
2098 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
2099 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
2100 csbi->wAttributes,
2101 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
2102 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
2104 return ret;
2108 /******************************************************************************
2109 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
2111 * RETURNS
2112 * Success: TRUE
2113 * Failure: FALSE
2115 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
2117 BOOL ret;
2119 TRACE("(%p)\n", hConsoleOutput);
2121 SERVER_START_REQ( set_console_input_info )
2123 req->handle = 0;
2124 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
2125 req->active_sb = wine_server_obj_handle( hConsoleOutput );
2126 ret = !wine_server_call_err( req );
2128 SERVER_END_REQ;
2129 return ret;
2133 /***********************************************************************
2134 * GetConsoleMode (KERNEL32.@)
2136 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
2138 return get_console_mode(hcon, mode, NULL);
2142 /******************************************************************************
2143 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
2145 * PARAMS
2146 * hcon [I] Handle to console input or screen buffer
2147 * mode [I] Input or output mode to set
2149 * RETURNS
2150 * Success: TRUE
2151 * Failure: FALSE
2153 * mode:
2154 * ENABLE_PROCESSED_INPUT 0x01
2155 * ENABLE_LINE_INPUT 0x02
2156 * ENABLE_ECHO_INPUT 0x04
2157 * ENABLE_WINDOW_INPUT 0x08
2158 * ENABLE_MOUSE_INPUT 0x10
2160 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
2162 BOOL ret;
2164 SERVER_START_REQ(set_console_mode)
2166 req->handle = console_handle_unmap(hcon);
2167 req->mode = mode;
2168 ret = !wine_server_call_err( req );
2170 SERVER_END_REQ;
2171 /* FIXME: when resetting a console input to editline mode, I think we should
2172 * empty the S_EditString buffer
2175 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
2177 return ret;
2181 /******************************************************************
2182 * CONSOLE_WriteChars
2184 * WriteConsoleOutput helper: hides server call semantics
2185 * writes a string at a given pos with standard attribute
2187 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
2189 int written = -1;
2191 if (!nc) return 0;
2193 SERVER_START_REQ( write_console_output )
2195 req->handle = console_handle_unmap(hCon);
2196 req->x = pos->X;
2197 req->y = pos->Y;
2198 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
2199 req->wrap = FALSE;
2200 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
2201 if (!wine_server_call_err( req )) written = reply->written;
2203 SERVER_END_REQ;
2205 if (written > 0) pos->X += written;
2206 return written;
2209 /******************************************************************
2210 * next_line
2212 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
2215 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
2217 SMALL_RECT src;
2218 CHAR_INFO ci;
2219 COORD dst;
2221 csbi->dwCursorPosition.X = 0;
2222 csbi->dwCursorPosition.Y++;
2224 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
2226 src.Top = 1;
2227 src.Bottom = csbi->dwSize.Y - 1;
2228 src.Left = 0;
2229 src.Right = csbi->dwSize.X - 1;
2231 dst.X = 0;
2232 dst.Y = 0;
2234 ci.Attributes = csbi->wAttributes;
2235 ci.Char.UnicodeChar = ' ';
2237 csbi->dwCursorPosition.Y--;
2238 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
2239 return 0;
2240 return 1;
2243 /******************************************************************
2244 * write_block
2246 * WriteConsoleOutput helper: writes a block of non special characters
2247 * Block can spread on several lines, and wrapping, if needed, is
2248 * handled
2251 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2252 DWORD mode, LPCWSTR ptr, int len)
2254 int blk; /* number of chars to write on current line */
2255 int done; /* number of chars already written */
2257 if (len <= 0) return 1;
2259 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2261 for (done = 0; done < len; done += blk)
2263 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2265 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2266 return 0;
2267 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2268 return 0;
2271 else
2273 int pos = csbi->dwCursorPosition.X;
2274 /* FIXME: we could reduce the number of loops
2275 * but, in most cases we wouldn't gain lots of time (it would only
2276 * happen if we're asked to overwrite more than twice the part of the line,
2277 * which is unlikely
2279 for (done = 0; done < len; done += blk)
2281 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2283 csbi->dwCursorPosition.X = pos;
2284 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2285 return 0;
2289 return 1;
2292 /***********************************************************************
2293 * WriteConsoleW (KERNEL32.@)
2295 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2296 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2298 DWORD mode;
2299 DWORD nw = 0;
2300 const WCHAR* psz = lpBuffer;
2301 CONSOLE_SCREEN_BUFFER_INFO csbi;
2302 int k, first = 0, fd;
2304 TRACE("%p %s %d %p %p\n",
2305 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2306 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2308 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2310 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
2312 char* ptr;
2313 unsigned len;
2314 BOOL ret;
2316 close(fd);
2317 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
2318 * to do the job
2320 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
2321 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
2322 return FALSE;
2324 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
2325 ret = WriteFile(wine_server_ptr_handle(console_handle_unmap(hConsoleOutput)),
2326 ptr, len, lpNumberOfCharsWritten, NULL);
2327 if (ret && lpNumberOfCharsWritten)
2329 if (*lpNumberOfCharsWritten == len)
2330 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
2331 else
2332 FIXME("Conversion not supported yet\n");
2334 HeapFree(GetProcessHeap(), 0, ptr);
2335 return ret;
2338 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2339 return FALSE;
2341 if (!nNumberOfCharsToWrite) return TRUE;
2343 if (mode & ENABLE_PROCESSED_OUTPUT)
2345 unsigned int i;
2347 for (i = 0; i < nNumberOfCharsToWrite; i++)
2349 switch (psz[i])
2351 case '\b': case '\t': case '\n': case '\a': case '\r':
2352 /* don't handle here the i-th char... done below */
2353 if ((k = i - first) > 0)
2355 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2356 goto the_end;
2357 nw += k;
2359 first = i + 1;
2360 nw++;
2362 switch (psz[i])
2364 case '\b':
2365 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2366 break;
2367 case '\t':
2369 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2371 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2372 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2373 goto the_end;
2375 break;
2376 case '\n':
2377 next_line(hConsoleOutput, &csbi);
2378 break;
2379 case '\a':
2380 Beep(400, 300);
2381 break;
2382 case '\r':
2383 csbi.dwCursorPosition.X = 0;
2384 break;
2385 default:
2386 break;
2391 /* write the remaining block (if any) if processed output is enabled, or the
2392 * entire buffer otherwise
2394 if ((k = nNumberOfCharsToWrite - first) > 0)
2396 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2397 goto the_end;
2398 nw += k;
2401 the_end:
2402 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2403 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2404 return nw != 0;
2408 /***********************************************************************
2409 * WriteConsoleA (KERNEL32.@)
2411 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2412 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2414 BOOL ret;
2415 LPWSTR xstring;
2416 DWORD n;
2418 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2420 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2421 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2422 if (!xstring) return 0;
2424 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2426 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2428 HeapFree(GetProcessHeap(), 0, xstring);
2430 return ret;
2433 /******************************************************************************
2434 * SetConsoleCursorPosition [KERNEL32.@]
2435 * Sets the cursor position in console
2437 * PARAMS
2438 * hConsoleOutput [I] Handle of console screen buffer
2439 * dwCursorPosition [I] New cursor position coordinates
2441 * RETURNS
2442 * Success: TRUE
2443 * Failure: FALSE
2445 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2447 BOOL ret;
2448 CONSOLE_SCREEN_BUFFER_INFO csbi;
2449 int do_move = 0;
2450 int w, h;
2452 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2454 SERVER_START_REQ(set_console_output_info)
2456 req->handle = console_handle_unmap(hcon);
2457 req->cursor_x = pos.X;
2458 req->cursor_y = pos.Y;
2459 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2460 ret = !wine_server_call_err( req );
2462 SERVER_END_REQ;
2464 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2465 return FALSE;
2467 /* if cursor is no longer visible, scroll the visible window... */
2468 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2469 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2470 if (pos.X < csbi.srWindow.Left)
2472 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2473 do_move++;
2475 else if (pos.X > csbi.srWindow.Right)
2477 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2478 do_move++;
2480 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2482 if (pos.Y < csbi.srWindow.Top)
2484 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2485 do_move++;
2487 else if (pos.Y > csbi.srWindow.Bottom)
2489 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2490 do_move++;
2492 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2494 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2496 return ret;
2499 /******************************************************************************
2500 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2502 * PARAMS
2503 * hcon [I] Handle to console screen buffer
2504 * cinfo [O] Address of cursor information
2506 * RETURNS
2507 * Success: TRUE
2508 * Failure: FALSE
2510 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2512 BOOL ret;
2514 SERVER_START_REQ(get_console_output_info)
2516 req->handle = console_handle_unmap(hCon);
2517 ret = !wine_server_call_err( req );
2518 if (ret && cinfo)
2520 cinfo->dwSize = reply->cursor_size;
2521 cinfo->bVisible = reply->cursor_visible;
2524 SERVER_END_REQ;
2526 if (!ret) return FALSE;
2528 if (!cinfo)
2530 SetLastError(ERROR_INVALID_ACCESS);
2531 ret = FALSE;
2533 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2535 return ret;
2539 /******************************************************************************
2540 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2542 * PARAMS
2543 * hcon [I] Handle to console screen buffer
2544 * cinfo [I] Address of cursor information
2545 * RETURNS
2546 * Success: TRUE
2547 * Failure: FALSE
2549 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2551 BOOL ret;
2553 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2554 SERVER_START_REQ(set_console_output_info)
2556 req->handle = console_handle_unmap(hCon);
2557 req->cursor_size = cinfo->dwSize;
2558 req->cursor_visible = cinfo->bVisible;
2559 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2560 ret = !wine_server_call_err( req );
2562 SERVER_END_REQ;
2563 return ret;
2567 /******************************************************************************
2568 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2570 * PARAMS
2571 * hcon [I] Handle to console screen buffer
2572 * bAbsolute [I] Coordinate type flag
2573 * window [I] Address of new window rectangle
2574 * RETURNS
2575 * Success: TRUE
2576 * Failure: FALSE
2578 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2580 SMALL_RECT p = *window;
2581 BOOL ret;
2583 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2585 if (!bAbsolute)
2587 CONSOLE_SCREEN_BUFFER_INFO csbi;
2589 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2590 return FALSE;
2591 p.Left += csbi.srWindow.Left;
2592 p.Top += csbi.srWindow.Top;
2593 p.Right += csbi.srWindow.Right;
2594 p.Bottom += csbi.srWindow.Bottom;
2596 SERVER_START_REQ(set_console_output_info)
2598 req->handle = console_handle_unmap(hCon);
2599 req->win_left = p.Left;
2600 req->win_top = p.Top;
2601 req->win_right = p.Right;
2602 req->win_bottom = p.Bottom;
2603 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2604 ret = !wine_server_call_err( req );
2606 SERVER_END_REQ;
2608 return ret;
2612 /******************************************************************************
2613 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2615 * Sets the foreground and background color attributes of characters
2616 * written to the screen buffer.
2618 * RETURNS
2619 * Success: TRUE
2620 * Failure: FALSE
2622 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2624 BOOL ret;
2626 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2627 SERVER_START_REQ(set_console_output_info)
2629 req->handle = console_handle_unmap(hConsoleOutput);
2630 req->attr = wAttr;
2631 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2632 ret = !wine_server_call_err( req );
2634 SERVER_END_REQ;
2635 return ret;
2639 /******************************************************************************
2640 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2642 * PARAMS
2643 * hConsoleOutput [I] Handle to console screen buffer
2644 * dwSize [I] New size in character rows and cols
2646 * RETURNS
2647 * Success: TRUE
2648 * Failure: FALSE
2650 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2652 BOOL ret;
2654 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2655 SERVER_START_REQ(set_console_output_info)
2657 req->handle = console_handle_unmap(hConsoleOutput);
2658 req->width = dwSize.X;
2659 req->height = dwSize.Y;
2660 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2661 ret = !wine_server_call_err( req );
2663 SERVER_END_REQ;
2664 return ret;
2668 /******************************************************************************
2669 * ScrollConsoleScreenBufferA [KERNEL32.@]
2672 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2673 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2674 LPCHAR_INFO lpFill)
2676 CHAR_INFO ciw;
2678 ciw.Attributes = lpFill->Attributes;
2679 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2681 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2682 dwDestOrigin, &ciw);
2685 /******************************************************************
2686 * CONSOLE_FillLineUniform
2688 * Helper function for ScrollConsoleScreenBufferW
2689 * Fills a part of a line with a constant character info
2691 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2693 SERVER_START_REQ( fill_console_output )
2695 req->handle = console_handle_unmap(hConsoleOutput);
2696 req->mode = CHAR_INFO_MODE_TEXTATTR;
2697 req->x = i;
2698 req->y = j;
2699 req->count = len;
2700 req->wrap = FALSE;
2701 req->data.ch = lpFill->Char.UnicodeChar;
2702 req->data.attr = lpFill->Attributes;
2703 wine_server_call_err( req );
2705 SERVER_END_REQ;
2708 /******************************************************************************
2709 * ScrollConsoleScreenBufferW [KERNEL32.@]
2713 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2714 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2715 LPCHAR_INFO lpFill)
2717 SMALL_RECT dst;
2718 DWORD ret;
2719 int i, j;
2720 int start = -1;
2721 SMALL_RECT clip;
2722 CONSOLE_SCREEN_BUFFER_INFO csbi;
2723 BOOL inside;
2724 COORD src;
2726 if (lpClipRect)
2727 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2728 lpScrollRect->Left, lpScrollRect->Top,
2729 lpScrollRect->Right, lpScrollRect->Bottom,
2730 lpClipRect->Left, lpClipRect->Top,
2731 lpClipRect->Right, lpClipRect->Bottom,
2732 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2733 else
2734 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2735 lpScrollRect->Left, lpScrollRect->Top,
2736 lpScrollRect->Right, lpScrollRect->Bottom,
2737 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2739 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2740 return FALSE;
2742 src.X = lpScrollRect->Left;
2743 src.Y = lpScrollRect->Top;
2745 /* step 1: get dst rect */
2746 dst.Left = dwDestOrigin.X;
2747 dst.Top = dwDestOrigin.Y;
2748 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2749 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2751 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2752 if (lpClipRect)
2754 clip.Left = max(0, lpClipRect->Left);
2755 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2756 clip.Top = max(0, lpClipRect->Top);
2757 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2759 else
2761 clip.Left = 0;
2762 clip.Right = csbi.dwSize.X - 1;
2763 clip.Top = 0;
2764 clip.Bottom = csbi.dwSize.Y - 1;
2766 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2768 /* step 2b: clip dst rect */
2769 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2770 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2771 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2772 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2774 /* step 3: transfer the bits */
2775 SERVER_START_REQ(move_console_output)
2777 req->handle = console_handle_unmap(hConsoleOutput);
2778 req->x_src = src.X;
2779 req->y_src = src.Y;
2780 req->x_dst = dst.Left;
2781 req->y_dst = dst.Top;
2782 req->w = dst.Right - dst.Left + 1;
2783 req->h = dst.Bottom - dst.Top + 1;
2784 ret = !wine_server_call_err( req );
2786 SERVER_END_REQ;
2788 if (!ret) return FALSE;
2790 /* step 4: clean out the exposed part */
2792 /* have to write cell [i,j] if it is not in dst rect (because it has already
2793 * been written to by the scroll) and is in clip (we shall not write
2794 * outside of clip)
2796 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2798 inside = dst.Top <= j && j <= dst.Bottom;
2799 start = -1;
2800 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2802 if (inside && dst.Left <= i && i <= dst.Right)
2804 if (start != -1)
2806 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2807 start = -1;
2810 else
2812 if (start == -1) start = i;
2815 if (start != -1)
2816 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2819 return TRUE;
2822 /******************************************************************
2823 * AttachConsole (KERNEL32.@)
2825 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2827 FIXME("stub %x\n",dwProcessId);
2828 return TRUE;
2831 /******************************************************************
2832 * GetConsoleDisplayMode (KERNEL32.@)
2834 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2836 TRACE("semi-stub: %p\n", lpModeFlags);
2837 /* It is safe to successfully report windowed mode */
2838 *lpModeFlags = 0;
2839 return TRUE;
2842 /******************************************************************
2843 * SetConsoleDisplayMode (KERNEL32.@)
2845 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2846 COORD *lpNewScreenBufferDimensions)
2848 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2849 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2850 if (dwFlags == 1)
2852 /* We cannot switch to fullscreen */
2853 return FALSE;
2855 return TRUE;
2859 /* ====================================================================
2861 * Console manipulation functions
2863 * ====================================================================*/
2865 /* some missing functions...
2866 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2867 * should get the right API and implement them
2868 * GetConsoleCommandHistory[AW] (dword dword dword)
2869 * GetConsoleCommandHistoryLength[AW]
2870 * SetConsoleCommandHistoryMode
2871 * SetConsoleNumberOfCommands[AW]
2873 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2875 int len = 0;
2877 SERVER_START_REQ( get_console_input_history )
2879 req->handle = 0;
2880 req->index = idx;
2881 if (buf && buf_len > 1)
2883 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2885 if (!wine_server_call_err( req ))
2887 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2888 len = reply->total / sizeof(WCHAR) + 1;
2891 SERVER_END_REQ;
2892 return len;
2895 /******************************************************************
2896 * CONSOLE_AppendHistory
2900 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2902 size_t len = strlenW(ptr);
2903 BOOL ret;
2905 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2906 if (!len) return FALSE;
2908 SERVER_START_REQ( append_console_input_history )
2910 req->handle = 0;
2911 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2912 ret = !wine_server_call_err( req );
2914 SERVER_END_REQ;
2915 return ret;
2918 /******************************************************************
2919 * CONSOLE_GetNumHistoryEntries
2923 unsigned CONSOLE_GetNumHistoryEntries(void)
2925 unsigned ret = -1;
2926 SERVER_START_REQ(get_console_input_info)
2928 req->handle = 0;
2929 if (!wine_server_call_err( req )) ret = reply->history_index;
2931 SERVER_END_REQ;
2932 return ret;
2935 /******************************************************************
2936 * CONSOLE_GetEditionMode
2940 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2942 unsigned ret = FALSE;
2943 SERVER_START_REQ(get_console_input_info)
2945 req->handle = console_handle_unmap(hConIn);
2946 if ((ret = !wine_server_call_err( req )))
2947 *mode = reply->edition_mode;
2949 SERVER_END_REQ;
2950 return ret;
2953 /******************************************************************
2954 * GetConsoleAliasW
2957 * RETURNS
2958 * 0 if an error occurred, non-zero for success
2961 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
2962 DWORD TargetBufferLength, LPWSTR lpExename)
2964 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
2965 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2966 return 0;
2969 /******************************************************************
2970 * GetConsoleProcessList (KERNEL32.@)
2972 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
2974 FIXME("(%p,%d): stub\n", processlist, processcount);
2976 if (!processlist || processcount < 1)
2978 SetLastError(ERROR_INVALID_PARAMETER);
2979 return 0;
2982 return 0;
2985 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
2987 memset(&S_termios, 0, sizeof(S_termios));
2988 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
2990 HANDLE conin;
2992 /* FIXME: to be done even if program is a GUI ? */
2993 /* This is wine specific: we have no parent (we're started from unix)
2994 * so, create a simple console with bare handles
2996 wine_server_send_fd(0);
2997 SERVER_START_REQ( alloc_console )
2999 req->access = GENERIC_READ | GENERIC_WRITE;
3000 req->attributes = OBJ_INHERIT;
3001 req->pid = 0xffffffff;
3002 req->input_fd = 0;
3003 wine_server_call( req );
3004 conin = wine_server_ptr_handle( reply->handle_in );
3005 /* reply->event shouldn't be created by server */
3007 SERVER_END_REQ;
3009 if (!params->hStdInput)
3010 params->hStdInput = conin;
3012 if (!params->hStdOutput)
3014 wine_server_send_fd(1);
3015 SERVER_START_REQ( create_console_output )
3017 req->handle_in = wine_server_obj_handle(conin);
3018 req->access = GENERIC_WRITE|GENERIC_READ;
3019 req->attributes = OBJ_INHERIT;
3020 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3021 req->fd = 1;
3022 wine_server_call(req);
3023 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
3025 SERVER_END_REQ;
3027 if (!params->hStdError)
3029 wine_server_send_fd(2);
3030 SERVER_START_REQ( create_console_output )
3032 req->handle_in = wine_server_obj_handle(conin);
3033 req->access = GENERIC_WRITE|GENERIC_READ;
3034 req->attributes = OBJ_INHERIT;
3035 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
3036 req->fd = 2;
3037 wine_server_call(req);
3038 params->hStdError = wine_server_ptr_handle(reply->handle_out);
3040 SERVER_END_REQ;
3044 /* convert value from server:
3045 * + 0 => INVALID_HANDLE_VALUE
3046 * + console handle needs to be mapped
3048 if (!params->hStdInput)
3049 params->hStdInput = INVALID_HANDLE_VALUE;
3050 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
3052 params->hStdInput = console_handle_map(params->hStdInput);
3053 save_console_mode(params->hStdInput);
3056 if (!params->hStdOutput)
3057 params->hStdOutput = INVALID_HANDLE_VALUE;
3058 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
3059 params->hStdOutput = console_handle_map(params->hStdOutput);
3061 if (!params->hStdError)
3062 params->hStdError = INVALID_HANDLE_VALUE;
3063 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
3064 params->hStdError = console_handle_map(params->hStdError);
3066 return TRUE;
3069 BOOL CONSOLE_Exit(void)
3071 /* the console is in raw mode, put it back in cooked mode */
3072 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));