- ctrl-c enabling flag is now inherited
[wine.git] / dlls / kernel / console.c
blob96b9ceb4a7bd52cd309dc9cc59447049fc212688
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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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"
55 #include "thread.h"
57 WINE_DEFAULT_DEBUG_CHANNEL(console);
59 static UINT console_input_codepage;
60 static UINT console_output_codepage;
63 /* map input records to ASCII */
64 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
66 int i;
67 char ch;
69 for (i = 0; i < count; i++)
71 if (buffer[i].EventType != KEY_EVENT) continue;
72 WideCharToMultiByte( GetConsoleCP(), 0,
73 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
74 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
78 /* map input records to Unicode */
79 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
81 int i;
82 WCHAR ch;
84 for (i = 0; i < count; i++)
86 if (buffer[i].EventType != KEY_EVENT) continue;
87 MultiByteToWideChar( GetConsoleCP(), 0,
88 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
89 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
93 /* map char infos to ASCII */
94 static void char_info_WtoA( CHAR_INFO *buffer, int count )
96 char ch;
98 while (count-- > 0)
100 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
101 &ch, 1, NULL, NULL );
102 buffer->Char.AsciiChar = ch;
103 buffer++;
107 /* map char infos to Unicode */
108 static void char_info_AtoW( CHAR_INFO *buffer, int count )
110 WCHAR ch;
112 while (count-- > 0)
114 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
115 buffer->Char.UnicodeChar = ch;
116 buffer++;
121 /******************************************************************************
122 * GetConsoleWindow [KERNEL32.@]
124 HWND WINAPI GetConsoleWindow(VOID)
126 FIXME("stub\n");
127 return NULL;
131 /******************************************************************************
132 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
134 * RETURNS
135 * Code page code
137 UINT WINAPI GetConsoleCP(VOID)
139 if (!console_input_codepage)
141 console_input_codepage = GetOEMCP();
142 TRACE("%u\n", console_input_codepage);
144 return console_input_codepage;
148 /******************************************************************************
149 * SetConsoleCP [KERNEL32.@]
151 BOOL WINAPI SetConsoleCP(UINT cp)
153 if (!IsValidCodePage( cp )) return FALSE;
154 console_input_codepage = cp;
155 return TRUE;
159 /***********************************************************************
160 * GetConsoleOutputCP (KERNEL32.@)
162 UINT WINAPI GetConsoleOutputCP(VOID)
164 if (!console_output_codepage)
166 console_output_codepage = GetOEMCP();
167 TRACE("%u\n", console_output_codepage);
169 return console_output_codepage;
173 /******************************************************************************
174 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
176 * PARAMS
177 * cp [I] code page to set
179 * RETURNS
180 * Success: TRUE
181 * Failure: FALSE
183 BOOL WINAPI SetConsoleOutputCP(UINT cp)
185 if (!IsValidCodePage( cp )) return FALSE;
186 console_output_codepage = cp;
187 return TRUE;
191 /***********************************************************************
192 * Beep (KERNEL32.@)
194 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
196 static const char beep = '\a';
197 /* dwFreq and dwDur are ignored by Win95 */
198 if (isatty(2)) write( 2, &beep, 1 );
199 return TRUE;
203 /******************************************************************
204 * OpenConsoleW (KERNEL32.@)
206 * Undocumented
207 * Open a handle to the current process console.
208 * Returns INVALID_HANDLE_VALUE on failure.
210 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
212 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
213 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
214 BOOL output;
215 HANDLE ret;
217 if (strcmpiW(coninW, name) == 0)
218 output = FALSE;
219 else if (strcmpiW(conoutW, name) == 0)
220 output = TRUE;
221 else
223 SetLastError(ERROR_INVALID_NAME);
224 return INVALID_HANDLE_VALUE;
226 if (creation != OPEN_EXISTING)
228 SetLastError(ERROR_INVALID_PARAMETER);
229 return INVALID_HANDLE_VALUE;
232 SERVER_START_REQ( open_console )
234 req->from = output;
235 req->access = access;
236 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
237 req->inherit = inherit;
238 SetLastError(0);
239 wine_server_call_err( req );
240 ret = reply->handle;
242 SERVER_END_REQ;
243 return ret ? console_handle_map(ret) : INVALID_HANDLE_VALUE;
246 /******************************************************************
247 * VerifyConsoleIoHandle (KERNEL32.@)
249 * Undocumented
251 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
253 BOOL ret;
255 if (!is_console_handle(handle)) return FALSE;
256 SERVER_START_REQ(get_console_mode)
258 req->handle = console_handle_unmap(handle);
259 ret = !wine_server_call_err( req );
261 SERVER_END_REQ;
262 return ret;
265 /******************************************************************
266 * DuplicateConsoleHandle (KERNEL32.@)
268 * Undocumented
270 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
271 DWORD options)
273 HANDLE ret;
275 if (!is_console_handle(handle) ||
276 !DuplicateHandle(GetCurrentProcess(), console_handle_unmap(handle),
277 GetCurrentProcess(), &ret, access, inherit, options))
278 return INVALID_HANDLE_VALUE;
279 return console_handle_map(ret);
282 /******************************************************************
283 * CloseConsoleHandle (KERNEL32.@)
285 * Undocumented
287 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
289 if (!is_console_handle(handle))
291 SetLastError(ERROR_INVALID_PARAMETER);
292 return FALSE;
294 return CloseHandle(console_handle_unmap(handle));
297 /******************************************************************
298 * GetConsoleInputWaitHandle (KERNEL32.@)
300 * Undocumented
302 HANDLE WINAPI GetConsoleInputWaitHandle(void)
304 static HANDLE console_wait_event;
306 /* FIXME: this is not thread safe */
307 if (!console_wait_event)
309 SERVER_START_REQ(get_console_wait_event)
311 if (!wine_server_call_err( req )) console_wait_event = reply->handle;
313 SERVER_END_REQ;
315 return console_wait_event;
319 /******************************************************************************
320 * WriteConsoleInputA [KERNEL32.@]
322 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
323 DWORD count, LPDWORD written )
325 INPUT_RECORD *recW;
326 BOOL ret;
328 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
329 memcpy( recW, buffer, count*sizeof(*recW) );
330 input_records_AtoW( recW, count );
331 ret = WriteConsoleInputW( handle, recW, count, written );
332 HeapFree( GetProcessHeap(), 0, recW );
333 return ret;
337 /******************************************************************************
338 * WriteConsoleInputW [KERNEL32.@]
340 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
341 DWORD count, LPDWORD written )
343 BOOL ret;
345 TRACE("(%p,%p,%ld,%p)\n", handle, buffer, count, written);
347 if (written) *written = 0;
348 SERVER_START_REQ( write_console_input )
350 req->handle = console_handle_unmap(handle);
351 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
352 if ((ret = !wine_server_call_err( req )) && written)
353 *written = reply->written;
355 SERVER_END_REQ;
357 return ret;
361 /***********************************************************************
362 * WriteConsoleOutputA (KERNEL32.@)
364 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
365 COORD size, COORD coord, LPSMALL_RECT region )
367 int y;
368 BOOL ret;
369 COORD new_size, new_coord;
370 CHAR_INFO *ciw;
372 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
373 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
375 if (new_size.X <= 0 || new_size.Y <= 0)
377 region->Bottom = region->Top + new_size.Y - 1;
378 region->Right = region->Left + new_size.X - 1;
379 return TRUE;
382 /* only copy the useful rectangle */
383 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
384 return FALSE;
385 for (y = 0; y < new_size.Y; y++)
387 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
388 new_size.X * sizeof(CHAR_INFO) );
389 char_info_AtoW( ciw, new_size.X );
391 new_coord.X = new_coord.Y = 0;
392 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
393 if (ciw) HeapFree( GetProcessHeap(), 0, ciw );
394 return ret;
398 /***********************************************************************
399 * WriteConsoleOutputW (KERNEL32.@)
401 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
402 COORD size, COORD coord, LPSMALL_RECT region )
404 int width, height, y;
405 BOOL ret = TRUE;
407 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
408 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
409 region->Left, region->Top, region->Right, region->Bottom);
411 width = min( region->Right - region->Left + 1, size.X - coord.X );
412 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
414 if (width > 0 && height > 0)
416 for (y = 0; y < height; y++)
418 SERVER_START_REQ( write_console_output )
420 req->handle = console_handle_unmap(hConsoleOutput);
421 req->x = region->Left;
422 req->y = region->Top + y;
423 req->mode = CHAR_INFO_MODE_TEXTATTR;
424 req->wrap = FALSE;
425 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
426 width * sizeof(CHAR_INFO));
427 if ((ret = !wine_server_call_err( req )))
429 width = min( width, reply->width - region->Left );
430 height = min( height, reply->height - region->Top );
433 SERVER_END_REQ;
434 if (!ret) break;
437 region->Bottom = region->Top + height - 1;
438 region->Right = region->Left + width - 1;
439 return ret;
443 /******************************************************************************
444 * WriteConsoleOutputCharacterA [KERNEL32.@] Copies character to consecutive
445 * cells in the console screen buffer
447 * PARAMS
448 * hConsoleOutput [I] Handle to screen buffer
449 * str [I] Pointer to buffer with chars to write
450 * length [I] Number of cells to write to
451 * coord [I] Coords of first cell
452 * lpNumCharsWritten [O] Pointer to number of cells written
454 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
455 COORD coord, LPDWORD lpNumCharsWritten )
457 BOOL ret;
458 LPWSTR strW;
459 DWORD lenW;
461 TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
462 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
464 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
466 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
468 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
469 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
471 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
472 HeapFree( GetProcessHeap(), 0, strW );
473 return ret;
477 /******************************************************************************
478 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
479 * the console screen buffer
481 * PARAMS
482 * hConsoleOutput [I] Handle to screen buffer
483 * attr [I] Pointer to buffer with write attributes
484 * length [I] Number of cells to write to
485 * coord [I] Coords of first cell
486 * lpNumAttrsWritten [O] Pointer to number of cells written
488 * RETURNS
489 * Success: TRUE
490 * Failure: FALSE
493 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
494 COORD coord, LPDWORD lpNumAttrsWritten )
496 BOOL ret;
498 TRACE("(%p,%p,%ld,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
500 SERVER_START_REQ( write_console_output )
502 req->handle = console_handle_unmap(hConsoleOutput);
503 req->x = coord.X;
504 req->y = coord.Y;
505 req->mode = CHAR_INFO_MODE_ATTR;
506 req->wrap = TRUE;
507 wine_server_add_data( req, attr, length * sizeof(WORD) );
508 if ((ret = !wine_server_call_err( req )))
510 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
513 SERVER_END_REQ;
514 return ret;
518 /******************************************************************************
519 * FillConsoleOutputCharacterA [KERNEL32.@]
521 * PARAMS
522 * hConsoleOutput [I] Handle to screen buffer
523 * ch [I] Character to write
524 * length [I] Number of cells to write to
525 * coord [I] Coords of first cell
526 * lpNumCharsWritten [O] Pointer to number of cells written
528 * RETURNS
529 * Success: TRUE
530 * Failure: FALSE
532 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
533 COORD coord, LPDWORD lpNumCharsWritten )
535 WCHAR wch;
537 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
538 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
542 /******************************************************************************
543 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
545 * PARAMS
546 * hConsoleOutput [I] Handle to screen buffer
547 * ch [I] Character to write
548 * length [I] Number of cells to write to
549 * coord [I] Coords of first cell
550 * lpNumCharsWritten [O] Pointer to number of cells written
552 * RETURNS
553 * Success: TRUE
554 * Failure: FALSE
556 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
557 COORD coord, LPDWORD lpNumCharsWritten)
559 BOOL ret;
561 TRACE("(%p,%s,%ld,(%dx%d),%p)\n",
562 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
564 SERVER_START_REQ( fill_console_output )
566 req->handle = console_handle_unmap(hConsoleOutput);
567 req->x = coord.X;
568 req->y = coord.Y;
569 req->mode = CHAR_INFO_MODE_TEXT;
570 req->wrap = TRUE;
571 req->data.ch = ch;
572 req->count = length;
573 if ((ret = !wine_server_call_err( req )))
575 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
578 SERVER_END_REQ;
579 return ret;
583 /******************************************************************************
584 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
586 * PARAMS
587 * hConsoleOutput [I] Handle to screen buffer
588 * attr [I] Color attribute to write
589 * length [I] Number of cells to write to
590 * coord [I] Coords of first cell
591 * lpNumAttrsWritten [O] Pointer to number of cells written
593 * RETURNS
594 * Success: TRUE
595 * Failure: FALSE
597 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
598 COORD coord, LPDWORD lpNumAttrsWritten )
600 BOOL ret;
602 TRACE("(%p,%d,%ld,(%dx%d),%p)\n",
603 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
605 SERVER_START_REQ( fill_console_output )
607 req->handle = console_handle_unmap(hConsoleOutput);
608 req->x = coord.X;
609 req->y = coord.Y;
610 req->mode = CHAR_INFO_MODE_ATTR;
611 req->wrap = TRUE;
612 req->data.attr = attr;
613 req->count = length;
614 if ((ret = !wine_server_call_err( req )))
616 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
619 SERVER_END_REQ;
620 return ret;
624 /******************************************************************************
625 * ReadConsoleOutputCharacterA [KERNEL32.@]
628 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
629 COORD coord, LPDWORD read_count)
631 DWORD read;
632 BOOL ret;
633 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
635 if (read_count) *read_count = 0;
636 if (!wptr) return FALSE;
638 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
640 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
641 if (read_count) *read_count = read;
643 HeapFree( GetProcessHeap(), 0, wptr );
644 return ret;
648 /******************************************************************************
649 * ReadConsoleOutputCharacterW [KERNEL32.@]
652 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
653 COORD coord, LPDWORD read_count )
655 BOOL ret;
657 TRACE( "(%p,%p,%ld,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
659 SERVER_START_REQ( read_console_output )
661 req->handle = console_handle_unmap(hConsoleOutput);
662 req->x = coord.X;
663 req->y = coord.Y;
664 req->mode = CHAR_INFO_MODE_TEXT;
665 req->wrap = TRUE;
666 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
667 if ((ret = !wine_server_call_err( req )))
669 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
672 SERVER_END_REQ;
673 return ret;
677 /******************************************************************************
678 * ReadConsoleOutputAttribute [KERNEL32.@]
680 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
681 COORD coord, LPDWORD read_count)
683 BOOL ret;
685 TRACE("(%p,%p,%ld,%dx%d,%p)\n",
686 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
688 SERVER_START_REQ( read_console_output )
690 req->handle = console_handle_unmap(hConsoleOutput);
691 req->x = coord.X;
692 req->y = coord.Y;
693 req->mode = CHAR_INFO_MODE_ATTR;
694 req->wrap = TRUE;
695 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
696 if ((ret = !wine_server_call_err( req )))
698 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
701 SERVER_END_REQ;
702 return ret;
706 /******************************************************************************
707 * ReadConsoleOutputA [KERNEL32.@]
710 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
711 COORD coord, LPSMALL_RECT region )
713 BOOL ret;
714 int y;
716 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
717 if (ret && region->Right >= region->Left)
719 for (y = 0; y <= region->Bottom - region->Top; y++)
721 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
722 region->Right - region->Left + 1 );
725 return ret;
729 /******************************************************************************
730 * ReadConsoleOutputW [KERNEL32.@]
732 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
733 * think we need to be *that* compatible. -- AJ
735 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
736 COORD coord, LPSMALL_RECT region )
738 int width, height, y;
739 BOOL ret = TRUE;
741 width = min( region->Right - region->Left + 1, size.X - coord.X );
742 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
744 if (width > 0 && height > 0)
746 for (y = 0; y < height; y++)
748 SERVER_START_REQ( read_console_output )
750 req->handle = console_handle_unmap(hConsoleOutput);
751 req->x = region->Left;
752 req->y = region->Top + y;
753 req->mode = CHAR_INFO_MODE_TEXTATTR;
754 req->wrap = FALSE;
755 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
756 width * sizeof(CHAR_INFO) );
757 if ((ret = !wine_server_call_err( req )))
759 width = min( width, reply->width - region->Left );
760 height = min( height, reply->height - region->Top );
763 SERVER_END_REQ;
764 if (!ret) break;
767 region->Bottom = region->Top + height - 1;
768 region->Right = region->Left + width - 1;
769 return ret;
773 /******************************************************************************
774 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
776 * PARAMS
777 * handle [I] Handle to console input buffer
778 * buffer [O] Address of buffer for read data
779 * count [I] Number of records to read
780 * pRead [O] Address of number of records read
782 * RETURNS
783 * Success: TRUE
784 * Failure: FALSE
786 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
788 DWORD read;
790 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
791 input_records_WtoA( buffer, read );
792 if (pRead) *pRead = read;
793 return TRUE;
797 /***********************************************************************
798 * PeekConsoleInputA (KERNEL32.@)
800 * Gets 'count' first events (or less) from input queue.
802 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
804 DWORD read;
806 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
807 input_records_WtoA( buffer, read );
808 if (pRead) *pRead = read;
809 return TRUE;
813 /***********************************************************************
814 * PeekConsoleInputW (KERNEL32.@)
816 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
818 BOOL ret;
819 SERVER_START_REQ( read_console_input )
821 req->handle = console_handle_unmap(handle);
822 req->flush = FALSE;
823 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
824 if ((ret = !wine_server_call_err( req )))
826 if (read) *read = count ? reply->read : 0;
829 SERVER_END_REQ;
830 return ret;
834 /***********************************************************************
835 * GetNumberOfConsoleInputEvents (KERNEL32.@)
837 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
839 BOOL ret;
840 SERVER_START_REQ( read_console_input )
842 req->handle = console_handle_unmap(handle);
843 req->flush = FALSE;
844 if ((ret = !wine_server_call_err( req )))
846 if (nrofevents) *nrofevents = reply->read;
849 SERVER_END_REQ;
850 return ret;
854 /******************************************************************************
855 * read_console_input
857 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
859 * Returns
860 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
862 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
863 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
865 enum read_console_input_return ret;
867 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
868 return rci_timeout;
869 SERVER_START_REQ( read_console_input )
871 req->handle = console_handle_unmap(handle);
872 req->flush = TRUE;
873 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
874 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
875 else ret = rci_gotone;
877 SERVER_END_REQ;
879 return ret;
883 /***********************************************************************
884 * FlushConsoleInputBuffer (KERNEL32.@)
886 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
888 enum read_console_input_return last;
889 INPUT_RECORD ir;
891 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
893 return last == rci_timeout;
897 /***********************************************************************
898 * SetConsoleTitleA (KERNEL32.@)
900 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
902 LPWSTR titleW;
903 BOOL ret;
905 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
906 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
907 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
908 ret = SetConsoleTitleW(titleW);
909 HeapFree(GetProcessHeap(), 0, titleW);
910 return ret;
914 /***********************************************************************
915 * GetConsoleTitleA (KERNEL32.@)
917 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
919 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
920 DWORD ret;
922 if (!ptr) return 0;
923 ret = GetConsoleTitleW( ptr, size );
924 if (ret)
926 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
927 ret = strlen(title);
929 HeapFree(GetProcessHeap(), 0, ptr);
930 return ret;
934 /******************************************************************************
935 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
937 * PARAMS
938 * title [O] Address of buffer for title
939 * size [I] Size of buffer
941 * RETURNS
942 * Success: Length of string copied
943 * Failure: 0
945 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
947 DWORD ret = 0;
949 SERVER_START_REQ( get_console_input_info )
951 req->handle = 0;
952 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
953 if (!wine_server_call_err( req ))
955 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
956 title[ret] = 0;
959 SERVER_END_REQ;
960 return ret;
964 /***********************************************************************
965 * GetLargestConsoleWindowSize (KERNEL32.@)
967 * NOTE
968 * This should return a COORD, but calling convention for returning
969 * structures is different between Windows and gcc on i386.
971 * VERSION: [i386]
973 #ifdef __i386__
974 #undef GetLargestConsoleWindowSize
975 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
977 union {
978 COORD c;
979 DWORD w;
980 } x;
981 x.c.X = 80;
982 x.c.Y = 24;
983 TRACE("(%p), returning %dx%d (%lx)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
984 return x.w;
986 #endif /* defined(__i386__) */
989 /***********************************************************************
990 * GetLargestConsoleWindowSize (KERNEL32.@)
992 * NOTE
993 * This should return a COORD, but calling convention for returning
994 * structures is different between Windows and gcc on i386.
996 * VERSION: [!i386]
998 #ifndef __i386__
999 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1001 COORD c;
1002 c.X = 80;
1003 c.Y = 24;
1004 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1005 return c;
1007 #endif /* defined(__i386__) */
1009 static WCHAR* S_EditString /* = NULL */;
1010 static unsigned S_EditStrPos /* = 0 */;
1012 /***********************************************************************
1013 * FreeConsole (KERNEL32.@)
1015 BOOL WINAPI FreeConsole(VOID)
1017 BOOL ret;
1019 SERVER_START_REQ(free_console)
1021 ret = !wine_server_call_err( req );
1023 SERVER_END_REQ;
1024 return ret;
1027 /******************************************************************
1028 * start_console_renderer
1030 * helper for AllocConsole
1031 * starts the renderer process
1033 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1034 HANDLE hEvent)
1036 char buffer[1024];
1037 int ret;
1038 PROCESS_INFORMATION pi;
1040 /* FIXME: use dynamic allocation for most of the buffers below */
1041 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%d", appname, (INT)hEvent);
1042 if ((ret > -1) && (ret < sizeof(buffer)) &&
1043 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1044 NULL, NULL, si, &pi))
1046 if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) return FALSE;
1048 TRACE("Started wineconsole pid=%08lx tid=%08lx\n",
1049 pi.dwProcessId, pi.dwThreadId);
1051 return TRUE;
1053 return FALSE;
1056 static BOOL start_console_renderer(STARTUPINFOA* si)
1058 HANDLE hEvent = 0;
1059 LPSTR p;
1060 OBJECT_ATTRIBUTES attr;
1061 BOOL ret = FALSE;
1063 attr.Length = sizeof(attr);
1064 attr.RootDirectory = 0;
1065 attr.Attributes = OBJ_INHERIT;
1066 attr.ObjectName = NULL;
1067 attr.SecurityDescriptor = NULL;
1068 attr.SecurityQualityOfService = NULL;
1070 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
1071 if (!hEvent) return FALSE;
1073 /* first try environment variable */
1074 if ((p = getenv("WINECONSOLE")) != NULL)
1076 ret = start_console_renderer_helper(p, si, hEvent);
1077 if (!ret)
1078 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1079 "trying default access\n", p);
1082 /* then try the regular PATH */
1083 if (!ret)
1084 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1086 CloseHandle(hEvent);
1087 return ret;
1090 /***********************************************************************
1091 * AllocConsole (KERNEL32.@)
1093 * creates an xterm with a pty to our program
1095 BOOL WINAPI AllocConsole(void)
1097 HANDLE handle_in = INVALID_HANDLE_VALUE;
1098 HANDLE handle_out = INVALID_HANDLE_VALUE;
1099 HANDLE handle_err = INVALID_HANDLE_VALUE;
1100 STARTUPINFOA siCurrent;
1101 STARTUPINFOA siConsole;
1102 char buffer[1024];
1103 SECURITY_ATTRIBUTES sa;
1105 TRACE("()\n");
1107 handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1108 0, NULL, OPEN_EXISTING, 0, 0 );
1110 if (handle_in != INVALID_HANDLE_VALUE)
1112 /* we already have a console opened on this process, don't create a new one */
1113 CloseHandle(handle_in);
1114 return FALSE;
1117 GetStartupInfoA(&siCurrent);
1119 memset(&siConsole, 0, sizeof(siConsole));
1120 siConsole.cb = sizeof(siConsole);
1121 /* setup a view arguments for wineconsole (it'll use them as default values) */
1122 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1124 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1125 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1126 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1128 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1130 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1131 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1133 /* FIXME (should pass the unicode form) */
1134 if (siCurrent.lpTitle)
1135 siConsole.lpTitle = siCurrent.lpTitle;
1136 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1138 buffer[sizeof(buffer) - 1] = '\0';
1139 siConsole.lpTitle = buffer;
1142 if (!start_console_renderer(&siConsole))
1143 goto the_end;
1145 /* all std I/O handles are inheritable by default */
1146 sa.nLength = sizeof(sa);
1147 sa.lpSecurityDescriptor = NULL;
1148 sa.bInheritHandle = TRUE;
1150 handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1151 0, &sa, OPEN_EXISTING, 0, 0 );
1152 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1154 handle_out = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE,
1155 0, &sa, OPEN_EXISTING, 0, 0 );
1156 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1158 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(), &handle_err,
1159 0, TRUE, DUPLICATE_SAME_ACCESS))
1160 goto the_end;
1162 /* NT resets the STD_*_HANDLEs on console alloc */
1163 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1164 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1165 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1167 SetLastError(ERROR_SUCCESS);
1169 return TRUE;
1171 the_end:
1172 ERR("Can't allocate console\n");
1173 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1174 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1175 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1176 FreeConsole();
1177 return FALSE;
1181 /***********************************************************************
1182 * ReadConsoleA (KERNEL32.@)
1184 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1185 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1187 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1188 DWORD ncr = 0;
1189 BOOL ret;
1191 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1192 ncr = WideCharToMultiByte(CP_ACP, 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1194 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1195 HeapFree(GetProcessHeap(), 0, ptr);
1197 return ret;
1200 /***********************************************************************
1201 * ReadConsoleW (KERNEL32.@)
1203 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1204 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1206 DWORD charsread;
1207 LPWSTR xbuf = (LPWSTR)lpBuffer;
1208 DWORD mode;
1210 TRACE("(%p,%p,%ld,%p,%p)\n",
1211 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1213 if (!GetConsoleMode(hConsoleInput, &mode))
1214 return FALSE;
1216 if (mode & ENABLE_LINE_INPUT)
1218 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1220 if (S_EditString) HeapFree(GetProcessHeap(), 0, S_EditString);
1221 if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1222 return FALSE;
1223 S_EditStrPos = 0;
1225 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1226 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1227 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1228 S_EditStrPos += charsread;
1230 else
1232 INPUT_RECORD ir;
1233 DWORD timeout = INFINITE;
1235 /* FIXME: should we read at least 1 char? The SDK does not say */
1236 /* wait for at least one available input record (it doesn't mean we'll have
1237 * chars stored in xbuf...)
1239 charsread = 0;
1242 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1243 timeout = 0;
1244 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1245 ir.Event.KeyEvent.uChar.UnicodeChar &&
1246 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
1248 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1250 } while (charsread < nNumberOfCharsToRead);
1251 /* nothing has been read */
1252 if (timeout == INFINITE) return FALSE;
1255 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1257 return TRUE;
1261 /***********************************************************************
1262 * ReadConsoleInputW (KERNEL32.@)
1264 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1265 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1267 DWORD idx = 0;
1268 DWORD timeout = INFINITE;
1270 if (!nLength)
1272 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1273 return TRUE;
1276 /* loop until we get at least one event */
1277 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1278 ++idx < nLength)
1279 timeout = 0;
1281 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1282 return idx != 0;
1286 /******************************************************************************
1287 * WriteConsoleOutputCharacterW [KERNEL32.@] Copies character to consecutive
1288 * cells in the console screen buffer
1290 * PARAMS
1291 * hConsoleOutput [I] Handle to screen buffer
1292 * str [I] Pointer to buffer with chars to write
1293 * length [I] Number of cells to write to
1294 * coord [I] Coords of first cell
1295 * lpNumCharsWritten [O] Pointer to number of cells written
1297 * RETURNS
1298 * Success: TRUE
1299 * Failure: FALSE
1302 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1303 COORD coord, LPDWORD lpNumCharsWritten )
1305 BOOL ret;
1307 TRACE("(%p,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
1308 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1310 SERVER_START_REQ( write_console_output )
1312 req->handle = console_handle_unmap(hConsoleOutput);
1313 req->x = coord.X;
1314 req->y = coord.Y;
1315 req->mode = CHAR_INFO_MODE_TEXT;
1316 req->wrap = TRUE;
1317 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1318 if ((ret = !wine_server_call_err( req )))
1320 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1323 SERVER_END_REQ;
1324 return ret;
1328 /******************************************************************************
1329 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1331 * PARAMS
1332 * title [I] Address of new title
1334 * RETURNS
1335 * Success: TRUE
1336 * Failure: FALSE
1338 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1340 BOOL ret;
1342 TRACE("(%s)\n", debugstr_w(title));
1343 SERVER_START_REQ( set_console_input_info )
1345 req->handle = 0;
1346 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1347 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1348 ret = !wine_server_call_err( req );
1350 SERVER_END_REQ;
1351 return ret;
1355 /***********************************************************************
1356 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1358 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1360 FIXME("(%p): stub\n", nrofbuttons);
1361 *nrofbuttons = 2;
1362 return TRUE;
1365 /******************************************************************************
1366 * SetConsoleInputExeNameW [KERNEL32.@]
1368 * BUGS
1369 * Unimplemented
1371 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1373 FIXME("(%s): stub!\n", debugstr_w(name));
1375 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1376 return TRUE;
1379 /******************************************************************************
1380 * SetConsoleInputExeNameA [KERNEL32.@]
1382 * BUGS
1383 * Unimplemented
1385 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1387 int len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1388 LPWSTR xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1389 BOOL ret;
1391 if (!xptr) return FALSE;
1393 MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
1394 ret = SetConsoleInputExeNameW(xptr);
1395 HeapFree(GetProcessHeap(), 0, xptr);
1397 return ret;
1400 /******************************************************************
1401 * CONSOLE_DefaultHandler
1403 * Final control event handler
1405 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1407 FIXME("Terminating process %lx on event %lx\n", GetCurrentProcessId(), dwCtrlType);
1408 ExitProcess(0);
1409 /* should never go here */
1410 return TRUE;
1413 /******************************************************************************
1414 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1416 * PARAMS
1417 * func [I] Address of handler function
1418 * add [I] Handler to add or remove
1420 * RETURNS
1421 * Success: TRUE
1422 * Failure: FALSE
1425 struct ConsoleHandler
1427 PHANDLER_ROUTINE handler;
1428 struct ConsoleHandler* next;
1431 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1432 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1434 static CRITICAL_SECTION CONSOLE_CritSect;
1435 static CRITICAL_SECTION_DEBUG critsect_debug =
1437 0, 0, &CONSOLE_CritSect,
1438 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
1439 0, 0, { 0, (DWORD)(__FILE__ ": CONSOLE_CritSect") }
1441 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
1443 /*****************************************************************************/
1445 /******************************************************************
1446 * SetConsoleCtrlHandler (KERNEL32.@)
1448 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1450 BOOL ret = TRUE;
1452 TRACE("(%p,%i)\n", func, add);
1454 if (!func)
1456 RtlEnterCriticalSection(&CONSOLE_CritSect);
1457 if (add)
1458 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1459 else
1460 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1461 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1463 else if (add)
1465 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1467 if (!ch) return FALSE;
1468 ch->handler = func;
1469 RtlEnterCriticalSection(&CONSOLE_CritSect);
1470 ch->next = CONSOLE_Handlers;
1471 CONSOLE_Handlers = ch;
1472 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1474 else
1476 struct ConsoleHandler** ch;
1477 RtlEnterCriticalSection(&CONSOLE_CritSect);
1478 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1480 if ((*ch)->handler == func) break;
1482 if (*ch)
1484 struct ConsoleHandler* rch = *ch;
1486 /* sanity check */
1487 if (rch == &CONSOLE_DefaultConsoleHandler)
1489 ERR("Who's trying to remove default handler???\n");
1490 SetLastError(ERROR_INVALID_PARAMETER);
1491 ret = FALSE;
1493 else
1495 *ch = rch->next;
1496 HeapFree(GetProcessHeap(), 0, rch);
1499 else
1501 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1502 SetLastError(ERROR_INVALID_PARAMETER);
1503 ret = FALSE;
1505 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1507 return ret;
1510 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
1512 TRACE("(%lx)\n", GetExceptionCode());
1513 return EXCEPTION_EXECUTE_HANDLER;
1516 /******************************************************************
1517 * CONSOLE_SendEventThread
1519 * Internal helper to pass an event to the list on installed handlers
1521 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1523 DWORD event = (DWORD)pmt;
1524 struct ConsoleHandler* ch;
1526 if (event == CTRL_C_EVENT)
1528 BOOL caught_by_dbg = TRUE;
1529 /* First, try to pass the ctrl-C event to the debugger (if any)
1530 * If it continues, there's nothing more to do
1531 * Otherwise, we need to send the ctrl-C event to the handlers
1533 __TRY
1535 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1537 __EXCEPT(CONSOLE_CtrlEventHandler)
1539 caught_by_dbg = FALSE;
1541 __ENDTRY;
1542 if (caught_by_dbg) return 0;
1543 /* the debugger didn't continue... so, pass to ctrl handlers */
1545 RtlEnterCriticalSection(&CONSOLE_CritSect);
1546 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1548 if (ch->handler(event)) break;
1550 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1551 return 1;
1554 /******************************************************************
1555 * CONSOLE_HandleCtrlC
1557 * Check whether the shall manipulate CtrlC events
1559 int CONSOLE_HandleCtrlC(unsigned sig)
1561 /* FIXME: better test whether a console is attached to this process ??? */
1562 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1563 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1565 /* check if we have to ignore ctrl-C events */
1566 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1568 /* Create a separate thread to signal all the events.
1569 * This is needed because:
1570 * - this function can be called in an Unix signal handler (hence on an
1571 * different stack than the thread that's running). This breaks the
1572 * Win32 exception mechanisms (where the thread's stack is checked).
1573 * - since the current thread, while processing the signal, can hold the
1574 * console critical section, we need another execution environment where
1575 * we can wait on this critical section
1577 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1579 return 1;
1582 /******************************************************************************
1583 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1585 * PARAMS
1586 * dwCtrlEvent [I] Type of event
1587 * dwProcessGroupID [I] Process group ID to send event to
1589 * RETURNS
1590 * Success: True
1591 * Failure: False (and *should* [but doesn't] set LastError)
1593 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1594 DWORD dwProcessGroupID)
1596 BOOL ret;
1598 TRACE("(%ld, %ld)\n", dwCtrlEvent, dwProcessGroupID);
1600 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1602 ERR("Invalid event %ld for PGID %ld\n", dwCtrlEvent, dwProcessGroupID);
1603 return FALSE;
1606 SERVER_START_REQ( send_console_signal )
1608 req->signal = dwCtrlEvent;
1609 req->group_id = dwProcessGroupID;
1610 ret = !wine_server_call_err( req );
1612 SERVER_END_REQ;
1614 /* FIXME: shall this function be synchronous, ie only return when all events
1615 * have been handled by all processes in the given group ?
1616 * As of today, we don't wait...
1618 return ret;
1622 /******************************************************************************
1623 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
1625 * PARAMS
1626 * dwDesiredAccess [I] Access flag
1627 * dwShareMode [I] Buffer share mode
1628 * sa [I] Security attributes
1629 * dwFlags [I] Type of buffer to create
1630 * lpScreenBufferData [I] Reserved
1632 * NOTES
1633 * Should call SetLastError
1635 * RETURNS
1636 * Success: Handle to new console screen buffer
1637 * Failure: INVALID_HANDLE_VALUE
1639 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1640 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1641 LPVOID lpScreenBufferData)
1643 HANDLE ret = INVALID_HANDLE_VALUE;
1645 TRACE("(%ld,%ld,%p,%ld,%p)\n",
1646 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1648 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1650 SetLastError(ERROR_INVALID_PARAMETER);
1651 return INVALID_HANDLE_VALUE;
1654 SERVER_START_REQ(create_console_output)
1656 req->handle_in = 0;
1657 req->access = dwDesiredAccess;
1658 req->share = dwShareMode;
1659 req->inherit = (sa && sa->bInheritHandle);
1660 if (!wine_server_call_err( req )) ret = reply->handle_out;
1662 SERVER_END_REQ;
1664 return ret;
1668 /***********************************************************************
1669 * GetConsoleScreenBufferInfo (KERNEL32.@)
1671 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1673 BOOL ret;
1675 SERVER_START_REQ(get_console_output_info)
1677 req->handle = console_handle_unmap(hConsoleOutput);
1678 if ((ret = !wine_server_call_err( req )))
1680 csbi->dwSize.X = reply->width;
1681 csbi->dwSize.Y = reply->height;
1682 csbi->dwCursorPosition.X = reply->cursor_x;
1683 csbi->dwCursorPosition.Y = reply->cursor_y;
1684 csbi->wAttributes = reply->attr;
1685 csbi->srWindow.Left = reply->win_left;
1686 csbi->srWindow.Right = reply->win_right;
1687 csbi->srWindow.Top = reply->win_top;
1688 csbi->srWindow.Bottom = reply->win_bottom;
1689 csbi->dwMaximumWindowSize.X = reply->max_width;
1690 csbi->dwMaximumWindowSize.Y = reply->max_height;
1693 SERVER_END_REQ;
1695 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
1696 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1697 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1698 csbi->wAttributes,
1699 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1700 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1702 return ret;
1706 /******************************************************************************
1707 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
1709 * RETURNS
1710 * Success: TRUE
1711 * Failure: FALSE
1713 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1715 BOOL ret;
1717 TRACE("(%p)\n", hConsoleOutput);
1719 SERVER_START_REQ( set_console_input_info )
1721 req->handle = 0;
1722 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1723 req->active_sb = hConsoleOutput;
1724 ret = !wine_server_call_err( req );
1726 SERVER_END_REQ;
1727 return ret;
1731 /***********************************************************************
1732 * GetConsoleMode (KERNEL32.@)
1734 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1736 BOOL ret;
1738 SERVER_START_REQ(get_console_mode)
1740 req->handle = console_handle_unmap(hcon);
1741 ret = !wine_server_call_err( req );
1742 if (ret && mode) *mode = reply->mode;
1744 SERVER_END_REQ;
1745 return ret;
1749 /******************************************************************************
1750 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
1752 * PARAMS
1753 * hcon [I] Handle to console input or screen buffer
1754 * mode [I] Input or output mode to set
1756 * RETURNS
1757 * Success: TRUE
1758 * Failure: FALSE
1760 * mode:
1761 * ENABLE_PROCESSED_INPUT 0x01
1762 * ENABLE_LINE_INPUT 0x02
1763 * ENABLE_ECHO_INPUT 0x04
1764 * ENABLE_WINDOW_INPUT 0x08
1765 * ENABLE_MOUSE_INPUT 0x10
1767 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1769 BOOL ret;
1771 SERVER_START_REQ(set_console_mode)
1773 req->handle = console_handle_unmap(hcon);
1774 req->mode = mode;
1775 ret = !wine_server_call_err( req );
1777 SERVER_END_REQ;
1778 /* FIXME: when resetting a console input to editline mode, I think we should
1779 * empty the S_EditString buffer
1782 TRACE("(%p,%lx) retval == %d\n", hcon, mode, ret);
1784 return ret;
1788 /******************************************************************
1789 * CONSOLE_WriteChars
1791 * WriteConsoleOutput helper: hides server call semantics
1792 * writes a string at a given pos with standard attribute
1794 int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1796 int written = -1;
1798 if (!nc) return 0;
1800 SERVER_START_REQ( write_console_output )
1802 req->handle = console_handle_unmap(hCon);
1803 req->x = pos->X;
1804 req->y = pos->Y;
1805 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1806 req->wrap = FALSE;
1807 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1808 if (!wine_server_call_err( req )) written = reply->written;
1810 SERVER_END_REQ;
1812 if (written > 0) pos->X += written;
1813 return written;
1816 /******************************************************************
1817 * next_line
1819 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1822 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1824 SMALL_RECT src;
1825 CHAR_INFO ci;
1826 COORD dst;
1828 csbi->dwCursorPosition.X = 0;
1829 csbi->dwCursorPosition.Y++;
1831 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1833 src.Top = 1;
1834 src.Bottom = csbi->dwSize.Y - 1;
1835 src.Left = 0;
1836 src.Right = csbi->dwSize.X - 1;
1838 dst.X = 0;
1839 dst.Y = 0;
1841 ci.Attributes = csbi->wAttributes;
1842 ci.Char.UnicodeChar = ' ';
1844 csbi->dwCursorPosition.Y--;
1845 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1846 return 0;
1847 return 1;
1850 /******************************************************************
1851 * write_block
1853 * WriteConsoleOutput helper: writes a block of non special characters
1854 * Block can spread on several lines, and wrapping, if needed, is
1855 * handled
1858 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1859 DWORD mode, LPCWSTR ptr, int len)
1861 int blk; /* number of chars to write on current line */
1862 int done; /* number of chars already written */
1864 if (len <= 0) return 1;
1866 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1868 for (done = 0; done < len; done += blk)
1870 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1872 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1873 return 0;
1874 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
1875 return 0;
1878 else
1880 int pos = csbi->dwCursorPosition.X;
1881 /* FIXME: we could reduce the number of loops
1882 * but, in most cases we wouldn't gain lots of time (it would only
1883 * happen if we're asked to overwrite more than twice the part of the line,
1884 * which is unlikely
1886 for (blk = done = 0; done < len; done += blk)
1888 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1890 csbi->dwCursorPosition.X = pos;
1891 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1892 return 0;
1896 return 1;
1899 /***********************************************************************
1900 * WriteConsoleW (KERNEL32.@)
1902 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1903 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1905 DWORD mode;
1906 DWORD nw = 0;
1907 const WCHAR* psz = lpBuffer;
1908 CONSOLE_SCREEN_BUFFER_INFO csbi;
1909 int k, first = 0;
1911 TRACE("%p %s %ld %p %p\n",
1912 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
1913 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
1915 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1917 if (!GetConsoleMode(hConsoleOutput, &mode) ||
1918 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1919 return FALSE;
1921 if (mode & ENABLE_PROCESSED_OUTPUT)
1923 unsigned int i;
1925 for (i = 0; i < nNumberOfCharsToWrite; i++)
1927 switch (psz[i])
1929 case '\b': case '\t': case '\n': case '\a': case '\r':
1930 /* don't handle here the i-th char... done below */
1931 if ((k = i - first) > 0)
1933 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1934 goto the_end;
1935 nw += k;
1937 first = i + 1;
1938 nw++;
1940 switch (psz[i])
1942 case '\b':
1943 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
1944 break;
1945 case '\t':
1947 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
1949 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
1950 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
1951 goto the_end;
1953 break;
1954 case '\n':
1955 next_line(hConsoleOutput, &csbi);
1956 break;
1957 case '\a':
1958 Beep(400, 300);
1959 break;
1960 case '\r':
1961 csbi.dwCursorPosition.X = 0;
1962 break;
1963 default:
1964 break;
1969 /* write the remaining block (if any) if processed output is enabled, or the
1970 * entire buffer otherwise
1972 if ((k = nNumberOfCharsToWrite - first) > 0)
1974 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1975 goto the_end;
1976 nw += k;
1979 the_end:
1980 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
1981 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
1982 return nw != 0;
1986 /***********************************************************************
1987 * WriteConsoleA (KERNEL32.@)
1989 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1990 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1992 BOOL ret;
1993 LPWSTR xstring;
1994 DWORD n;
1996 n = MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
1998 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1999 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2000 if (!xstring) return 0;
2002 MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2004 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2006 HeapFree(GetProcessHeap(), 0, xstring);
2008 return ret;
2011 /******************************************************************************
2012 * SetConsoleCursorPosition [KERNEL32.@]
2013 * Sets the cursor position in console
2015 * PARAMS
2016 * hConsoleOutput [I] Handle of console screen buffer
2017 * dwCursorPosition [I] New cursor position coordinates
2019 * RETURNS STD
2021 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2023 BOOL ret;
2024 CONSOLE_SCREEN_BUFFER_INFO csbi;
2025 int do_move = 0;
2026 int w, h;
2028 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2030 SERVER_START_REQ(set_console_output_info)
2032 req->handle = console_handle_unmap(hcon);
2033 req->cursor_x = pos.X;
2034 req->cursor_y = pos.Y;
2035 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2036 ret = !wine_server_call_err( req );
2038 SERVER_END_REQ;
2040 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2041 return FALSE;
2043 /* if cursor is no longer visible, scroll the visible window... */
2044 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2045 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2046 if (pos.X < csbi.srWindow.Left)
2048 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2049 do_move++;
2051 else if (pos.X > csbi.srWindow.Right)
2053 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2054 do_move++;
2056 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2058 if (pos.Y < csbi.srWindow.Top)
2060 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2061 do_move++;
2063 else if (pos.Y > csbi.srWindow.Bottom)
2065 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2066 do_move++;
2068 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2070 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2072 return ret;
2075 /******************************************************************************
2076 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2078 * PARAMS
2079 * hcon [I] Handle to console screen buffer
2080 * cinfo [O] Address of cursor information
2082 * RETURNS
2083 * Success: TRUE
2084 * Failure: FALSE
2086 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2088 BOOL ret;
2090 SERVER_START_REQ(get_console_output_info)
2092 req->handle = console_handle_unmap(hCon);
2093 ret = !wine_server_call_err( req );
2094 if (ret && cinfo)
2096 cinfo->dwSize = reply->cursor_size;
2097 cinfo->bVisible = reply->cursor_visible;
2100 SERVER_END_REQ;
2102 TRACE("(%p) returning (%ld,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2103 return ret;
2107 /******************************************************************************
2108 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2110 * PARAMS
2111 * hcon [I] Handle to console screen buffer
2112 * cinfo [I] Address of cursor information
2113 * RETURNS
2114 * Success: TRUE
2115 * Failure: FALSE
2117 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2119 BOOL ret;
2121 TRACE("(%p,%ld,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2122 SERVER_START_REQ(set_console_output_info)
2124 req->handle = console_handle_unmap(hCon);
2125 req->cursor_size = cinfo->dwSize;
2126 req->cursor_visible = cinfo->bVisible;
2127 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2128 ret = !wine_server_call_err( req );
2130 SERVER_END_REQ;
2131 return ret;
2135 /******************************************************************************
2136 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2138 * PARAMS
2139 * hcon [I] Handle to console screen buffer
2140 * bAbsolute [I] Coordinate type flag
2141 * window [I] Address of new window rectangle
2142 * RETURNS
2143 * Success: TRUE
2144 * Failure: FALSE
2146 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2148 SMALL_RECT p = *window;
2149 BOOL ret;
2151 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2153 if (!bAbsolute)
2155 CONSOLE_SCREEN_BUFFER_INFO csbi;
2157 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2158 return FALSE;
2159 p.Left += csbi.srWindow.Left;
2160 p.Top += csbi.srWindow.Top;
2161 p.Right += csbi.srWindow.Right;
2162 p.Bottom += csbi.srWindow.Bottom;
2164 SERVER_START_REQ(set_console_output_info)
2166 req->handle = console_handle_unmap(hCon);
2167 req->win_left = p.Left;
2168 req->win_top = p.Top;
2169 req->win_right = p.Right;
2170 req->win_bottom = p.Bottom;
2171 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2172 ret = !wine_server_call_err( req );
2174 SERVER_END_REQ;
2176 return ret;
2180 /******************************************************************************
2181 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2183 * Sets the foreground and background color attributes of characters
2184 * written to the screen buffer.
2186 * RETURNS
2187 * Success: TRUE
2188 * Failure: FALSE
2190 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2192 BOOL ret;
2194 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2195 SERVER_START_REQ(set_console_output_info)
2197 req->handle = console_handle_unmap(hConsoleOutput);
2198 req->attr = wAttr;
2199 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2200 ret = !wine_server_call_err( req );
2202 SERVER_END_REQ;
2203 return ret;
2207 /******************************************************************************
2208 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2210 * PARAMS
2211 * hConsoleOutput [I] Handle to console screen buffer
2212 * dwSize [I] New size in character rows and cols
2214 * RETURNS
2215 * Success: TRUE
2216 * Failure: FALSE
2218 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2220 BOOL ret;
2222 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2223 SERVER_START_REQ(set_console_output_info)
2225 req->handle = console_handle_unmap(hConsoleOutput);
2226 req->width = dwSize.X;
2227 req->height = dwSize.Y;
2228 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2229 ret = !wine_server_call_err( req );
2231 SERVER_END_REQ;
2232 return ret;
2236 /******************************************************************************
2237 * ScrollConsoleScreenBufferA [KERNEL32.@]
2240 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2241 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2242 LPCHAR_INFO lpFill)
2244 CHAR_INFO ciw;
2246 ciw.Attributes = lpFill->Attributes;
2247 MultiByteToWideChar(CP_ACP, 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2249 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2250 dwDestOrigin, &ciw);
2253 /******************************************************************
2254 * CONSOLE_FillLineUniform
2256 * Helper function for ScrollConsoleScreenBufferW
2257 * Fills a part of a line with a constant character info
2259 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2261 SERVER_START_REQ( fill_console_output )
2263 req->handle = console_handle_unmap(hConsoleOutput);
2264 req->mode = CHAR_INFO_MODE_TEXTATTR;
2265 req->x = i;
2266 req->y = j;
2267 req->count = len;
2268 req->wrap = FALSE;
2269 req->data.ch = lpFill->Char.UnicodeChar;
2270 req->data.attr = lpFill->Attributes;
2271 wine_server_call_err( req );
2273 SERVER_END_REQ;
2276 /******************************************************************************
2277 * ScrollConsoleScreenBufferW [KERNEL32.@]
2281 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2282 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2283 LPCHAR_INFO lpFill)
2285 SMALL_RECT dst;
2286 DWORD ret;
2287 int i, j;
2288 int start = -1;
2289 SMALL_RECT clip;
2290 CONSOLE_SCREEN_BUFFER_INFO csbi;
2291 BOOL inside;
2293 if (lpClipRect)
2294 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2295 lpScrollRect->Left, lpScrollRect->Top,
2296 lpScrollRect->Right, lpScrollRect->Bottom,
2297 lpClipRect->Left, lpClipRect->Top,
2298 lpClipRect->Right, lpClipRect->Bottom,
2299 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2300 else
2301 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2302 lpScrollRect->Left, lpScrollRect->Top,
2303 lpScrollRect->Right, lpScrollRect->Bottom,
2304 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2306 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2307 return FALSE;
2309 /* step 1: get dst rect */
2310 dst.Left = dwDestOrigin.X;
2311 dst.Top = dwDestOrigin.Y;
2312 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2313 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2315 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2316 if (lpClipRect)
2318 clip.Left = max(0, lpClipRect->Left);
2319 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2320 clip.Top = max(0, lpClipRect->Top);
2321 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2323 else
2325 clip.Left = 0;
2326 clip.Right = csbi.dwSize.X - 1;
2327 clip.Top = 0;
2328 clip.Bottom = csbi.dwSize.Y - 1;
2330 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2332 /* step 2b: clip dst rect */
2333 if (dst.Left < clip.Left ) dst.Left = clip.Left;
2334 if (dst.Top < clip.Top ) dst.Top = clip.Top;
2335 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2336 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2338 /* step 3: transfer the bits */
2339 SERVER_START_REQ(move_console_output)
2341 req->handle = console_handle_unmap(hConsoleOutput);
2342 req->x_src = lpScrollRect->Left;
2343 req->y_src = lpScrollRect->Top;
2344 req->x_dst = dst.Left;
2345 req->y_dst = dst.Top;
2346 req->w = dst.Right - dst.Left + 1;
2347 req->h = dst.Bottom - dst.Top + 1;
2348 ret = !wine_server_call_err( req );
2350 SERVER_END_REQ;
2352 if (!ret) return FALSE;
2354 /* step 4: clean out the exposed part */
2356 /* have to write cell [i,j] if it is not in dst rect (because it has already
2357 * been written to by the scroll) and is in clip (we shall not write
2358 * outside of clip)
2360 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2362 inside = dst.Top <= j && j <= dst.Bottom;
2363 start = -1;
2364 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2366 if (inside && dst.Left <= i && i <= dst.Right)
2368 if (start != -1)
2370 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2371 start = -1;
2374 else
2376 if (start == -1) start = i;
2379 if (start != -1)
2380 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2383 return TRUE;
2387 /* ====================================================================
2389 * Console manipulation functions
2391 * ====================================================================*/
2393 /* some missing functions...
2394 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2395 * should get the right API and implement them
2396 * GetConsoleCommandHistory[AW] (dword dword dword)
2397 * GetConsoleCommandHistoryLength[AW]
2398 * SetConsoleCommandHistoryMode
2399 * SetConsoleNumberOfCommands[AW]
2401 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2403 int len = 0;
2405 SERVER_START_REQ( get_console_input_history )
2407 req->handle = 0;
2408 req->index = idx;
2409 if (buf && buf_len > 1)
2411 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2413 if (!wine_server_call_err( req ))
2415 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2416 len = reply->total / sizeof(WCHAR) + 1;
2419 SERVER_END_REQ;
2420 return len;
2423 /******************************************************************
2424 * CONSOLE_AppendHistory
2428 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2430 size_t len = strlenW(ptr);
2431 BOOL ret;
2433 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2435 SERVER_START_REQ( append_console_input_history )
2437 req->handle = 0;
2438 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2439 ret = !wine_server_call_err( req );
2441 SERVER_END_REQ;
2442 return ret;
2445 /******************************************************************
2446 * CONSOLE_GetNumHistoryEntries
2450 unsigned CONSOLE_GetNumHistoryEntries(void)
2452 unsigned ret = -1;
2453 SERVER_START_REQ(get_console_input_info)
2455 req->handle = 0;
2456 if (!wine_server_call_err( req )) ret = reply->history_index;
2458 SERVER_END_REQ;
2459 return ret;
2462 /******************************************************************
2463 * CONSOLE_GetEditionMode
2467 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2469 unsigned ret = FALSE;
2470 SERVER_START_REQ(get_console_input_info)
2472 req->handle = console_handle_unmap(hConIn);
2473 if ((ret = !wine_server_call_err( req )))
2474 *mode = reply->edition_mode;
2476 SERVER_END_REQ;
2477 return ret;