push 92ef5b88da02911741c0a2f56030fd2e20189321
[wine/hacks.git] / dlls / kernel32 / console.c
blob32d02146efcc20c7f0c875e5ebf9e75949ab3db2
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 const WCHAR coninW[] = {'C','O','N','I','N','$',0};
59 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
61 /* map input records to ASCII */
62 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
64 int i;
65 char ch;
67 for (i = 0; i < count; i++)
69 if (buffer[i].EventType != KEY_EVENT) continue;
70 WideCharToMultiByte( GetConsoleCP(), 0,
71 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
72 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
76 /* map input records to Unicode */
77 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
79 int i;
80 WCHAR ch;
82 for (i = 0; i < count; i++)
84 if (buffer[i].EventType != KEY_EVENT) continue;
85 MultiByteToWideChar( GetConsoleCP(), 0,
86 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
87 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
91 /* map char infos to ASCII */
92 static void char_info_WtoA( CHAR_INFO *buffer, int count )
94 char ch;
96 while (count-- > 0)
98 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
99 &ch, 1, NULL, NULL );
100 buffer->Char.AsciiChar = ch;
101 buffer++;
105 /* map char infos to Unicode */
106 static void char_info_AtoW( CHAR_INFO *buffer, int count )
108 WCHAR ch;
110 while (count-- > 0)
112 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
113 buffer->Char.UnicodeChar = ch;
114 buffer++;
119 /******************************************************************************
120 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
122 * RETURNS
123 * Success: hwnd of the console window.
124 * Failure: NULL
126 HWND WINAPI GetConsoleWindow(VOID)
128 HWND hWnd = NULL;
130 SERVER_START_REQ(get_console_input_info)
132 req->handle = 0;
133 if (!wine_server_call_err(req)) hWnd = reply->win;
135 SERVER_END_REQ;
137 return hWnd;
141 /******************************************************************************
142 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
144 * RETURNS
145 * Code page code
147 UINT WINAPI GetConsoleCP(VOID)
149 BOOL ret;
150 UINT codepage = GetOEMCP(); /* default value */
152 SERVER_START_REQ(get_console_input_info)
154 req->handle = 0;
155 ret = !wine_server_call_err(req);
156 if (ret && reply->input_cp)
157 codepage = reply->input_cp;
159 SERVER_END_REQ;
161 return codepage;
165 /******************************************************************************
166 * SetConsoleCP [KERNEL32.@]
168 BOOL WINAPI SetConsoleCP(UINT cp)
170 BOOL ret;
172 if (!IsValidCodePage(cp))
174 SetLastError(ERROR_INVALID_PARAMETER);
175 return FALSE;
178 SERVER_START_REQ(set_console_input_info)
180 req->handle = 0;
181 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
182 req->input_cp = cp;
183 ret = !wine_server_call_err(req);
185 SERVER_END_REQ;
187 return ret;
191 /***********************************************************************
192 * GetConsoleOutputCP (KERNEL32.@)
194 UINT WINAPI GetConsoleOutputCP(VOID)
196 BOOL ret;
197 UINT codepage = GetOEMCP(); /* default value */
199 SERVER_START_REQ(get_console_input_info)
201 req->handle = 0;
202 ret = !wine_server_call_err(req);
203 if (ret && reply->output_cp)
204 codepage = reply->output_cp;
206 SERVER_END_REQ;
208 return codepage;
212 /******************************************************************************
213 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
215 * PARAMS
216 * cp [I] code page to set
218 * RETURNS
219 * Success: TRUE
220 * Failure: FALSE
222 BOOL WINAPI SetConsoleOutputCP(UINT cp)
224 BOOL ret;
226 if (!IsValidCodePage(cp))
228 SetLastError(ERROR_INVALID_PARAMETER);
229 return FALSE;
232 SERVER_START_REQ(set_console_input_info)
234 req->handle = 0;
235 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
236 req->output_cp = cp;
237 ret = !wine_server_call_err(req);
239 SERVER_END_REQ;
241 return ret;
245 /***********************************************************************
246 * Beep (KERNEL32.@)
248 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
250 static const char beep = '\a';
251 /* dwFreq and dwDur are ignored by Win95 */
252 if (isatty(2)) write( 2, &beep, 1 );
253 return TRUE;
257 /******************************************************************
258 * OpenConsoleW (KERNEL32.@)
260 * Undocumented
261 * Open a handle to the current process console.
262 * Returns INVALID_HANDLE_VALUE on failure.
264 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
266 HANDLE output;
267 HANDLE ret;
269 if (strcmpiW(coninW, name) == 0)
270 output = (HANDLE) FALSE;
271 else if (strcmpiW(conoutW, name) == 0)
272 output = (HANDLE) TRUE;
273 else
275 SetLastError(ERROR_INVALID_NAME);
276 return INVALID_HANDLE_VALUE;
278 if (creation != OPEN_EXISTING)
280 SetLastError(ERROR_INVALID_PARAMETER);
281 return INVALID_HANDLE_VALUE;
284 SERVER_START_REQ( open_console )
286 req->from = output;
287 req->access = access;
288 req->attributes = inherit ? OBJ_INHERIT : 0;
289 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
290 SetLastError(0);
291 wine_server_call_err( req );
292 ret = reply->handle;
294 SERVER_END_REQ;
295 if (ret)
296 ret = console_handle_map(ret);
297 else
299 /* likely, we're not attached to wineconsole
300 * let's try to return a handle to the unix-console
302 int fd = open("/dev/tty", output ? O_WRONLY : O_RDONLY);
303 ret = INVALID_HANDLE_VALUE;
304 if (fd != -1)
306 DWORD access = (output ? GENERIC_WRITE : GENERIC_READ) | SYNCHRONIZE;
307 wine_server_fd_to_handle(fd, access, inherit ? OBJ_INHERIT : 0, &ret);
308 close(fd);
311 return ret;
314 /******************************************************************
315 * VerifyConsoleIoHandle (KERNEL32.@)
317 * Undocumented
319 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
321 BOOL ret;
323 if (!is_console_handle(handle)) return FALSE;
324 SERVER_START_REQ(get_console_mode)
326 req->handle = console_handle_unmap(handle);
327 ret = !wine_server_call_err( req );
329 SERVER_END_REQ;
330 return ret;
333 /******************************************************************
334 * DuplicateConsoleHandle (KERNEL32.@)
336 * Undocumented
338 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
339 DWORD options)
341 HANDLE ret;
343 if (!is_console_handle(handle) ||
344 !DuplicateHandle(GetCurrentProcess(), console_handle_unmap(handle),
345 GetCurrentProcess(), &ret, access, inherit, options))
346 return INVALID_HANDLE_VALUE;
347 return console_handle_map(ret);
350 /******************************************************************
351 * CloseConsoleHandle (KERNEL32.@)
353 * Undocumented
355 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
357 if (!is_console_handle(handle))
359 SetLastError(ERROR_INVALID_PARAMETER);
360 return FALSE;
362 return CloseHandle(console_handle_unmap(handle));
365 /******************************************************************
366 * GetConsoleInputWaitHandle (KERNEL32.@)
368 * Undocumented
370 HANDLE WINAPI GetConsoleInputWaitHandle(void)
372 static HANDLE console_wait_event;
374 /* FIXME: this is not thread safe */
375 if (!console_wait_event)
377 SERVER_START_REQ(get_console_wait_event)
379 if (!wine_server_call_err( req )) console_wait_event = reply->handle;
381 SERVER_END_REQ;
383 return console_wait_event;
387 /******************************************************************************
388 * WriteConsoleInputA [KERNEL32.@]
390 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
391 DWORD count, LPDWORD written )
393 INPUT_RECORD *recW;
394 BOOL ret;
396 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
397 memcpy( recW, buffer, count*sizeof(*recW) );
398 input_records_AtoW( recW, count );
399 ret = WriteConsoleInputW( handle, recW, count, written );
400 HeapFree( GetProcessHeap(), 0, recW );
401 return ret;
405 /******************************************************************************
406 * WriteConsoleInputW [KERNEL32.@]
408 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
409 DWORD count, LPDWORD written )
411 BOOL ret;
413 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
415 if (written) *written = 0;
416 SERVER_START_REQ( write_console_input )
418 req->handle = console_handle_unmap(handle);
419 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
420 if ((ret = !wine_server_call_err( req )) && written)
421 *written = reply->written;
423 SERVER_END_REQ;
425 return ret;
429 /***********************************************************************
430 * WriteConsoleOutputA (KERNEL32.@)
432 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
433 COORD size, COORD coord, LPSMALL_RECT region )
435 int y;
436 BOOL ret;
437 COORD new_size, new_coord;
438 CHAR_INFO *ciw;
440 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
441 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
443 if (new_size.X <= 0 || new_size.Y <= 0)
445 region->Bottom = region->Top + new_size.Y - 1;
446 region->Right = region->Left + new_size.X - 1;
447 return TRUE;
450 /* only copy the useful rectangle */
451 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
452 return FALSE;
453 for (y = 0; y < new_size.Y; y++)
455 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
456 new_size.X * sizeof(CHAR_INFO) );
457 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
459 new_coord.X = new_coord.Y = 0;
460 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
461 HeapFree( GetProcessHeap(), 0, ciw );
462 return ret;
466 /***********************************************************************
467 * WriteConsoleOutputW (KERNEL32.@)
469 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
470 COORD size, COORD coord, LPSMALL_RECT region )
472 int width, height, y;
473 BOOL ret = TRUE;
475 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
476 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
477 region->Left, region->Top, region->Right, region->Bottom);
479 width = min( region->Right - region->Left + 1, size.X - coord.X );
480 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
482 if (width > 0 && height > 0)
484 for (y = 0; y < height; y++)
486 SERVER_START_REQ( write_console_output )
488 req->handle = console_handle_unmap(hConsoleOutput);
489 req->x = region->Left;
490 req->y = region->Top + y;
491 req->mode = CHAR_INFO_MODE_TEXTATTR;
492 req->wrap = FALSE;
493 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
494 width * sizeof(CHAR_INFO));
495 if ((ret = !wine_server_call_err( req )))
497 width = min( width, reply->width - region->Left );
498 height = min( height, reply->height - region->Top );
501 SERVER_END_REQ;
502 if (!ret) break;
505 region->Bottom = region->Top + height - 1;
506 region->Right = region->Left + width - 1;
507 return ret;
511 /******************************************************************************
512 * WriteConsoleOutputCharacterA [KERNEL32.@]
514 * See WriteConsoleOutputCharacterW.
516 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
517 COORD coord, LPDWORD lpNumCharsWritten )
519 BOOL ret;
520 LPWSTR strW;
521 DWORD lenW;
523 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
524 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
526 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
528 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
530 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
531 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
533 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
534 HeapFree( GetProcessHeap(), 0, strW );
535 return ret;
539 /******************************************************************************
540 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
541 * the console screen buffer
543 * PARAMS
544 * hConsoleOutput [I] Handle to screen buffer
545 * attr [I] Pointer to buffer with write attributes
546 * length [I] Number of cells to write to
547 * coord [I] Coords of first cell
548 * lpNumAttrsWritten [O] Pointer to number of cells written
550 * RETURNS
551 * Success: TRUE
552 * Failure: FALSE
555 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
556 COORD coord, LPDWORD lpNumAttrsWritten )
558 BOOL ret;
560 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
562 SERVER_START_REQ( write_console_output )
564 req->handle = console_handle_unmap(hConsoleOutput);
565 req->x = coord.X;
566 req->y = coord.Y;
567 req->mode = CHAR_INFO_MODE_ATTR;
568 req->wrap = TRUE;
569 wine_server_add_data( req, attr, length * sizeof(WORD) );
570 if ((ret = !wine_server_call_err( req )))
572 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
575 SERVER_END_REQ;
576 return ret;
580 /******************************************************************************
581 * FillConsoleOutputCharacterA [KERNEL32.@]
583 * See FillConsoleOutputCharacterW.
585 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
586 COORD coord, LPDWORD lpNumCharsWritten )
588 WCHAR wch;
590 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
591 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
595 /******************************************************************************
596 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
598 * PARAMS
599 * hConsoleOutput [I] Handle to screen buffer
600 * ch [I] Character to write
601 * length [I] Number of cells to write to
602 * coord [I] Coords of first cell
603 * lpNumCharsWritten [O] Pointer to number of cells written
605 * RETURNS
606 * Success: TRUE
607 * Failure: FALSE
609 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
610 COORD coord, LPDWORD lpNumCharsWritten)
612 BOOL ret;
614 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
615 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
617 SERVER_START_REQ( fill_console_output )
619 req->handle = console_handle_unmap(hConsoleOutput);
620 req->x = coord.X;
621 req->y = coord.Y;
622 req->mode = CHAR_INFO_MODE_TEXT;
623 req->wrap = TRUE;
624 req->data.ch = ch;
625 req->count = length;
626 if ((ret = !wine_server_call_err( req )))
628 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
631 SERVER_END_REQ;
632 return ret;
636 /******************************************************************************
637 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
639 * PARAMS
640 * hConsoleOutput [I] Handle to screen buffer
641 * attr [I] Color attribute to write
642 * length [I] Number of cells to write to
643 * coord [I] Coords of first cell
644 * lpNumAttrsWritten [O] Pointer to number of cells written
646 * RETURNS
647 * Success: TRUE
648 * Failure: FALSE
650 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
651 COORD coord, LPDWORD lpNumAttrsWritten )
653 BOOL ret;
655 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
656 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
658 SERVER_START_REQ( fill_console_output )
660 req->handle = console_handle_unmap(hConsoleOutput);
661 req->x = coord.X;
662 req->y = coord.Y;
663 req->mode = CHAR_INFO_MODE_ATTR;
664 req->wrap = TRUE;
665 req->data.attr = attr;
666 req->count = length;
667 if ((ret = !wine_server_call_err( req )))
669 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
672 SERVER_END_REQ;
673 return ret;
677 /******************************************************************************
678 * ReadConsoleOutputCharacterA [KERNEL32.@]
681 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
682 COORD coord, LPDWORD read_count)
684 DWORD read;
685 BOOL ret;
686 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
688 if (read_count) *read_count = 0;
689 if (!wptr) return FALSE;
691 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
693 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
694 if (read_count) *read_count = read;
696 HeapFree( GetProcessHeap(), 0, wptr );
697 return ret;
701 /******************************************************************************
702 * ReadConsoleOutputCharacterW [KERNEL32.@]
705 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
706 COORD coord, LPDWORD read_count )
708 BOOL ret;
710 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
712 SERVER_START_REQ( read_console_output )
714 req->handle = console_handle_unmap(hConsoleOutput);
715 req->x = coord.X;
716 req->y = coord.Y;
717 req->mode = CHAR_INFO_MODE_TEXT;
718 req->wrap = TRUE;
719 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
720 if ((ret = !wine_server_call_err( req )))
722 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
725 SERVER_END_REQ;
726 return ret;
730 /******************************************************************************
731 * ReadConsoleOutputAttribute [KERNEL32.@]
733 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
734 COORD coord, LPDWORD read_count)
736 BOOL ret;
738 TRACE("(%p,%p,%d,%dx%d,%p)\n",
739 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
741 SERVER_START_REQ( read_console_output )
743 req->handle = console_handle_unmap(hConsoleOutput);
744 req->x = coord.X;
745 req->y = coord.Y;
746 req->mode = CHAR_INFO_MODE_ATTR;
747 req->wrap = TRUE;
748 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
749 if ((ret = !wine_server_call_err( req )))
751 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
754 SERVER_END_REQ;
755 return ret;
759 /******************************************************************************
760 * ReadConsoleOutputA [KERNEL32.@]
763 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
764 COORD coord, LPSMALL_RECT region )
766 BOOL ret;
767 int y;
769 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
770 if (ret && region->Right >= region->Left)
772 for (y = 0; y <= region->Bottom - region->Top; y++)
774 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
775 region->Right - region->Left + 1 );
778 return ret;
782 /******************************************************************************
783 * ReadConsoleOutputW [KERNEL32.@]
785 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
786 * think we need to be *that* compatible. -- AJ
788 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
789 COORD coord, LPSMALL_RECT region )
791 int width, height, y;
792 BOOL ret = TRUE;
794 width = min( region->Right - region->Left + 1, size.X - coord.X );
795 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
797 if (width > 0 && height > 0)
799 for (y = 0; y < height; y++)
801 SERVER_START_REQ( read_console_output )
803 req->handle = console_handle_unmap(hConsoleOutput);
804 req->x = region->Left;
805 req->y = region->Top + y;
806 req->mode = CHAR_INFO_MODE_TEXTATTR;
807 req->wrap = FALSE;
808 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
809 width * sizeof(CHAR_INFO) );
810 if ((ret = !wine_server_call_err( req )))
812 width = min( width, reply->width - region->Left );
813 height = min( height, reply->height - region->Top );
816 SERVER_END_REQ;
817 if (!ret) break;
820 region->Bottom = region->Top + height - 1;
821 region->Right = region->Left + width - 1;
822 return ret;
826 /******************************************************************************
827 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
829 * PARAMS
830 * handle [I] Handle to console input buffer
831 * buffer [O] Address of buffer for read data
832 * count [I] Number of records to read
833 * pRead [O] Address of number of records read
835 * RETURNS
836 * Success: TRUE
837 * Failure: FALSE
839 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
841 DWORD read;
843 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
844 input_records_WtoA( buffer, read );
845 if (pRead) *pRead = read;
846 return TRUE;
850 /***********************************************************************
851 * PeekConsoleInputA (KERNEL32.@)
853 * Gets 'count' first events (or less) from input queue.
855 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
857 DWORD read;
859 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
860 input_records_WtoA( buffer, read );
861 if (pRead) *pRead = read;
862 return TRUE;
866 /***********************************************************************
867 * PeekConsoleInputW (KERNEL32.@)
869 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
871 BOOL ret;
872 SERVER_START_REQ( read_console_input )
874 req->handle = console_handle_unmap(handle);
875 req->flush = FALSE;
876 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
877 if ((ret = !wine_server_call_err( req )))
879 if (read) *read = count ? reply->read : 0;
882 SERVER_END_REQ;
883 return ret;
887 /***********************************************************************
888 * GetNumberOfConsoleInputEvents (KERNEL32.@)
890 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
892 BOOL ret;
893 SERVER_START_REQ( read_console_input )
895 req->handle = console_handle_unmap(handle);
896 req->flush = FALSE;
897 if ((ret = !wine_server_call_err( req )))
899 if (nrofevents) *nrofevents = reply->read;
902 SERVER_END_REQ;
903 return ret;
907 /******************************************************************************
908 * read_console_input
910 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
912 * Returns
913 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
915 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
916 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
918 enum read_console_input_return ret;
920 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
921 return rci_timeout;
922 SERVER_START_REQ( read_console_input )
924 req->handle = console_handle_unmap(handle);
925 req->flush = TRUE;
926 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
927 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
928 else ret = rci_gotone;
930 SERVER_END_REQ;
932 return ret;
936 /***********************************************************************
937 * FlushConsoleInputBuffer (KERNEL32.@)
939 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
941 enum read_console_input_return last;
942 INPUT_RECORD ir;
944 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
946 return last == rci_timeout;
950 /***********************************************************************
951 * SetConsoleTitleA (KERNEL32.@)
953 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
955 LPWSTR titleW;
956 BOOL ret;
958 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
959 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
960 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
961 ret = SetConsoleTitleW(titleW);
962 HeapFree(GetProcessHeap(), 0, titleW);
963 return ret;
967 /***********************************************************************
968 * GetConsoleTitleA (KERNEL32.@)
970 * See GetConsoleTitleW.
972 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
974 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
975 DWORD ret;
977 if (!ptr) return 0;
978 ret = GetConsoleTitleW( ptr, size );
979 if (ret)
981 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
982 ret = strlen(title);
984 HeapFree(GetProcessHeap(), 0, ptr);
985 return ret;
989 /******************************************************************************
990 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
992 * PARAMS
993 * title [O] Address of buffer for title
994 * size [I] Size of buffer
996 * RETURNS
997 * Success: Length of string copied
998 * Failure: 0
1000 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1002 DWORD ret = 0;
1004 SERVER_START_REQ( get_console_input_info )
1006 req->handle = 0;
1007 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1008 if (!wine_server_call_err( req ))
1010 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1011 title[ret] = 0;
1014 SERVER_END_REQ;
1015 return ret;
1019 /***********************************************************************
1020 * GetLargestConsoleWindowSize (KERNEL32.@)
1022 * NOTE
1023 * This should return a COORD, but calling convention for returning
1024 * structures is different between Windows and gcc on i386.
1026 * VERSION: [i386]
1028 #ifdef __i386__
1029 #undef GetLargestConsoleWindowSize
1030 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1032 union {
1033 COORD c;
1034 DWORD w;
1035 } x;
1036 x.c.X = 80;
1037 x.c.Y = 24;
1038 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1039 return x.w;
1041 #endif /* defined(__i386__) */
1044 /***********************************************************************
1045 * GetLargestConsoleWindowSize (KERNEL32.@)
1047 * NOTE
1048 * This should return a COORD, but calling convention for returning
1049 * structures is different between Windows and gcc on i386.
1051 * VERSION: [!i386]
1053 #ifndef __i386__
1054 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1056 COORD c;
1057 c.X = 80;
1058 c.Y = 24;
1059 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1060 return c;
1062 #endif /* defined(__i386__) */
1064 static WCHAR* S_EditString /* = NULL */;
1065 static unsigned S_EditStrPos /* = 0 */;
1067 /***********************************************************************
1068 * FreeConsole (KERNEL32.@)
1070 BOOL WINAPI FreeConsole(VOID)
1072 BOOL ret;
1074 SERVER_START_REQ(free_console)
1076 ret = !wine_server_call_err( req );
1078 SERVER_END_REQ;
1079 return ret;
1082 /******************************************************************
1083 * start_console_renderer
1085 * helper for AllocConsole
1086 * starts the renderer process
1088 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1089 HANDLE hEvent)
1091 char buffer[1024];
1092 int ret;
1093 PROCESS_INFORMATION pi;
1095 /* FIXME: use dynamic allocation for most of the buffers below */
1096 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1097 if ((ret > -1) && (ret < sizeof(buffer)) &&
1098 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1099 NULL, NULL, si, &pi))
1101 if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
1103 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1104 pi.dwProcessId, pi.dwThreadId);
1106 return TRUE;
1108 return FALSE;
1111 static BOOL start_console_renderer(STARTUPINFOA* si)
1113 HANDLE hEvent = 0;
1114 LPSTR p;
1115 OBJECT_ATTRIBUTES attr;
1116 BOOL ret = FALSE;
1118 attr.Length = sizeof(attr);
1119 attr.RootDirectory = 0;
1120 attr.Attributes = OBJ_INHERIT;
1121 attr.ObjectName = NULL;
1122 attr.SecurityDescriptor = NULL;
1123 attr.SecurityQualityOfService = NULL;
1125 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
1126 if (!hEvent) return FALSE;
1128 /* first try environment variable */
1129 if ((p = getenv("WINECONSOLE")) != NULL)
1131 ret = start_console_renderer_helper(p, si, hEvent);
1132 if (!ret)
1133 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1134 "trying default access\n", p);
1137 /* then try the regular PATH */
1138 if (!ret)
1139 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1141 CloseHandle(hEvent);
1142 return ret;
1145 /***********************************************************************
1146 * AllocConsole (KERNEL32.@)
1148 * creates an xterm with a pty to our program
1150 BOOL WINAPI AllocConsole(void)
1152 HANDLE handle_in = INVALID_HANDLE_VALUE;
1153 HANDLE handle_out = INVALID_HANDLE_VALUE;
1154 HANDLE handle_err = INVALID_HANDLE_VALUE;
1155 STARTUPINFOA siCurrent;
1156 STARTUPINFOA siConsole;
1157 char buffer[1024];
1159 TRACE("()\n");
1161 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1162 FALSE, OPEN_EXISTING );
1164 if (VerifyConsoleIoHandle(handle_in))
1166 /* we already have a console opened on this process, don't create a new one */
1167 CloseHandle(handle_in);
1168 return FALSE;
1170 /* happens when we're running on a Unix console */
1171 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1173 GetStartupInfoA(&siCurrent);
1175 memset(&siConsole, 0, sizeof(siConsole));
1176 siConsole.cb = sizeof(siConsole);
1177 /* setup a view arguments for wineconsole (it'll use them as default values) */
1178 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1180 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1181 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1182 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1184 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1186 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1187 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1189 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1191 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1192 siConsole.wShowWindow = siCurrent.wShowWindow;
1194 /* FIXME (should pass the unicode form) */
1195 if (siCurrent.lpTitle)
1196 siConsole.lpTitle = siCurrent.lpTitle;
1197 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1199 buffer[sizeof(buffer) - 1] = '\0';
1200 siConsole.lpTitle = buffer;
1203 if (!start_console_renderer(&siConsole))
1204 goto the_end;
1206 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1207 /* all std I/O handles are inheritable by default */
1208 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1209 TRUE, OPEN_EXISTING );
1210 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1212 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1213 TRUE, OPEN_EXISTING );
1214 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1216 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1217 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1218 goto the_end;
1219 } else {
1220 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1221 handle_in = siCurrent.hStdInput;
1222 handle_out = siCurrent.hStdOutput;
1223 handle_err = siCurrent.hStdError;
1226 /* NT resets the STD_*_HANDLEs on console alloc */
1227 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1228 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1229 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1231 SetLastError(ERROR_SUCCESS);
1233 return TRUE;
1235 the_end:
1236 ERR("Can't allocate console\n");
1237 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1238 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1239 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1240 FreeConsole();
1241 return FALSE;
1245 /***********************************************************************
1246 * ReadConsoleA (KERNEL32.@)
1248 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1249 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1251 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1252 DWORD ncr = 0;
1253 BOOL ret;
1255 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1256 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1258 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1259 HeapFree(GetProcessHeap(), 0, ptr);
1261 return ret;
1264 /***********************************************************************
1265 * ReadConsoleW (KERNEL32.@)
1267 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1268 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1270 DWORD charsread;
1271 LPWSTR xbuf = (LPWSTR)lpBuffer;
1272 DWORD mode;
1274 TRACE("(%p,%p,%d,%p,%p)\n",
1275 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1277 if (!GetConsoleMode(hConsoleInput, &mode))
1278 return FALSE;
1280 if (mode & ENABLE_LINE_INPUT)
1282 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1284 HeapFree(GetProcessHeap(), 0, S_EditString);
1285 if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1286 return FALSE;
1287 S_EditStrPos = 0;
1289 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1290 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1291 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1292 S_EditStrPos += charsread;
1294 else
1296 INPUT_RECORD ir;
1297 DWORD timeout = INFINITE;
1299 /* FIXME: should we read at least 1 char? The SDK does not say */
1300 /* wait for at least one available input record (it doesn't mean we'll have
1301 * chars stored in xbuf...)
1303 charsread = 0;
1306 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1307 timeout = 0;
1308 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1309 ir.Event.KeyEvent.uChar.UnicodeChar &&
1310 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
1312 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1314 } while (charsread < nNumberOfCharsToRead);
1315 /* nothing has been read */
1316 if (timeout == INFINITE) return FALSE;
1319 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1321 return TRUE;
1325 /***********************************************************************
1326 * ReadConsoleInputW (KERNEL32.@)
1328 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1329 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1331 DWORD idx = 0;
1332 DWORD timeout = INFINITE;
1334 if (!nLength)
1336 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1337 return TRUE;
1340 /* loop until we get at least one event */
1341 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1342 ++idx < nLength)
1343 timeout = 0;
1345 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1346 return idx != 0;
1350 /******************************************************************************
1351 * WriteConsoleOutputCharacterW [KERNEL32.@]
1353 * Copy character to consecutive cells in the console screen buffer.
1355 * PARAMS
1356 * hConsoleOutput [I] Handle to screen buffer
1357 * str [I] Pointer to buffer with chars to write
1358 * length [I] Number of cells to write to
1359 * coord [I] Coords of first cell
1360 * lpNumCharsWritten [O] Pointer to number of cells written
1362 * RETURNS
1363 * Success: TRUE
1364 * Failure: FALSE
1367 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1368 COORD coord, LPDWORD lpNumCharsWritten )
1370 BOOL ret;
1372 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1373 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1375 SERVER_START_REQ( write_console_output )
1377 req->handle = console_handle_unmap(hConsoleOutput);
1378 req->x = coord.X;
1379 req->y = coord.Y;
1380 req->mode = CHAR_INFO_MODE_TEXT;
1381 req->wrap = TRUE;
1382 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1383 if ((ret = !wine_server_call_err( req )))
1385 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1388 SERVER_END_REQ;
1389 return ret;
1393 /******************************************************************************
1394 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1396 * PARAMS
1397 * title [I] Address of new title
1399 * RETURNS
1400 * Success: TRUE
1401 * Failure: FALSE
1403 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1405 BOOL ret;
1407 TRACE("(%s)\n", debugstr_w(title));
1408 SERVER_START_REQ( set_console_input_info )
1410 req->handle = 0;
1411 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1412 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1413 ret = !wine_server_call_err( req );
1415 SERVER_END_REQ;
1416 return ret;
1420 /***********************************************************************
1421 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1423 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1425 FIXME("(%p): stub\n", nrofbuttons);
1426 *nrofbuttons = 2;
1427 return TRUE;
1430 /******************************************************************************
1431 * SetConsoleInputExeNameW [KERNEL32.@]
1433 * BUGS
1434 * Unimplemented
1436 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1438 FIXME("(%s): stub!\n", debugstr_w(name));
1440 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1441 return TRUE;
1444 /******************************************************************************
1445 * SetConsoleInputExeNameA [KERNEL32.@]
1447 * BUGS
1448 * Unimplemented
1450 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1452 int len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1453 LPWSTR xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1454 BOOL ret;
1456 if (!xptr) return FALSE;
1458 MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
1459 ret = SetConsoleInputExeNameW(xptr);
1460 HeapFree(GetProcessHeap(), 0, xptr);
1462 return ret;
1465 /******************************************************************
1466 * CONSOLE_DefaultHandler
1468 * Final control event handler
1470 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1472 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1473 ExitProcess(0);
1474 /* should never go here */
1475 return TRUE;
1478 /******************************************************************************
1479 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1481 * PARAMS
1482 * func [I] Address of handler function
1483 * add [I] Handler to add or remove
1485 * RETURNS
1486 * Success: TRUE
1487 * Failure: FALSE
1490 struct ConsoleHandler
1492 PHANDLER_ROUTINE handler;
1493 struct ConsoleHandler* next;
1496 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1497 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1499 static CRITICAL_SECTION CONSOLE_CritSect;
1500 static CRITICAL_SECTION_DEBUG critsect_debug =
1502 0, 0, &CONSOLE_CritSect,
1503 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
1504 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
1506 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
1508 /*****************************************************************************/
1510 /******************************************************************
1511 * SetConsoleCtrlHandler (KERNEL32.@)
1513 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1515 BOOL ret = TRUE;
1517 TRACE("(%p,%i)\n", func, add);
1519 if (!func)
1521 RtlEnterCriticalSection(&CONSOLE_CritSect);
1522 if (add)
1523 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1524 else
1525 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1526 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1528 else if (add)
1530 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1532 if (!ch) return FALSE;
1533 ch->handler = func;
1534 RtlEnterCriticalSection(&CONSOLE_CritSect);
1535 ch->next = CONSOLE_Handlers;
1536 CONSOLE_Handlers = ch;
1537 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1539 else
1541 struct ConsoleHandler** ch;
1542 RtlEnterCriticalSection(&CONSOLE_CritSect);
1543 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1545 if ((*ch)->handler == func) break;
1547 if (*ch)
1549 struct ConsoleHandler* rch = *ch;
1551 /* sanity check */
1552 if (rch == &CONSOLE_DefaultConsoleHandler)
1554 ERR("Who's trying to remove default handler???\n");
1555 SetLastError(ERROR_INVALID_PARAMETER);
1556 ret = FALSE;
1558 else
1560 *ch = rch->next;
1561 HeapFree(GetProcessHeap(), 0, rch);
1564 else
1566 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1567 SetLastError(ERROR_INVALID_PARAMETER);
1568 ret = FALSE;
1570 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1572 return ret;
1575 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
1577 TRACE("(%x)\n", GetExceptionCode());
1578 return EXCEPTION_EXECUTE_HANDLER;
1581 /******************************************************************
1582 * CONSOLE_SendEventThread
1584 * Internal helper to pass an event to the list on installed handlers
1586 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1588 DWORD_PTR event = (DWORD_PTR)pmt;
1589 struct ConsoleHandler* ch;
1591 if (event == CTRL_C_EVENT)
1593 BOOL caught_by_dbg = TRUE;
1594 /* First, try to pass the ctrl-C event to the debugger (if any)
1595 * If it continues, there's nothing more to do
1596 * Otherwise, we need to send the ctrl-C event to the handlers
1598 __TRY
1600 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1602 __EXCEPT(CONSOLE_CtrlEventHandler)
1604 caught_by_dbg = FALSE;
1606 __ENDTRY;
1607 if (caught_by_dbg) return 0;
1608 /* the debugger didn't continue... so, pass to ctrl handlers */
1610 RtlEnterCriticalSection(&CONSOLE_CritSect);
1611 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1613 if (ch->handler(event)) break;
1615 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1616 return 1;
1619 /******************************************************************
1620 * CONSOLE_HandleCtrlC
1622 * Check whether the shall manipulate CtrlC events
1624 int CONSOLE_HandleCtrlC(unsigned sig)
1626 /* FIXME: better test whether a console is attached to this process ??? */
1627 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1628 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1630 /* check if we have to ignore ctrl-C events */
1631 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1633 /* Create a separate thread to signal all the events.
1634 * This is needed because:
1635 * - this function can be called in an Unix signal handler (hence on an
1636 * different stack than the thread that's running). This breaks the
1637 * Win32 exception mechanisms (where the thread's stack is checked).
1638 * - since the current thread, while processing the signal, can hold the
1639 * console critical section, we need another execution environment where
1640 * we can wait on this critical section
1642 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1644 return 1;
1647 /******************************************************************************
1648 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1650 * PARAMS
1651 * dwCtrlEvent [I] Type of event
1652 * dwProcessGroupID [I] Process group ID to send event to
1654 * RETURNS
1655 * Success: True
1656 * Failure: False (and *should* [but doesn't] set LastError)
1658 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1659 DWORD dwProcessGroupID)
1661 BOOL ret;
1663 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
1665 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1667 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
1668 return FALSE;
1671 SERVER_START_REQ( send_console_signal )
1673 req->signal = dwCtrlEvent;
1674 req->group_id = dwProcessGroupID;
1675 ret = !wine_server_call_err( req );
1677 SERVER_END_REQ;
1679 /* FIXME: shall this function be synchronous, ie only return when all events
1680 * have been handled by all processes in the given group ?
1681 * As of today, we don't wait...
1683 return ret;
1687 /******************************************************************************
1688 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
1690 * PARAMS
1691 * dwDesiredAccess [I] Access flag
1692 * dwShareMode [I] Buffer share mode
1693 * sa [I] Security attributes
1694 * dwFlags [I] Type of buffer to create
1695 * lpScreenBufferData [I] Reserved
1697 * NOTES
1698 * Should call SetLastError
1700 * RETURNS
1701 * Success: Handle to new console screen buffer
1702 * Failure: INVALID_HANDLE_VALUE
1704 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1705 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1706 LPVOID lpScreenBufferData)
1708 HANDLE ret = INVALID_HANDLE_VALUE;
1710 TRACE("(%d,%d,%p,%d,%p)\n",
1711 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1713 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1715 SetLastError(ERROR_INVALID_PARAMETER);
1716 return INVALID_HANDLE_VALUE;
1719 SERVER_START_REQ(create_console_output)
1721 req->handle_in = 0;
1722 req->access = dwDesiredAccess;
1723 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
1724 req->share = dwShareMode;
1725 if (!wine_server_call_err( req )) ret = reply->handle_out;
1727 SERVER_END_REQ;
1729 return ret;
1733 /***********************************************************************
1734 * GetConsoleScreenBufferInfo (KERNEL32.@)
1736 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1738 BOOL ret;
1740 SERVER_START_REQ(get_console_output_info)
1742 req->handle = console_handle_unmap(hConsoleOutput);
1743 if ((ret = !wine_server_call_err( req )))
1745 csbi->dwSize.X = reply->width;
1746 csbi->dwSize.Y = reply->height;
1747 csbi->dwCursorPosition.X = reply->cursor_x;
1748 csbi->dwCursorPosition.Y = reply->cursor_y;
1749 csbi->wAttributes = reply->attr;
1750 csbi->srWindow.Left = reply->win_left;
1751 csbi->srWindow.Right = reply->win_right;
1752 csbi->srWindow.Top = reply->win_top;
1753 csbi->srWindow.Bottom = reply->win_bottom;
1754 csbi->dwMaximumWindowSize.X = reply->max_width;
1755 csbi->dwMaximumWindowSize.Y = reply->max_height;
1758 SERVER_END_REQ;
1760 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
1761 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1762 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1763 csbi->wAttributes,
1764 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1765 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1767 return ret;
1771 /******************************************************************************
1772 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
1774 * RETURNS
1775 * Success: TRUE
1776 * Failure: FALSE
1778 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1780 BOOL ret;
1782 TRACE("(%p)\n", hConsoleOutput);
1784 SERVER_START_REQ( set_console_input_info )
1786 req->handle = 0;
1787 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1788 req->active_sb = hConsoleOutput;
1789 ret = !wine_server_call_err( req );
1791 SERVER_END_REQ;
1792 return ret;
1796 /***********************************************************************
1797 * GetConsoleMode (KERNEL32.@)
1799 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1801 BOOL ret;
1803 SERVER_START_REQ(get_console_mode)
1805 req->handle = console_handle_unmap(hcon);
1806 ret = !wine_server_call_err( req );
1807 if (ret && mode) *mode = reply->mode;
1809 SERVER_END_REQ;
1810 return ret;
1814 /******************************************************************************
1815 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
1817 * PARAMS
1818 * hcon [I] Handle to console input or screen buffer
1819 * mode [I] Input or output mode to set
1821 * RETURNS
1822 * Success: TRUE
1823 * Failure: FALSE
1825 * mode:
1826 * ENABLE_PROCESSED_INPUT 0x01
1827 * ENABLE_LINE_INPUT 0x02
1828 * ENABLE_ECHO_INPUT 0x04
1829 * ENABLE_WINDOW_INPUT 0x08
1830 * ENABLE_MOUSE_INPUT 0x10
1832 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1834 BOOL ret;
1836 SERVER_START_REQ(set_console_mode)
1838 req->handle = console_handle_unmap(hcon);
1839 req->mode = mode;
1840 ret = !wine_server_call_err( req );
1842 SERVER_END_REQ;
1843 /* FIXME: when resetting a console input to editline mode, I think we should
1844 * empty the S_EditString buffer
1847 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
1849 return ret;
1853 /******************************************************************
1854 * CONSOLE_WriteChars
1856 * WriteConsoleOutput helper: hides server call semantics
1857 * writes a string at a given pos with standard attribute
1859 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1861 int written = -1;
1863 if (!nc) return 0;
1865 SERVER_START_REQ( write_console_output )
1867 req->handle = console_handle_unmap(hCon);
1868 req->x = pos->X;
1869 req->y = pos->Y;
1870 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1871 req->wrap = FALSE;
1872 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1873 if (!wine_server_call_err( req )) written = reply->written;
1875 SERVER_END_REQ;
1877 if (written > 0) pos->X += written;
1878 return written;
1881 /******************************************************************
1882 * next_line
1884 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1887 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1889 SMALL_RECT src;
1890 CHAR_INFO ci;
1891 COORD dst;
1893 csbi->dwCursorPosition.X = 0;
1894 csbi->dwCursorPosition.Y++;
1896 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1898 src.Top = 1;
1899 src.Bottom = csbi->dwSize.Y - 1;
1900 src.Left = 0;
1901 src.Right = csbi->dwSize.X - 1;
1903 dst.X = 0;
1904 dst.Y = 0;
1906 ci.Attributes = csbi->wAttributes;
1907 ci.Char.UnicodeChar = ' ';
1909 csbi->dwCursorPosition.Y--;
1910 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1911 return 0;
1912 return 1;
1915 /******************************************************************
1916 * write_block
1918 * WriteConsoleOutput helper: writes a block of non special characters
1919 * Block can spread on several lines, and wrapping, if needed, is
1920 * handled
1923 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1924 DWORD mode, LPCWSTR ptr, int len)
1926 int blk; /* number of chars to write on current line */
1927 int done; /* number of chars already written */
1929 if (len <= 0) return 1;
1931 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1933 for (done = 0; done < len; done += blk)
1935 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1937 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1938 return 0;
1939 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
1940 return 0;
1943 else
1945 int pos = csbi->dwCursorPosition.X;
1946 /* FIXME: we could reduce the number of loops
1947 * but, in most cases we wouldn't gain lots of time (it would only
1948 * happen if we're asked to overwrite more than twice the part of the line,
1949 * which is unlikely
1951 for (blk = done = 0; done < len; done += blk)
1953 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1955 csbi->dwCursorPosition.X = pos;
1956 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1957 return 0;
1961 return 1;
1964 /***********************************************************************
1965 * WriteConsoleW (KERNEL32.@)
1967 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1968 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1970 DWORD mode;
1971 DWORD nw = 0;
1972 const WCHAR* psz = lpBuffer;
1973 CONSOLE_SCREEN_BUFFER_INFO csbi;
1974 int k, first = 0;
1976 TRACE("%p %s %d %p %p\n",
1977 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
1978 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
1980 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1982 if (!GetConsoleMode(hConsoleOutput, &mode) ||
1983 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1984 return FALSE;
1986 if (mode & ENABLE_PROCESSED_OUTPUT)
1988 unsigned int i;
1990 for (i = 0; i < nNumberOfCharsToWrite; i++)
1992 switch (psz[i])
1994 case '\b': case '\t': case '\n': case '\a': case '\r':
1995 /* don't handle here the i-th char... done below */
1996 if ((k = i - first) > 0)
1998 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1999 goto the_end;
2000 nw += k;
2002 first = i + 1;
2003 nw++;
2005 switch (psz[i])
2007 case '\b':
2008 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2009 break;
2010 case '\t':
2012 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2014 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2015 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2016 goto the_end;
2018 break;
2019 case '\n':
2020 next_line(hConsoleOutput, &csbi);
2021 break;
2022 case '\a':
2023 Beep(400, 300);
2024 break;
2025 case '\r':
2026 csbi.dwCursorPosition.X = 0;
2027 break;
2028 default:
2029 break;
2034 /* write the remaining block (if any) if processed output is enabled, or the
2035 * entire buffer otherwise
2037 if ((k = nNumberOfCharsToWrite - first) > 0)
2039 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2040 goto the_end;
2041 nw += k;
2044 the_end:
2045 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2046 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2047 return nw != 0;
2051 /***********************************************************************
2052 * WriteConsoleA (KERNEL32.@)
2054 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2055 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2057 BOOL ret;
2058 LPWSTR xstring;
2059 DWORD n;
2061 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2063 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2064 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2065 if (!xstring) return 0;
2067 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2069 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2071 HeapFree(GetProcessHeap(), 0, xstring);
2073 return ret;
2076 /******************************************************************************
2077 * SetConsoleCursorPosition [KERNEL32.@]
2078 * Sets the cursor position in console
2080 * PARAMS
2081 * hConsoleOutput [I] Handle of console screen buffer
2082 * dwCursorPosition [I] New cursor position coordinates
2084 * RETURNS
2085 * Success: TRUE
2086 * Failure: FALSE
2088 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2090 BOOL ret;
2091 CONSOLE_SCREEN_BUFFER_INFO csbi;
2092 int do_move = 0;
2093 int w, h;
2095 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2097 SERVER_START_REQ(set_console_output_info)
2099 req->handle = console_handle_unmap(hcon);
2100 req->cursor_x = pos.X;
2101 req->cursor_y = pos.Y;
2102 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2103 ret = !wine_server_call_err( req );
2105 SERVER_END_REQ;
2107 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2108 return FALSE;
2110 /* if cursor is no longer visible, scroll the visible window... */
2111 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2112 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2113 if (pos.X < csbi.srWindow.Left)
2115 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2116 do_move++;
2118 else if (pos.X > csbi.srWindow.Right)
2120 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2121 do_move++;
2123 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2125 if (pos.Y < csbi.srWindow.Top)
2127 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2128 do_move++;
2130 else if (pos.Y > csbi.srWindow.Bottom)
2132 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2133 do_move++;
2135 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2137 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2139 return ret;
2142 /******************************************************************************
2143 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2145 * PARAMS
2146 * hcon [I] Handle to console screen buffer
2147 * cinfo [O] Address of cursor information
2149 * RETURNS
2150 * Success: TRUE
2151 * Failure: FALSE
2153 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2155 BOOL ret;
2157 SERVER_START_REQ(get_console_output_info)
2159 req->handle = console_handle_unmap(hCon);
2160 ret = !wine_server_call_err( req );
2161 if (ret && cinfo)
2163 cinfo->dwSize = reply->cursor_size;
2164 cinfo->bVisible = reply->cursor_visible;
2167 SERVER_END_REQ;
2169 TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2170 return ret;
2174 /******************************************************************************
2175 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2177 * PARAMS
2178 * hcon [I] Handle to console screen buffer
2179 * cinfo [I] Address of cursor information
2180 * RETURNS
2181 * Success: TRUE
2182 * Failure: FALSE
2184 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2186 BOOL ret;
2188 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2189 SERVER_START_REQ(set_console_output_info)
2191 req->handle = console_handle_unmap(hCon);
2192 req->cursor_size = cinfo->dwSize;
2193 req->cursor_visible = cinfo->bVisible;
2194 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2195 ret = !wine_server_call_err( req );
2197 SERVER_END_REQ;
2198 return ret;
2202 /******************************************************************************
2203 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2205 * PARAMS
2206 * hcon [I] Handle to console screen buffer
2207 * bAbsolute [I] Coordinate type flag
2208 * window [I] Address of new window rectangle
2209 * RETURNS
2210 * Success: TRUE
2211 * Failure: FALSE
2213 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2215 SMALL_RECT p = *window;
2216 BOOL ret;
2218 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2220 if (!bAbsolute)
2222 CONSOLE_SCREEN_BUFFER_INFO csbi;
2224 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2225 return FALSE;
2226 p.Left += csbi.srWindow.Left;
2227 p.Top += csbi.srWindow.Top;
2228 p.Right += csbi.srWindow.Right;
2229 p.Bottom += csbi.srWindow.Bottom;
2231 SERVER_START_REQ(set_console_output_info)
2233 req->handle = console_handle_unmap(hCon);
2234 req->win_left = p.Left;
2235 req->win_top = p.Top;
2236 req->win_right = p.Right;
2237 req->win_bottom = p.Bottom;
2238 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2239 ret = !wine_server_call_err( req );
2241 SERVER_END_REQ;
2243 return ret;
2247 /******************************************************************************
2248 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2250 * Sets the foreground and background color attributes of characters
2251 * written to the screen buffer.
2253 * RETURNS
2254 * Success: TRUE
2255 * Failure: FALSE
2257 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2259 BOOL ret;
2261 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2262 SERVER_START_REQ(set_console_output_info)
2264 req->handle = console_handle_unmap(hConsoleOutput);
2265 req->attr = wAttr;
2266 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2267 ret = !wine_server_call_err( req );
2269 SERVER_END_REQ;
2270 return ret;
2274 /******************************************************************************
2275 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2277 * PARAMS
2278 * hConsoleOutput [I] Handle to console screen buffer
2279 * dwSize [I] New size in character rows and cols
2281 * RETURNS
2282 * Success: TRUE
2283 * Failure: FALSE
2285 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2287 BOOL ret;
2289 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2290 SERVER_START_REQ(set_console_output_info)
2292 req->handle = console_handle_unmap(hConsoleOutput);
2293 req->width = dwSize.X;
2294 req->height = dwSize.Y;
2295 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2296 ret = !wine_server_call_err( req );
2298 SERVER_END_REQ;
2299 return ret;
2303 /******************************************************************************
2304 * ScrollConsoleScreenBufferA [KERNEL32.@]
2307 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2308 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2309 LPCHAR_INFO lpFill)
2311 CHAR_INFO ciw;
2313 ciw.Attributes = lpFill->Attributes;
2314 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2316 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2317 dwDestOrigin, &ciw);
2320 /******************************************************************
2321 * CONSOLE_FillLineUniform
2323 * Helper function for ScrollConsoleScreenBufferW
2324 * Fills a part of a line with a constant character info
2326 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2328 SERVER_START_REQ( fill_console_output )
2330 req->handle = console_handle_unmap(hConsoleOutput);
2331 req->mode = CHAR_INFO_MODE_TEXTATTR;
2332 req->x = i;
2333 req->y = j;
2334 req->count = len;
2335 req->wrap = FALSE;
2336 req->data.ch = lpFill->Char.UnicodeChar;
2337 req->data.attr = lpFill->Attributes;
2338 wine_server_call_err( req );
2340 SERVER_END_REQ;
2343 /******************************************************************************
2344 * ScrollConsoleScreenBufferW [KERNEL32.@]
2348 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2349 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2350 LPCHAR_INFO lpFill)
2352 SMALL_RECT dst;
2353 DWORD ret;
2354 int i, j;
2355 int start = -1;
2356 SMALL_RECT clip;
2357 CONSOLE_SCREEN_BUFFER_INFO csbi;
2358 BOOL inside;
2359 COORD src;
2361 if (lpClipRect)
2362 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2363 lpScrollRect->Left, lpScrollRect->Top,
2364 lpScrollRect->Right, lpScrollRect->Bottom,
2365 lpClipRect->Left, lpClipRect->Top,
2366 lpClipRect->Right, lpClipRect->Bottom,
2367 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2368 else
2369 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2370 lpScrollRect->Left, lpScrollRect->Top,
2371 lpScrollRect->Right, lpScrollRect->Bottom,
2372 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2374 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2375 return FALSE;
2377 src.X = lpScrollRect->Left;
2378 src.Y = lpScrollRect->Top;
2380 /* step 1: get dst rect */
2381 dst.Left = dwDestOrigin.X;
2382 dst.Top = dwDestOrigin.Y;
2383 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2384 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2386 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2387 if (lpClipRect)
2389 clip.Left = max(0, lpClipRect->Left);
2390 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2391 clip.Top = max(0, lpClipRect->Top);
2392 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2394 else
2396 clip.Left = 0;
2397 clip.Right = csbi.dwSize.X - 1;
2398 clip.Top = 0;
2399 clip.Bottom = csbi.dwSize.Y - 1;
2401 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2403 /* step 2b: clip dst rect */
2404 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2405 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2406 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2407 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2409 /* step 3: transfer the bits */
2410 SERVER_START_REQ(move_console_output)
2412 req->handle = console_handle_unmap(hConsoleOutput);
2413 req->x_src = src.X;
2414 req->y_src = src.Y;
2415 req->x_dst = dst.Left;
2416 req->y_dst = dst.Top;
2417 req->w = dst.Right - dst.Left + 1;
2418 req->h = dst.Bottom - dst.Top + 1;
2419 ret = !wine_server_call_err( req );
2421 SERVER_END_REQ;
2423 if (!ret) return FALSE;
2425 /* step 4: clean out the exposed part */
2427 /* have to write cell [i,j] if it is not in dst rect (because it has already
2428 * been written to by the scroll) and is in clip (we shall not write
2429 * outside of clip)
2431 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2433 inside = dst.Top <= j && j <= dst.Bottom;
2434 start = -1;
2435 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2437 if (inside && dst.Left <= i && i <= dst.Right)
2439 if (start != -1)
2441 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2442 start = -1;
2445 else
2447 if (start == -1) start = i;
2450 if (start != -1)
2451 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2454 return TRUE;
2457 /******************************************************************
2458 * AttachConsole (KERNEL32.@)
2460 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2462 FIXME("stub %x\n",dwProcessId);
2463 return TRUE;
2467 /* ====================================================================
2469 * Console manipulation functions
2471 * ====================================================================*/
2473 /* some missing functions...
2474 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2475 * should get the right API and implement them
2476 * GetConsoleCommandHistory[AW] (dword dword dword)
2477 * GetConsoleCommandHistoryLength[AW]
2478 * SetConsoleCommandHistoryMode
2479 * SetConsoleNumberOfCommands[AW]
2481 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2483 int len = 0;
2485 SERVER_START_REQ( get_console_input_history )
2487 req->handle = 0;
2488 req->index = idx;
2489 if (buf && buf_len > 1)
2491 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2493 if (!wine_server_call_err( req ))
2495 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2496 len = reply->total / sizeof(WCHAR) + 1;
2499 SERVER_END_REQ;
2500 return len;
2503 /******************************************************************
2504 * CONSOLE_AppendHistory
2508 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2510 size_t len = strlenW(ptr);
2511 BOOL ret;
2513 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2514 if (!len) return FALSE;
2516 SERVER_START_REQ( append_console_input_history )
2518 req->handle = 0;
2519 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2520 ret = !wine_server_call_err( req );
2522 SERVER_END_REQ;
2523 return ret;
2526 /******************************************************************
2527 * CONSOLE_GetNumHistoryEntries
2531 unsigned CONSOLE_GetNumHistoryEntries(void)
2533 unsigned ret = -1;
2534 SERVER_START_REQ(get_console_input_info)
2536 req->handle = 0;
2537 if (!wine_server_call_err( req )) ret = reply->history_index;
2539 SERVER_END_REQ;
2540 return ret;
2543 /******************************************************************
2544 * CONSOLE_GetEditionMode
2548 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2550 unsigned ret = FALSE;
2551 SERVER_START_REQ(get_console_input_info)
2553 req->handle = console_handle_unmap(hConIn);
2554 if ((ret = !wine_server_call_err( req )))
2555 *mode = reply->edition_mode;
2557 SERVER_END_REQ;
2558 return ret;