msvcrt/tests: Remove a space before a '\n'.
[wine/gsoc-2012-control.git] / dlls / kernel32 / console.c
blobd247e1b9cf38a89182201f25dd63825bb3a1f758
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>
42 #include "windef.h"
43 #include "winbase.h"
44 #include "winnls.h"
45 #include "winerror.h"
46 #include "wincon.h"
47 #include "wine/winbase16.h"
48 #include "wine/server.h"
49 #include "wine/exception.h"
50 #include "wine/unicode.h"
51 #include "wine/debug.h"
52 #include "excpt.h"
53 #include "console_private.h"
54 #include "kernel_private.h"
56 WINE_DEFAULT_DEBUG_CHANNEL(console);
58 static CRITICAL_SECTION CONSOLE_CritSect;
59 static CRITICAL_SECTION_DEBUG critsect_debug =
61 0, 0, &CONSOLE_CritSect,
62 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
63 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
65 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
67 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
68 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
70 /* FIXME: this is not thread safe */
71 static HANDLE console_wait_event;
73 /* map input records to ASCII */
74 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
76 int i;
77 char ch;
79 for (i = 0; i < count; i++)
81 if (buffer[i].EventType != KEY_EVENT) continue;
82 WideCharToMultiByte( GetConsoleCP(), 0,
83 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
84 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
88 /* map input records to Unicode */
89 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
91 int i;
92 WCHAR ch;
94 for (i = 0; i < count; i++)
96 if (buffer[i].EventType != KEY_EVENT) continue;
97 MultiByteToWideChar( GetConsoleCP(), 0,
98 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
99 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
103 /* map char infos to ASCII */
104 static void char_info_WtoA( CHAR_INFO *buffer, int count )
106 char ch;
108 while (count-- > 0)
110 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
111 &ch, 1, NULL, NULL );
112 buffer->Char.AsciiChar = ch;
113 buffer++;
117 /* map char infos to Unicode */
118 static void char_info_AtoW( CHAR_INFO *buffer, int count )
120 WCHAR ch;
122 while (count-- > 0)
124 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
125 buffer->Char.UnicodeChar = ch;
126 buffer++;
131 /******************************************************************************
132 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
134 * RETURNS
135 * Success: hwnd of the console window.
136 * Failure: NULL
138 HWND WINAPI GetConsoleWindow(VOID)
140 HWND hWnd = NULL;
142 SERVER_START_REQ(get_console_input_info)
144 req->handle = 0;
145 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
147 SERVER_END_REQ;
149 return hWnd;
153 /******************************************************************************
154 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
156 * RETURNS
157 * Code page code
159 UINT WINAPI GetConsoleCP(VOID)
161 BOOL ret;
162 UINT codepage = GetOEMCP(); /* default value */
164 SERVER_START_REQ(get_console_input_info)
166 req->handle = 0;
167 ret = !wine_server_call_err(req);
168 if (ret && reply->input_cp)
169 codepage = reply->input_cp;
171 SERVER_END_REQ;
173 return codepage;
177 /******************************************************************************
178 * SetConsoleCP [KERNEL32.@]
180 BOOL WINAPI SetConsoleCP(UINT cp)
182 BOOL ret;
184 if (!IsValidCodePage(cp))
186 SetLastError(ERROR_INVALID_PARAMETER);
187 return FALSE;
190 SERVER_START_REQ(set_console_input_info)
192 req->handle = 0;
193 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
194 req->input_cp = cp;
195 ret = !wine_server_call_err(req);
197 SERVER_END_REQ;
199 return ret;
203 /***********************************************************************
204 * GetConsoleOutputCP (KERNEL32.@)
206 UINT WINAPI GetConsoleOutputCP(VOID)
208 BOOL ret;
209 UINT codepage = GetOEMCP(); /* default value */
211 SERVER_START_REQ(get_console_input_info)
213 req->handle = 0;
214 ret = !wine_server_call_err(req);
215 if (ret && reply->output_cp)
216 codepage = reply->output_cp;
218 SERVER_END_REQ;
220 return codepage;
224 /******************************************************************************
225 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
227 * PARAMS
228 * cp [I] code page to set
230 * RETURNS
231 * Success: TRUE
232 * Failure: FALSE
234 BOOL WINAPI SetConsoleOutputCP(UINT cp)
236 BOOL ret;
238 if (!IsValidCodePage(cp))
240 SetLastError(ERROR_INVALID_PARAMETER);
241 return FALSE;
244 SERVER_START_REQ(set_console_input_info)
246 req->handle = 0;
247 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
248 req->output_cp = cp;
249 ret = !wine_server_call_err(req);
251 SERVER_END_REQ;
253 return ret;
257 /***********************************************************************
258 * Beep (KERNEL32.@)
260 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
262 static const char beep = '\a';
263 /* dwFreq and dwDur are ignored by Win95 */
264 if (isatty(2)) write( 2, &beep, 1 );
265 return TRUE;
269 /******************************************************************
270 * OpenConsoleW (KERNEL32.@)
272 * Undocumented
273 * Open a handle to the current process console.
274 * Returns INVALID_HANDLE_VALUE on failure.
276 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
278 HANDLE output;
279 HANDLE ret;
281 if (strcmpiW(coninW, name) == 0)
282 output = (HANDLE) FALSE;
283 else if (strcmpiW(conoutW, name) == 0)
284 output = (HANDLE) TRUE;
285 else
287 SetLastError(ERROR_INVALID_NAME);
288 return INVALID_HANDLE_VALUE;
290 if (creation != OPEN_EXISTING)
292 SetLastError(ERROR_INVALID_PARAMETER);
293 return INVALID_HANDLE_VALUE;
296 SERVER_START_REQ( open_console )
298 req->from = wine_server_obj_handle( output );
299 req->access = access;
300 req->attributes = inherit ? OBJ_INHERIT : 0;
301 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
302 SetLastError(0);
303 wine_server_call_err( req );
304 ret = wine_server_ptr_handle( reply->handle );
306 SERVER_END_REQ;
307 if (ret)
308 ret = console_handle_map(ret);
309 else
311 /* likely, we're not attached to wineconsole
312 * let's try to return a handle to the unix-console
314 int fd = open("/dev/tty", output ? O_WRONLY : O_RDONLY);
315 ret = INVALID_HANDLE_VALUE;
316 if (fd != -1)
318 DWORD access = (output ? GENERIC_WRITE : GENERIC_READ) | SYNCHRONIZE;
319 wine_server_fd_to_handle(fd, access, inherit ? OBJ_INHERIT : 0, &ret);
320 close(fd);
323 return ret;
326 /******************************************************************
327 * VerifyConsoleIoHandle (KERNEL32.@)
329 * Undocumented
331 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
333 BOOL ret;
335 if (!is_console_handle(handle)) return FALSE;
336 SERVER_START_REQ(get_console_mode)
338 req->handle = console_handle_unmap(handle);
339 ret = !wine_server_call_err( req );
341 SERVER_END_REQ;
342 return ret;
345 /******************************************************************
346 * DuplicateConsoleHandle (KERNEL32.@)
348 * Undocumented
350 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
351 DWORD options)
353 HANDLE ret;
355 if (!is_console_handle(handle) ||
356 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
357 GetCurrentProcess(), &ret, access, inherit, options))
358 return INVALID_HANDLE_VALUE;
359 return console_handle_map(ret);
362 /******************************************************************
363 * CloseConsoleHandle (KERNEL32.@)
365 * Undocumented
367 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
369 if (!is_console_handle(handle))
371 SetLastError(ERROR_INVALID_PARAMETER);
372 return FALSE;
374 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
377 /******************************************************************
378 * GetConsoleInputWaitHandle (KERNEL32.@)
380 * Undocumented
382 HANDLE WINAPI GetConsoleInputWaitHandle(void)
384 if (!console_wait_event)
386 SERVER_START_REQ(get_console_wait_event)
388 if (!wine_server_call_err( req ))
389 console_wait_event = wine_server_ptr_handle( reply->handle );
391 SERVER_END_REQ;
393 return console_wait_event;
397 /******************************************************************************
398 * WriteConsoleInputA [KERNEL32.@]
400 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
401 DWORD count, LPDWORD written )
403 INPUT_RECORD *recW;
404 BOOL ret;
406 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
407 memcpy( recW, buffer, count*sizeof(*recW) );
408 input_records_AtoW( recW, count );
409 ret = WriteConsoleInputW( handle, recW, count, written );
410 HeapFree( GetProcessHeap(), 0, recW );
411 return ret;
415 /******************************************************************************
416 * WriteConsoleInputW [KERNEL32.@]
418 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
419 DWORD count, LPDWORD written )
421 BOOL ret;
423 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
425 if (written) *written = 0;
426 SERVER_START_REQ( write_console_input )
428 req->handle = console_handle_unmap(handle);
429 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
430 if ((ret = !wine_server_call_err( req )) && written)
431 *written = reply->written;
433 SERVER_END_REQ;
435 return ret;
439 /***********************************************************************
440 * WriteConsoleOutputA (KERNEL32.@)
442 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
443 COORD size, COORD coord, LPSMALL_RECT region )
445 int y;
446 BOOL ret;
447 COORD new_size, new_coord;
448 CHAR_INFO *ciw;
450 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
451 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
453 if (new_size.X <= 0 || new_size.Y <= 0)
455 region->Bottom = region->Top + new_size.Y - 1;
456 region->Right = region->Left + new_size.X - 1;
457 return TRUE;
460 /* only copy the useful rectangle */
461 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
462 return FALSE;
463 for (y = 0; y < new_size.Y; y++)
465 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
466 new_size.X * sizeof(CHAR_INFO) );
467 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
469 new_coord.X = new_coord.Y = 0;
470 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
471 HeapFree( GetProcessHeap(), 0, ciw );
472 return ret;
476 /***********************************************************************
477 * WriteConsoleOutputW (KERNEL32.@)
479 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
480 COORD size, COORD coord, LPSMALL_RECT region )
482 int width, height, y;
483 BOOL ret = TRUE;
485 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
486 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
487 region->Left, region->Top, region->Right, region->Bottom);
489 width = min( region->Right - region->Left + 1, size.X - coord.X );
490 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
492 if (width > 0 && height > 0)
494 for (y = 0; y < height; y++)
496 SERVER_START_REQ( write_console_output )
498 req->handle = console_handle_unmap(hConsoleOutput);
499 req->x = region->Left;
500 req->y = region->Top + y;
501 req->mode = CHAR_INFO_MODE_TEXTATTR;
502 req->wrap = FALSE;
503 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
504 width * sizeof(CHAR_INFO));
505 if ((ret = !wine_server_call_err( req )))
507 width = min( width, reply->width - region->Left );
508 height = min( height, reply->height - region->Top );
511 SERVER_END_REQ;
512 if (!ret) break;
515 region->Bottom = region->Top + height - 1;
516 region->Right = region->Left + width - 1;
517 return ret;
521 /******************************************************************************
522 * WriteConsoleOutputCharacterA [KERNEL32.@]
524 * See WriteConsoleOutputCharacterW.
526 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
527 COORD coord, LPDWORD lpNumCharsWritten )
529 BOOL ret;
530 LPWSTR strW;
531 DWORD lenW;
533 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
534 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
536 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
538 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
540 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
541 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
543 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
544 HeapFree( GetProcessHeap(), 0, strW );
545 return ret;
549 /******************************************************************************
550 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
551 * the console screen buffer
553 * PARAMS
554 * hConsoleOutput [I] Handle to screen buffer
555 * attr [I] Pointer to buffer with write attributes
556 * length [I] Number of cells to write to
557 * coord [I] Coords of first cell
558 * lpNumAttrsWritten [O] Pointer to number of cells written
560 * RETURNS
561 * Success: TRUE
562 * Failure: FALSE
565 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
566 COORD coord, LPDWORD lpNumAttrsWritten )
568 BOOL ret;
570 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
572 SERVER_START_REQ( write_console_output )
574 req->handle = console_handle_unmap(hConsoleOutput);
575 req->x = coord.X;
576 req->y = coord.Y;
577 req->mode = CHAR_INFO_MODE_ATTR;
578 req->wrap = TRUE;
579 wine_server_add_data( req, attr, length * sizeof(WORD) );
580 if ((ret = !wine_server_call_err( req )))
582 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
585 SERVER_END_REQ;
586 return ret;
590 /******************************************************************************
591 * FillConsoleOutputCharacterA [KERNEL32.@]
593 * See FillConsoleOutputCharacterW.
595 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
596 COORD coord, LPDWORD lpNumCharsWritten )
598 WCHAR wch;
600 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
601 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
605 /******************************************************************************
606 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
608 * PARAMS
609 * hConsoleOutput [I] Handle to screen buffer
610 * ch [I] Character to write
611 * length [I] Number of cells to write to
612 * coord [I] Coords of first cell
613 * lpNumCharsWritten [O] Pointer to number of cells written
615 * RETURNS
616 * Success: TRUE
617 * Failure: FALSE
619 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
620 COORD coord, LPDWORD lpNumCharsWritten)
622 BOOL ret;
624 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
625 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
627 SERVER_START_REQ( fill_console_output )
629 req->handle = console_handle_unmap(hConsoleOutput);
630 req->x = coord.X;
631 req->y = coord.Y;
632 req->mode = CHAR_INFO_MODE_TEXT;
633 req->wrap = TRUE;
634 req->data.ch = ch;
635 req->count = length;
636 if ((ret = !wine_server_call_err( req )))
638 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
641 SERVER_END_REQ;
642 return ret;
646 /******************************************************************************
647 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
649 * PARAMS
650 * hConsoleOutput [I] Handle to screen buffer
651 * attr [I] Color attribute to write
652 * length [I] Number of cells to write to
653 * coord [I] Coords of first cell
654 * lpNumAttrsWritten [O] Pointer to number of cells written
656 * RETURNS
657 * Success: TRUE
658 * Failure: FALSE
660 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
661 COORD coord, LPDWORD lpNumAttrsWritten )
663 BOOL ret;
665 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
666 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
668 SERVER_START_REQ( fill_console_output )
670 req->handle = console_handle_unmap(hConsoleOutput);
671 req->x = coord.X;
672 req->y = coord.Y;
673 req->mode = CHAR_INFO_MODE_ATTR;
674 req->wrap = TRUE;
675 req->data.attr = attr;
676 req->count = length;
677 if ((ret = !wine_server_call_err( req )))
679 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
682 SERVER_END_REQ;
683 return ret;
687 /******************************************************************************
688 * ReadConsoleOutputCharacterA [KERNEL32.@]
691 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
692 COORD coord, LPDWORD read_count)
694 DWORD read;
695 BOOL ret;
696 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
698 if (read_count) *read_count = 0;
699 if (!wptr) return FALSE;
701 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
703 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
704 if (read_count) *read_count = read;
706 HeapFree( GetProcessHeap(), 0, wptr );
707 return ret;
711 /******************************************************************************
712 * ReadConsoleOutputCharacterW [KERNEL32.@]
715 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
716 COORD coord, LPDWORD read_count )
718 BOOL ret;
720 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
722 SERVER_START_REQ( read_console_output )
724 req->handle = console_handle_unmap(hConsoleOutput);
725 req->x = coord.X;
726 req->y = coord.Y;
727 req->mode = CHAR_INFO_MODE_TEXT;
728 req->wrap = TRUE;
729 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
730 if ((ret = !wine_server_call_err( req )))
732 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
735 SERVER_END_REQ;
736 return ret;
740 /******************************************************************************
741 * ReadConsoleOutputAttribute [KERNEL32.@]
743 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
744 COORD coord, LPDWORD read_count)
746 BOOL ret;
748 TRACE("(%p,%p,%d,%dx%d,%p)\n",
749 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
751 SERVER_START_REQ( read_console_output )
753 req->handle = console_handle_unmap(hConsoleOutput);
754 req->x = coord.X;
755 req->y = coord.Y;
756 req->mode = CHAR_INFO_MODE_ATTR;
757 req->wrap = TRUE;
758 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
759 if ((ret = !wine_server_call_err( req )))
761 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
764 SERVER_END_REQ;
765 return ret;
769 /******************************************************************************
770 * ReadConsoleOutputA [KERNEL32.@]
773 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
774 COORD coord, LPSMALL_RECT region )
776 BOOL ret;
777 int y;
779 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
780 if (ret && region->Right >= region->Left)
782 for (y = 0; y <= region->Bottom - region->Top; y++)
784 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
785 region->Right - region->Left + 1 );
788 return ret;
792 /******************************************************************************
793 * ReadConsoleOutputW [KERNEL32.@]
795 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
796 * think we need to be *that* compatible. -- AJ
798 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
799 COORD coord, LPSMALL_RECT region )
801 int width, height, y;
802 BOOL ret = TRUE;
804 width = min( region->Right - region->Left + 1, size.X - coord.X );
805 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
807 if (width > 0 && height > 0)
809 for (y = 0; y < height; y++)
811 SERVER_START_REQ( read_console_output )
813 req->handle = console_handle_unmap(hConsoleOutput);
814 req->x = region->Left;
815 req->y = region->Top + y;
816 req->mode = CHAR_INFO_MODE_TEXTATTR;
817 req->wrap = FALSE;
818 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
819 width * sizeof(CHAR_INFO) );
820 if ((ret = !wine_server_call_err( req )))
822 width = min( width, reply->width - region->Left );
823 height = min( height, reply->height - region->Top );
826 SERVER_END_REQ;
827 if (!ret) break;
830 region->Bottom = region->Top + height - 1;
831 region->Right = region->Left + width - 1;
832 return ret;
836 /******************************************************************************
837 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
839 * PARAMS
840 * handle [I] Handle to console input buffer
841 * buffer [O] Address of buffer for read data
842 * count [I] Number of records to read
843 * pRead [O] Address of number of records read
845 * RETURNS
846 * Success: TRUE
847 * Failure: FALSE
849 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
851 DWORD read;
853 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
854 input_records_WtoA( buffer, read );
855 if (pRead) *pRead = read;
856 return TRUE;
860 /***********************************************************************
861 * PeekConsoleInputA (KERNEL32.@)
863 * Gets 'count' first events (or less) from input queue.
865 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
867 DWORD read;
869 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
870 input_records_WtoA( buffer, read );
871 if (pRead) *pRead = read;
872 return TRUE;
876 /***********************************************************************
877 * PeekConsoleInputW (KERNEL32.@)
879 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
881 BOOL ret;
882 SERVER_START_REQ( read_console_input )
884 req->handle = console_handle_unmap(handle);
885 req->flush = FALSE;
886 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
887 if ((ret = !wine_server_call_err( req )))
889 if (read) *read = count ? reply->read : 0;
892 SERVER_END_REQ;
893 return ret;
897 /***********************************************************************
898 * GetNumberOfConsoleInputEvents (KERNEL32.@)
900 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
902 BOOL ret;
903 SERVER_START_REQ( read_console_input )
905 req->handle = console_handle_unmap(handle);
906 req->flush = FALSE;
907 if ((ret = !wine_server_call_err( req )))
909 if (nrofevents) *nrofevents = reply->read;
912 SERVER_END_REQ;
913 return ret;
917 /******************************************************************************
918 * read_console_input
920 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
922 * Returns
923 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
925 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
926 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
928 enum read_console_input_return ret;
930 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
931 return rci_timeout;
932 SERVER_START_REQ( read_console_input )
934 req->handle = console_handle_unmap(handle);
935 req->flush = TRUE;
936 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
937 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
938 else ret = rci_gotone;
940 SERVER_END_REQ;
942 return ret;
946 /***********************************************************************
947 * FlushConsoleInputBuffer (KERNEL32.@)
949 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
951 enum read_console_input_return last;
952 INPUT_RECORD ir;
954 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
956 return last == rci_timeout;
960 /***********************************************************************
961 * SetConsoleTitleA (KERNEL32.@)
963 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
965 LPWSTR titleW;
966 BOOL ret;
968 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
969 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
970 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
971 ret = SetConsoleTitleW(titleW);
972 HeapFree(GetProcessHeap(), 0, titleW);
973 return ret;
977 /***********************************************************************
978 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
980 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
982 FIXME( "stub %p\n", layoutName);
983 return TRUE;
986 /***********************************************************************
987 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
989 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
991 FIXME( "stub %p\n", layoutName);
992 return TRUE;
995 static WCHAR input_exe[MAX_PATH + 1];
997 /***********************************************************************
998 * GetConsoleInputExeNameW (KERNEL32.@)
1000 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1002 TRACE("%u %p\n", buflen, buffer);
1004 RtlEnterCriticalSection(&CONSOLE_CritSect);
1005 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1006 else SetLastError(ERROR_BUFFER_OVERFLOW);
1007 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1009 return TRUE;
1012 /***********************************************************************
1013 * GetConsoleInputExeNameA (KERNEL32.@)
1015 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1017 TRACE("%u %p\n", buflen, buffer);
1019 RtlEnterCriticalSection(&CONSOLE_CritSect);
1020 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1021 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1022 else SetLastError(ERROR_BUFFER_OVERFLOW);
1023 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1025 return TRUE;
1028 /***********************************************************************
1029 * GetConsoleTitleA (KERNEL32.@)
1031 * See GetConsoleTitleW.
1033 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1035 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1036 DWORD ret;
1038 if (!ptr) return 0;
1039 ret = GetConsoleTitleW( ptr, size );
1040 if (ret)
1042 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1043 ret = strlen(title);
1045 HeapFree(GetProcessHeap(), 0, ptr);
1046 return ret;
1050 /******************************************************************************
1051 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1053 * PARAMS
1054 * title [O] Address of buffer for title
1055 * size [I] Size of buffer
1057 * RETURNS
1058 * Success: Length of string copied
1059 * Failure: 0
1061 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1063 DWORD ret = 0;
1065 SERVER_START_REQ( get_console_input_info )
1067 req->handle = 0;
1068 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1069 if (!wine_server_call_err( req ))
1071 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1072 title[ret] = 0;
1075 SERVER_END_REQ;
1076 return ret;
1080 /***********************************************************************
1081 * GetLargestConsoleWindowSize (KERNEL32.@)
1083 * NOTE
1084 * This should return a COORD, but calling convention for returning
1085 * structures is different between Windows and gcc on i386.
1087 * VERSION: [i386]
1089 #ifdef __i386__
1090 #undef GetLargestConsoleWindowSize
1091 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1093 union {
1094 COORD c;
1095 DWORD w;
1096 } x;
1097 x.c.X = 80;
1098 x.c.Y = 24;
1099 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1100 return x.w;
1102 #endif /* defined(__i386__) */
1105 /***********************************************************************
1106 * GetLargestConsoleWindowSize (KERNEL32.@)
1108 * NOTE
1109 * This should return a COORD, but calling convention for returning
1110 * structures is different between Windows and gcc on i386.
1112 * VERSION: [!i386]
1114 #ifndef __i386__
1115 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1117 COORD c;
1118 c.X = 80;
1119 c.Y = 24;
1120 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1121 return c;
1123 #endif /* defined(__i386__) */
1125 static WCHAR* S_EditString /* = NULL */;
1126 static unsigned S_EditStrPos /* = 0 */;
1128 /***********************************************************************
1129 * FreeConsole (KERNEL32.@)
1131 BOOL WINAPI FreeConsole(VOID)
1133 BOOL ret;
1135 /* invalidate local copy of input event handle */
1136 console_wait_event = 0;
1138 SERVER_START_REQ(free_console)
1140 ret = !wine_server_call_err( req );
1142 SERVER_END_REQ;
1143 return ret;
1146 /******************************************************************
1147 * start_console_renderer
1149 * helper for AllocConsole
1150 * starts the renderer process
1152 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1153 HANDLE hEvent)
1155 char buffer[1024];
1156 int ret;
1157 PROCESS_INFORMATION pi;
1159 /* FIXME: use dynamic allocation for most of the buffers below */
1160 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1161 if ((ret > -1) && (ret < sizeof(buffer)) &&
1162 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1163 NULL, NULL, si, &pi))
1165 CloseHandle(pi.hThread);
1166 CloseHandle(pi.hProcess);
1168 if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
1170 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1171 pi.dwProcessId, pi.dwThreadId);
1173 return TRUE;
1175 return FALSE;
1178 static BOOL start_console_renderer(STARTUPINFOA* si)
1180 HANDLE hEvent = 0;
1181 LPSTR p;
1182 OBJECT_ATTRIBUTES attr;
1183 BOOL ret = FALSE;
1185 attr.Length = sizeof(attr);
1186 attr.RootDirectory = 0;
1187 attr.Attributes = OBJ_INHERIT;
1188 attr.ObjectName = NULL;
1189 attr.SecurityDescriptor = NULL;
1190 attr.SecurityQualityOfService = NULL;
1192 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
1193 if (!hEvent) return FALSE;
1195 /* first try environment variable */
1196 if ((p = getenv("WINECONSOLE")) != NULL)
1198 ret = start_console_renderer_helper(p, si, hEvent);
1199 if (!ret)
1200 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1201 "trying default access\n", p);
1204 /* then try the regular PATH */
1205 if (!ret)
1206 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1208 CloseHandle(hEvent);
1209 return ret;
1212 /***********************************************************************
1213 * AllocConsole (KERNEL32.@)
1215 * creates an xterm with a pty to our program
1217 BOOL WINAPI AllocConsole(void)
1219 HANDLE handle_in = INVALID_HANDLE_VALUE;
1220 HANDLE handle_out = INVALID_HANDLE_VALUE;
1221 HANDLE handle_err = INVALID_HANDLE_VALUE;
1222 STARTUPINFOA siCurrent;
1223 STARTUPINFOA siConsole;
1224 char buffer[1024];
1226 TRACE("()\n");
1228 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1229 FALSE, OPEN_EXISTING );
1231 if (VerifyConsoleIoHandle(handle_in))
1233 /* we already have a console opened on this process, don't create a new one */
1234 CloseHandle(handle_in);
1235 return FALSE;
1237 /* happens when we're running on a Unix console */
1238 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1240 /* invalidate local copy of input event handle */
1241 console_wait_event = 0;
1243 GetStartupInfoA(&siCurrent);
1245 memset(&siConsole, 0, sizeof(siConsole));
1246 siConsole.cb = sizeof(siConsole);
1247 /* setup a view arguments for wineconsole (it'll use them as default values) */
1248 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1250 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1251 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1252 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1254 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1256 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1257 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1259 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1261 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1262 siConsole.wShowWindow = siCurrent.wShowWindow;
1264 /* FIXME (should pass the unicode form) */
1265 if (siCurrent.lpTitle)
1266 siConsole.lpTitle = siCurrent.lpTitle;
1267 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1269 buffer[sizeof(buffer) - 1] = '\0';
1270 siConsole.lpTitle = buffer;
1273 if (!start_console_renderer(&siConsole))
1274 goto the_end;
1276 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1277 /* all std I/O handles are inheritable by default */
1278 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1279 TRUE, OPEN_EXISTING );
1280 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1282 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1283 TRUE, OPEN_EXISTING );
1284 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1286 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1287 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1288 goto the_end;
1289 } else {
1290 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1291 handle_in = siCurrent.hStdInput;
1292 handle_out = siCurrent.hStdOutput;
1293 handle_err = siCurrent.hStdError;
1296 /* NT resets the STD_*_HANDLEs on console alloc */
1297 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1298 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1299 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1301 SetLastError(ERROR_SUCCESS);
1303 return TRUE;
1305 the_end:
1306 ERR("Can't allocate console\n");
1307 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1308 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1309 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1310 FreeConsole();
1311 return FALSE;
1315 /***********************************************************************
1316 * ReadConsoleA (KERNEL32.@)
1318 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1319 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1321 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1322 DWORD ncr = 0;
1323 BOOL ret;
1325 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1326 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1328 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1329 HeapFree(GetProcessHeap(), 0, ptr);
1331 return ret;
1334 /***********************************************************************
1335 * ReadConsoleW (KERNEL32.@)
1337 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1338 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1340 DWORD charsread;
1341 LPWSTR xbuf = (LPWSTR)lpBuffer;
1342 DWORD mode;
1344 TRACE("(%p,%p,%d,%p,%p)\n",
1345 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1347 if (!GetConsoleMode(hConsoleInput, &mode))
1348 return FALSE;
1350 if (mode & ENABLE_LINE_INPUT)
1352 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1354 HeapFree(GetProcessHeap(), 0, S_EditString);
1355 if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1356 return FALSE;
1357 S_EditStrPos = 0;
1359 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1360 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1361 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1362 S_EditStrPos += charsread;
1364 else
1366 INPUT_RECORD ir;
1367 DWORD timeout = INFINITE;
1369 /* FIXME: should we read at least 1 char? The SDK does not say */
1370 /* wait for at least one available input record (it doesn't mean we'll have
1371 * chars stored in xbuf...)
1373 * Although SDK doc keeps silence about 1 char, SDK examples assume
1374 * that we should wait for at least one character (not key). --KS
1376 charsread = 0;
1379 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1380 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1381 ir.Event.KeyEvent.uChar.UnicodeChar)
1383 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1384 timeout = 0;
1386 } while (charsread < nNumberOfCharsToRead);
1387 /* nothing has been read */
1388 if (timeout == INFINITE) return FALSE;
1391 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1393 return TRUE;
1397 /***********************************************************************
1398 * ReadConsoleInputW (KERNEL32.@)
1400 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1401 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1403 DWORD idx = 0;
1404 DWORD timeout = INFINITE;
1406 if (!nLength)
1408 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1409 return TRUE;
1412 /* loop until we get at least one event */
1413 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1414 ++idx < nLength)
1415 timeout = 0;
1417 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1418 return idx != 0;
1422 /******************************************************************************
1423 * WriteConsoleOutputCharacterW [KERNEL32.@]
1425 * Copy character to consecutive cells in the console screen buffer.
1427 * PARAMS
1428 * hConsoleOutput [I] Handle to screen buffer
1429 * str [I] Pointer to buffer with chars to write
1430 * length [I] Number of cells to write to
1431 * coord [I] Coords of first cell
1432 * lpNumCharsWritten [O] Pointer to number of cells written
1434 * RETURNS
1435 * Success: TRUE
1436 * Failure: FALSE
1439 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1440 COORD coord, LPDWORD lpNumCharsWritten )
1442 BOOL ret;
1444 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1445 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1447 SERVER_START_REQ( write_console_output )
1449 req->handle = console_handle_unmap(hConsoleOutput);
1450 req->x = coord.X;
1451 req->y = coord.Y;
1452 req->mode = CHAR_INFO_MODE_TEXT;
1453 req->wrap = TRUE;
1454 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1455 if ((ret = !wine_server_call_err( req )))
1457 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1460 SERVER_END_REQ;
1461 return ret;
1465 /******************************************************************************
1466 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1468 * PARAMS
1469 * title [I] Address of new title
1471 * RETURNS
1472 * Success: TRUE
1473 * Failure: FALSE
1475 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1477 BOOL ret;
1479 TRACE("(%s)\n", debugstr_w(title));
1480 SERVER_START_REQ( set_console_input_info )
1482 req->handle = 0;
1483 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1484 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1485 ret = !wine_server_call_err( req );
1487 SERVER_END_REQ;
1488 return ret;
1492 /***********************************************************************
1493 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1495 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1497 FIXME("(%p): stub\n", nrofbuttons);
1498 *nrofbuttons = 2;
1499 return TRUE;
1502 /******************************************************************************
1503 * SetConsoleInputExeNameW [KERNEL32.@]
1505 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1507 TRACE("(%s)\n", debugstr_w(name));
1509 if (!name || !name[0])
1511 SetLastError(ERROR_INVALID_PARAMETER);
1512 return FALSE;
1515 RtlEnterCriticalSection(&CONSOLE_CritSect);
1516 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1517 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1519 return TRUE;
1522 /******************************************************************************
1523 * SetConsoleInputExeNameA [KERNEL32.@]
1525 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1527 int len;
1528 LPWSTR nameW;
1529 BOOL ret;
1531 if (!name || !name[0])
1533 SetLastError(ERROR_INVALID_PARAMETER);
1534 return FALSE;
1537 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1538 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1540 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1541 ret = SetConsoleInputExeNameW(nameW);
1542 HeapFree(GetProcessHeap(), 0, nameW);
1544 return ret;
1547 /******************************************************************
1548 * CONSOLE_DefaultHandler
1550 * Final control event handler
1552 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1554 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1555 ExitProcess(0);
1556 /* should never go here */
1557 return TRUE;
1560 /******************************************************************************
1561 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1563 * PARAMS
1564 * func [I] Address of handler function
1565 * add [I] Handler to add or remove
1567 * RETURNS
1568 * Success: TRUE
1569 * Failure: FALSE
1572 struct ConsoleHandler
1574 PHANDLER_ROUTINE handler;
1575 struct ConsoleHandler* next;
1578 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1579 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1581 /*****************************************************************************/
1583 /******************************************************************
1584 * SetConsoleCtrlHandler (KERNEL32.@)
1586 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1588 BOOL ret = TRUE;
1590 TRACE("(%p,%i)\n", func, add);
1592 if (!func)
1594 RtlEnterCriticalSection(&CONSOLE_CritSect);
1595 if (add)
1596 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1597 else
1598 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1599 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1601 else if (add)
1603 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1605 if (!ch) return FALSE;
1606 ch->handler = func;
1607 RtlEnterCriticalSection(&CONSOLE_CritSect);
1608 ch->next = CONSOLE_Handlers;
1609 CONSOLE_Handlers = ch;
1610 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1612 else
1614 struct ConsoleHandler** ch;
1615 RtlEnterCriticalSection(&CONSOLE_CritSect);
1616 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1618 if ((*ch)->handler == func) break;
1620 if (*ch)
1622 struct ConsoleHandler* rch = *ch;
1624 /* sanity check */
1625 if (rch == &CONSOLE_DefaultConsoleHandler)
1627 ERR("Who's trying to remove default handler???\n");
1628 SetLastError(ERROR_INVALID_PARAMETER);
1629 ret = FALSE;
1631 else
1633 *ch = rch->next;
1634 HeapFree(GetProcessHeap(), 0, rch);
1637 else
1639 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1640 SetLastError(ERROR_INVALID_PARAMETER);
1641 ret = FALSE;
1643 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1645 return ret;
1648 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1650 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1651 return EXCEPTION_EXECUTE_HANDLER;
1654 /******************************************************************
1655 * CONSOLE_SendEventThread
1657 * Internal helper to pass an event to the list on installed handlers
1659 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1661 DWORD_PTR event = (DWORD_PTR)pmt;
1662 struct ConsoleHandler* ch;
1664 if (event == CTRL_C_EVENT)
1666 BOOL caught_by_dbg = TRUE;
1667 /* First, try to pass the ctrl-C event to the debugger (if any)
1668 * If it continues, there's nothing more to do
1669 * Otherwise, we need to send the ctrl-C event to the handlers
1671 __TRY
1673 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1675 __EXCEPT(CONSOLE_CtrlEventHandler)
1677 caught_by_dbg = FALSE;
1679 __ENDTRY;
1680 if (caught_by_dbg) return 0;
1681 /* the debugger didn't continue... so, pass to ctrl handlers */
1683 RtlEnterCriticalSection(&CONSOLE_CritSect);
1684 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1686 if (ch->handler(event)) break;
1688 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1689 return 1;
1692 /******************************************************************
1693 * CONSOLE_HandleCtrlC
1695 * Check whether the shall manipulate CtrlC events
1697 int CONSOLE_HandleCtrlC(unsigned sig)
1699 /* FIXME: better test whether a console is attached to this process ??? */
1700 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1701 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1703 /* check if we have to ignore ctrl-C events */
1704 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1706 /* Create a separate thread to signal all the events.
1707 * This is needed because:
1708 * - this function can be called in an Unix signal handler (hence on an
1709 * different stack than the thread that's running). This breaks the
1710 * Win32 exception mechanisms (where the thread's stack is checked).
1711 * - since the current thread, while processing the signal, can hold the
1712 * console critical section, we need another execution environment where
1713 * we can wait on this critical section
1715 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1717 return 1;
1720 /******************************************************************************
1721 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1723 * PARAMS
1724 * dwCtrlEvent [I] Type of event
1725 * dwProcessGroupID [I] Process group ID to send event to
1727 * RETURNS
1728 * Success: True
1729 * Failure: False (and *should* [but doesn't] set LastError)
1731 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1732 DWORD dwProcessGroupID)
1734 BOOL ret;
1736 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
1738 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1740 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
1741 return FALSE;
1744 SERVER_START_REQ( send_console_signal )
1746 req->signal = dwCtrlEvent;
1747 req->group_id = dwProcessGroupID;
1748 ret = !wine_server_call_err( req );
1750 SERVER_END_REQ;
1752 /* FIXME: Shall this function be synchronous, i.e., only return when all events
1753 * have been handled by all processes in the given group?
1754 * As of today, we don't wait...
1756 return ret;
1760 /******************************************************************************
1761 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
1763 * PARAMS
1764 * dwDesiredAccess [I] Access flag
1765 * dwShareMode [I] Buffer share mode
1766 * sa [I] Security attributes
1767 * dwFlags [I] Type of buffer to create
1768 * lpScreenBufferData [I] Reserved
1770 * NOTES
1771 * Should call SetLastError
1773 * RETURNS
1774 * Success: Handle to new console screen buffer
1775 * Failure: INVALID_HANDLE_VALUE
1777 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1778 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1779 LPVOID lpScreenBufferData)
1781 HANDLE ret = INVALID_HANDLE_VALUE;
1783 TRACE("(%d,%d,%p,%d,%p)\n",
1784 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1786 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1788 SetLastError(ERROR_INVALID_PARAMETER);
1789 return INVALID_HANDLE_VALUE;
1792 SERVER_START_REQ(create_console_output)
1794 req->handle_in = 0;
1795 req->access = dwDesiredAccess;
1796 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
1797 req->share = dwShareMode;
1798 if (!wine_server_call_err( req ))
1799 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
1801 SERVER_END_REQ;
1803 return ret;
1807 /***********************************************************************
1808 * GetConsoleScreenBufferInfo (KERNEL32.@)
1810 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1812 BOOL ret;
1814 SERVER_START_REQ(get_console_output_info)
1816 req->handle = console_handle_unmap(hConsoleOutput);
1817 if ((ret = !wine_server_call_err( req )))
1819 csbi->dwSize.X = reply->width;
1820 csbi->dwSize.Y = reply->height;
1821 csbi->dwCursorPosition.X = reply->cursor_x;
1822 csbi->dwCursorPosition.Y = reply->cursor_y;
1823 csbi->wAttributes = reply->attr;
1824 csbi->srWindow.Left = reply->win_left;
1825 csbi->srWindow.Right = reply->win_right;
1826 csbi->srWindow.Top = reply->win_top;
1827 csbi->srWindow.Bottom = reply->win_bottom;
1828 csbi->dwMaximumWindowSize.X = reply->max_width;
1829 csbi->dwMaximumWindowSize.Y = reply->max_height;
1832 SERVER_END_REQ;
1834 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
1835 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1836 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1837 csbi->wAttributes,
1838 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1839 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1841 return ret;
1845 /******************************************************************************
1846 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
1848 * RETURNS
1849 * Success: TRUE
1850 * Failure: FALSE
1852 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1854 BOOL ret;
1856 TRACE("(%p)\n", hConsoleOutput);
1858 SERVER_START_REQ( set_console_input_info )
1860 req->handle = 0;
1861 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1862 req->active_sb = wine_server_obj_handle( hConsoleOutput );
1863 ret = !wine_server_call_err( req );
1865 SERVER_END_REQ;
1866 return ret;
1870 /***********************************************************************
1871 * GetConsoleMode (KERNEL32.@)
1873 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1875 BOOL ret;
1877 SERVER_START_REQ(get_console_mode)
1879 req->handle = console_handle_unmap(hcon);
1880 ret = !wine_server_call_err( req );
1881 if (ret && mode) *mode = reply->mode;
1883 SERVER_END_REQ;
1884 return ret;
1888 /******************************************************************************
1889 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
1891 * PARAMS
1892 * hcon [I] Handle to console input or screen buffer
1893 * mode [I] Input or output mode to set
1895 * RETURNS
1896 * Success: TRUE
1897 * Failure: FALSE
1899 * mode:
1900 * ENABLE_PROCESSED_INPUT 0x01
1901 * ENABLE_LINE_INPUT 0x02
1902 * ENABLE_ECHO_INPUT 0x04
1903 * ENABLE_WINDOW_INPUT 0x08
1904 * ENABLE_MOUSE_INPUT 0x10
1906 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1908 BOOL ret;
1910 SERVER_START_REQ(set_console_mode)
1912 req->handle = console_handle_unmap(hcon);
1913 req->mode = mode;
1914 ret = !wine_server_call_err( req );
1916 SERVER_END_REQ;
1917 /* FIXME: when resetting a console input to editline mode, I think we should
1918 * empty the S_EditString buffer
1921 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
1923 return ret;
1927 /******************************************************************
1928 * CONSOLE_WriteChars
1930 * WriteConsoleOutput helper: hides server call semantics
1931 * writes a string at a given pos with standard attribute
1933 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1935 int written = -1;
1937 if (!nc) return 0;
1939 SERVER_START_REQ( write_console_output )
1941 req->handle = console_handle_unmap(hCon);
1942 req->x = pos->X;
1943 req->y = pos->Y;
1944 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1945 req->wrap = FALSE;
1946 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1947 if (!wine_server_call_err( req )) written = reply->written;
1949 SERVER_END_REQ;
1951 if (written > 0) pos->X += written;
1952 return written;
1955 /******************************************************************
1956 * next_line
1958 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1961 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1963 SMALL_RECT src;
1964 CHAR_INFO ci;
1965 COORD dst;
1967 csbi->dwCursorPosition.X = 0;
1968 csbi->dwCursorPosition.Y++;
1970 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1972 src.Top = 1;
1973 src.Bottom = csbi->dwSize.Y - 1;
1974 src.Left = 0;
1975 src.Right = csbi->dwSize.X - 1;
1977 dst.X = 0;
1978 dst.Y = 0;
1980 ci.Attributes = csbi->wAttributes;
1981 ci.Char.UnicodeChar = ' ';
1983 csbi->dwCursorPosition.Y--;
1984 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1985 return 0;
1986 return 1;
1989 /******************************************************************
1990 * write_block
1992 * WriteConsoleOutput helper: writes a block of non special characters
1993 * Block can spread on several lines, and wrapping, if needed, is
1994 * handled
1997 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1998 DWORD mode, LPCWSTR ptr, int len)
2000 int blk; /* number of chars to write on current line */
2001 int done; /* number of chars already written */
2003 if (len <= 0) return 1;
2005 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2007 for (done = 0; done < len; done += blk)
2009 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2011 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2012 return 0;
2013 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2014 return 0;
2017 else
2019 int pos = csbi->dwCursorPosition.X;
2020 /* FIXME: we could reduce the number of loops
2021 * but, in most cases we wouldn't gain lots of time (it would only
2022 * happen if we're asked to overwrite more than twice the part of the line,
2023 * which is unlikely
2025 for (blk = done = 0; done < len; done += blk)
2027 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2029 csbi->dwCursorPosition.X = pos;
2030 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2031 return 0;
2035 return 1;
2038 /***********************************************************************
2039 * WriteConsoleW (KERNEL32.@)
2041 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2042 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2044 DWORD mode;
2045 DWORD nw = 0;
2046 const WCHAR* psz = lpBuffer;
2047 CONSOLE_SCREEN_BUFFER_INFO csbi;
2048 int k, first = 0;
2050 TRACE("%p %s %d %p %p\n",
2051 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2052 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2054 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2056 if (!GetConsoleMode(hConsoleOutput, &mode) ||
2057 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2058 return FALSE;
2060 if (!nNumberOfCharsToWrite) return TRUE;
2062 if (mode & ENABLE_PROCESSED_OUTPUT)
2064 unsigned int i;
2066 for (i = 0; i < nNumberOfCharsToWrite; i++)
2068 switch (psz[i])
2070 case '\b': case '\t': case '\n': case '\a': case '\r':
2071 /* don't handle here the i-th char... done below */
2072 if ((k = i - first) > 0)
2074 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2075 goto the_end;
2076 nw += k;
2078 first = i + 1;
2079 nw++;
2081 switch (psz[i])
2083 case '\b':
2084 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2085 break;
2086 case '\t':
2088 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2090 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2091 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2092 goto the_end;
2094 break;
2095 case '\n':
2096 next_line(hConsoleOutput, &csbi);
2097 break;
2098 case '\a':
2099 Beep(400, 300);
2100 break;
2101 case '\r':
2102 csbi.dwCursorPosition.X = 0;
2103 break;
2104 default:
2105 break;
2110 /* write the remaining block (if any) if processed output is enabled, or the
2111 * entire buffer otherwise
2113 if ((k = nNumberOfCharsToWrite - first) > 0)
2115 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2116 goto the_end;
2117 nw += k;
2120 the_end:
2121 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2122 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2123 return nw != 0;
2127 /***********************************************************************
2128 * WriteConsoleA (KERNEL32.@)
2130 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2131 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2133 BOOL ret;
2134 LPWSTR xstring;
2135 DWORD n;
2137 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2139 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2140 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2141 if (!xstring) return 0;
2143 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2145 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2147 HeapFree(GetProcessHeap(), 0, xstring);
2149 return ret;
2152 /******************************************************************************
2153 * SetConsoleCursorPosition [KERNEL32.@]
2154 * Sets the cursor position in console
2156 * PARAMS
2157 * hConsoleOutput [I] Handle of console screen buffer
2158 * dwCursorPosition [I] New cursor position coordinates
2160 * RETURNS
2161 * Success: TRUE
2162 * Failure: FALSE
2164 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2166 BOOL ret;
2167 CONSOLE_SCREEN_BUFFER_INFO csbi;
2168 int do_move = 0;
2169 int w, h;
2171 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2173 SERVER_START_REQ(set_console_output_info)
2175 req->handle = console_handle_unmap(hcon);
2176 req->cursor_x = pos.X;
2177 req->cursor_y = pos.Y;
2178 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2179 ret = !wine_server_call_err( req );
2181 SERVER_END_REQ;
2183 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2184 return FALSE;
2186 /* if cursor is no longer visible, scroll the visible window... */
2187 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2188 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2189 if (pos.X < csbi.srWindow.Left)
2191 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2192 do_move++;
2194 else if (pos.X > csbi.srWindow.Right)
2196 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2197 do_move++;
2199 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2201 if (pos.Y < csbi.srWindow.Top)
2203 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2204 do_move++;
2206 else if (pos.Y > csbi.srWindow.Bottom)
2208 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2209 do_move++;
2211 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2213 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2215 return ret;
2218 /******************************************************************************
2219 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2221 * PARAMS
2222 * hcon [I] Handle to console screen buffer
2223 * cinfo [O] Address of cursor information
2225 * RETURNS
2226 * Success: TRUE
2227 * Failure: FALSE
2229 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2231 BOOL ret;
2233 SERVER_START_REQ(get_console_output_info)
2235 req->handle = console_handle_unmap(hCon);
2236 ret = !wine_server_call_err( req );
2237 if (ret && cinfo)
2239 cinfo->dwSize = reply->cursor_size;
2240 cinfo->bVisible = reply->cursor_visible;
2243 SERVER_END_REQ;
2245 if (!ret) return FALSE;
2247 if (!cinfo)
2249 SetLastError(ERROR_INVALID_ACCESS);
2250 ret = FALSE;
2252 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2254 return ret;
2258 /******************************************************************************
2259 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2261 * PARAMS
2262 * hcon [I] Handle to console screen buffer
2263 * cinfo [I] Address of cursor information
2264 * RETURNS
2265 * Success: TRUE
2266 * Failure: FALSE
2268 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2270 BOOL ret;
2272 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2273 SERVER_START_REQ(set_console_output_info)
2275 req->handle = console_handle_unmap(hCon);
2276 req->cursor_size = cinfo->dwSize;
2277 req->cursor_visible = cinfo->bVisible;
2278 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2279 ret = !wine_server_call_err( req );
2281 SERVER_END_REQ;
2282 return ret;
2286 /******************************************************************************
2287 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2289 * PARAMS
2290 * hcon [I] Handle to console screen buffer
2291 * bAbsolute [I] Coordinate type flag
2292 * window [I] Address of new window rectangle
2293 * RETURNS
2294 * Success: TRUE
2295 * Failure: FALSE
2297 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2299 SMALL_RECT p = *window;
2300 BOOL ret;
2302 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2304 if (!bAbsolute)
2306 CONSOLE_SCREEN_BUFFER_INFO csbi;
2308 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2309 return FALSE;
2310 p.Left += csbi.srWindow.Left;
2311 p.Top += csbi.srWindow.Top;
2312 p.Right += csbi.srWindow.Right;
2313 p.Bottom += csbi.srWindow.Bottom;
2315 SERVER_START_REQ(set_console_output_info)
2317 req->handle = console_handle_unmap(hCon);
2318 req->win_left = p.Left;
2319 req->win_top = p.Top;
2320 req->win_right = p.Right;
2321 req->win_bottom = p.Bottom;
2322 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2323 ret = !wine_server_call_err( req );
2325 SERVER_END_REQ;
2327 return ret;
2331 /******************************************************************************
2332 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2334 * Sets the foreground and background color attributes of characters
2335 * written to the screen buffer.
2337 * RETURNS
2338 * Success: TRUE
2339 * Failure: FALSE
2341 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2343 BOOL ret;
2345 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2346 SERVER_START_REQ(set_console_output_info)
2348 req->handle = console_handle_unmap(hConsoleOutput);
2349 req->attr = wAttr;
2350 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2351 ret = !wine_server_call_err( req );
2353 SERVER_END_REQ;
2354 return ret;
2358 /******************************************************************************
2359 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2361 * PARAMS
2362 * hConsoleOutput [I] Handle to console screen buffer
2363 * dwSize [I] New size in character rows and cols
2365 * RETURNS
2366 * Success: TRUE
2367 * Failure: FALSE
2369 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2371 BOOL ret;
2373 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2374 SERVER_START_REQ(set_console_output_info)
2376 req->handle = console_handle_unmap(hConsoleOutput);
2377 req->width = dwSize.X;
2378 req->height = dwSize.Y;
2379 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2380 ret = !wine_server_call_err( req );
2382 SERVER_END_REQ;
2383 return ret;
2387 /******************************************************************************
2388 * ScrollConsoleScreenBufferA [KERNEL32.@]
2391 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2392 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2393 LPCHAR_INFO lpFill)
2395 CHAR_INFO ciw;
2397 ciw.Attributes = lpFill->Attributes;
2398 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2400 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2401 dwDestOrigin, &ciw);
2404 /******************************************************************
2405 * CONSOLE_FillLineUniform
2407 * Helper function for ScrollConsoleScreenBufferW
2408 * Fills a part of a line with a constant character info
2410 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2412 SERVER_START_REQ( fill_console_output )
2414 req->handle = console_handle_unmap(hConsoleOutput);
2415 req->mode = CHAR_INFO_MODE_TEXTATTR;
2416 req->x = i;
2417 req->y = j;
2418 req->count = len;
2419 req->wrap = FALSE;
2420 req->data.ch = lpFill->Char.UnicodeChar;
2421 req->data.attr = lpFill->Attributes;
2422 wine_server_call_err( req );
2424 SERVER_END_REQ;
2427 /******************************************************************************
2428 * ScrollConsoleScreenBufferW [KERNEL32.@]
2432 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2433 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2434 LPCHAR_INFO lpFill)
2436 SMALL_RECT dst;
2437 DWORD ret;
2438 int i, j;
2439 int start = -1;
2440 SMALL_RECT clip;
2441 CONSOLE_SCREEN_BUFFER_INFO csbi;
2442 BOOL inside;
2443 COORD src;
2445 if (lpClipRect)
2446 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2447 lpScrollRect->Left, lpScrollRect->Top,
2448 lpScrollRect->Right, lpScrollRect->Bottom,
2449 lpClipRect->Left, lpClipRect->Top,
2450 lpClipRect->Right, lpClipRect->Bottom,
2451 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2452 else
2453 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2454 lpScrollRect->Left, lpScrollRect->Top,
2455 lpScrollRect->Right, lpScrollRect->Bottom,
2456 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2458 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2459 return FALSE;
2461 src.X = lpScrollRect->Left;
2462 src.Y = lpScrollRect->Top;
2464 /* step 1: get dst rect */
2465 dst.Left = dwDestOrigin.X;
2466 dst.Top = dwDestOrigin.Y;
2467 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2468 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2470 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2471 if (lpClipRect)
2473 clip.Left = max(0, lpClipRect->Left);
2474 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2475 clip.Top = max(0, lpClipRect->Top);
2476 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2478 else
2480 clip.Left = 0;
2481 clip.Right = csbi.dwSize.X - 1;
2482 clip.Top = 0;
2483 clip.Bottom = csbi.dwSize.Y - 1;
2485 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2487 /* step 2b: clip dst rect */
2488 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2489 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2490 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2491 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2493 /* step 3: transfer the bits */
2494 SERVER_START_REQ(move_console_output)
2496 req->handle = console_handle_unmap(hConsoleOutput);
2497 req->x_src = src.X;
2498 req->y_src = src.Y;
2499 req->x_dst = dst.Left;
2500 req->y_dst = dst.Top;
2501 req->w = dst.Right - dst.Left + 1;
2502 req->h = dst.Bottom - dst.Top + 1;
2503 ret = !wine_server_call_err( req );
2505 SERVER_END_REQ;
2507 if (!ret) return FALSE;
2509 /* step 4: clean out the exposed part */
2511 /* have to write cell [i,j] if it is not in dst rect (because it has already
2512 * been written to by the scroll) and is in clip (we shall not write
2513 * outside of clip)
2515 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2517 inside = dst.Top <= j && j <= dst.Bottom;
2518 start = -1;
2519 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2521 if (inside && dst.Left <= i && i <= dst.Right)
2523 if (start != -1)
2525 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2526 start = -1;
2529 else
2531 if (start == -1) start = i;
2534 if (start != -1)
2535 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2538 return TRUE;
2541 /******************************************************************
2542 * AttachConsole (KERNEL32.@)
2544 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2546 FIXME("stub %x\n",dwProcessId);
2547 return TRUE;
2550 /******************************************************************
2551 * GetConsoleDisplayMode (KERNEL32.@)
2553 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2555 TRACE("semi-stub: %p\n", lpModeFlags);
2556 /* It is safe to successfully report windowed mode */
2557 *lpModeFlags = 0;
2558 return TRUE;
2561 /******************************************************************
2562 * SetConsoleDisplayMode (KERNEL32.@)
2564 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2565 COORD *lpNewScreenBufferDimensions)
2567 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2568 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2569 if (dwFlags == 1)
2571 /* We cannot switch to fullscreen */
2572 return FALSE;
2574 return TRUE;
2578 /* ====================================================================
2580 * Console manipulation functions
2582 * ====================================================================*/
2584 /* some missing functions...
2585 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2586 * should get the right API and implement them
2587 * GetConsoleCommandHistory[AW] (dword dword dword)
2588 * GetConsoleCommandHistoryLength[AW]
2589 * SetConsoleCommandHistoryMode
2590 * SetConsoleNumberOfCommands[AW]
2592 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2594 int len = 0;
2596 SERVER_START_REQ( get_console_input_history )
2598 req->handle = 0;
2599 req->index = idx;
2600 if (buf && buf_len > 1)
2602 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2604 if (!wine_server_call_err( req ))
2606 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2607 len = reply->total / sizeof(WCHAR) + 1;
2610 SERVER_END_REQ;
2611 return len;
2614 /******************************************************************
2615 * CONSOLE_AppendHistory
2619 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2621 size_t len = strlenW(ptr);
2622 BOOL ret;
2624 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2625 if (!len) return FALSE;
2627 SERVER_START_REQ( append_console_input_history )
2629 req->handle = 0;
2630 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2631 ret = !wine_server_call_err( req );
2633 SERVER_END_REQ;
2634 return ret;
2637 /******************************************************************
2638 * CONSOLE_GetNumHistoryEntries
2642 unsigned CONSOLE_GetNumHistoryEntries(void)
2644 unsigned ret = -1;
2645 SERVER_START_REQ(get_console_input_info)
2647 req->handle = 0;
2648 if (!wine_server_call_err( req )) ret = reply->history_index;
2650 SERVER_END_REQ;
2651 return ret;
2654 /******************************************************************
2655 * CONSOLE_GetEditionMode
2659 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2661 unsigned ret = FALSE;
2662 SERVER_START_REQ(get_console_input_info)
2664 req->handle = console_handle_unmap(hConIn);
2665 if ((ret = !wine_server_call_err( req )))
2666 *mode = reply->edition_mode;
2668 SERVER_END_REQ;
2669 return ret;
2672 /******************************************************************
2673 * GetConsoleAliasW
2676 * RETURNS
2677 * 0 if an error occurred, non-zero for success
2680 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
2681 DWORD TargetBufferLength, LPWSTR lpExename)
2683 static const WCHAR empty[] = {' ',0};
2685 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
2687 if(TargetBufferLength < sizeof(empty)/sizeof(WCHAR))
2688 return 0;
2690 lstrcpyW(lpTargetBuffer, empty);
2692 return 1;