powrprof: Add stubs for PowerGetActiveScheme and PowerReadDCValue.
[wine/hacks.git] / dlls / kernel32 / console.c
blobeb3e21d54b1ed75bb05b723cc8b33e3cca0e0385
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/server.h"
48 #include "wine/exception.h"
49 #include "wine/unicode.h"
50 #include "wine/debug.h"
51 #include "excpt.h"
52 #include "console_private.h"
53 #include "kernel_private.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(console);
57 static CRITICAL_SECTION CONSOLE_CritSect;
58 static CRITICAL_SECTION_DEBUG critsect_debug =
60 0, 0, &CONSOLE_CritSect,
61 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
62 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
64 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
66 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
67 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
69 /* FIXME: this is not thread safe */
70 static HANDLE console_wait_event;
72 /* map input records to ASCII */
73 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
75 int i;
76 char ch;
78 for (i = 0; i < count; i++)
80 if (buffer[i].EventType != KEY_EVENT) continue;
81 WideCharToMultiByte( GetConsoleCP(), 0,
82 &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
83 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
87 /* map input records to Unicode */
88 static void input_records_AtoW( INPUT_RECORD *buffer, int count )
90 int i;
91 WCHAR ch;
93 for (i = 0; i < count; i++)
95 if (buffer[i].EventType != KEY_EVENT) continue;
96 MultiByteToWideChar( GetConsoleCP(), 0,
97 &buffer[i].Event.KeyEvent.uChar.AsciiChar, 1, &ch, 1 );
98 buffer[i].Event.KeyEvent.uChar.UnicodeChar = ch;
102 /* map char infos to ASCII */
103 static void char_info_WtoA( CHAR_INFO *buffer, int count )
105 char ch;
107 while (count-- > 0)
109 WideCharToMultiByte( GetConsoleOutputCP(), 0, &buffer->Char.UnicodeChar, 1,
110 &ch, 1, NULL, NULL );
111 buffer->Char.AsciiChar = ch;
112 buffer++;
116 /* map char infos to Unicode */
117 static void char_info_AtoW( CHAR_INFO *buffer, int count )
119 WCHAR ch;
121 while (count-- > 0)
123 MultiByteToWideChar( GetConsoleOutputCP(), 0, &buffer->Char.AsciiChar, 1, &ch, 1 );
124 buffer->Char.UnicodeChar = ch;
125 buffer++;
130 /******************************************************************************
131 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
133 * RETURNS
134 * Success: hwnd of the console window.
135 * Failure: NULL
137 HWND WINAPI GetConsoleWindow(VOID)
139 HWND hWnd = NULL;
141 SERVER_START_REQ(get_console_input_info)
143 req->handle = 0;
144 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
146 SERVER_END_REQ;
148 return hWnd;
152 /******************************************************************************
153 * GetConsoleCP [KERNEL32.@] Returns the OEM code page for the console
155 * RETURNS
156 * Code page code
158 UINT WINAPI GetConsoleCP(VOID)
160 BOOL ret;
161 UINT codepage = GetOEMCP(); /* default value */
163 SERVER_START_REQ(get_console_input_info)
165 req->handle = 0;
166 ret = !wine_server_call_err(req);
167 if (ret && reply->input_cp)
168 codepage = reply->input_cp;
170 SERVER_END_REQ;
172 return codepage;
176 /******************************************************************************
177 * SetConsoleCP [KERNEL32.@]
179 BOOL WINAPI SetConsoleCP(UINT cp)
181 BOOL ret;
183 if (!IsValidCodePage(cp))
185 SetLastError(ERROR_INVALID_PARAMETER);
186 return FALSE;
189 SERVER_START_REQ(set_console_input_info)
191 req->handle = 0;
192 req->mask = SET_CONSOLE_INPUT_INFO_INPUT_CODEPAGE;
193 req->input_cp = cp;
194 ret = !wine_server_call_err(req);
196 SERVER_END_REQ;
198 return ret;
202 /***********************************************************************
203 * GetConsoleOutputCP (KERNEL32.@)
205 UINT WINAPI GetConsoleOutputCP(VOID)
207 BOOL ret;
208 UINT codepage = GetOEMCP(); /* default value */
210 SERVER_START_REQ(get_console_input_info)
212 req->handle = 0;
213 ret = !wine_server_call_err(req);
214 if (ret && reply->output_cp)
215 codepage = reply->output_cp;
217 SERVER_END_REQ;
219 return codepage;
223 /******************************************************************************
224 * SetConsoleOutputCP [KERNEL32.@] Set the output codepage used by the console
226 * PARAMS
227 * cp [I] code page to set
229 * RETURNS
230 * Success: TRUE
231 * Failure: FALSE
233 BOOL WINAPI SetConsoleOutputCP(UINT cp)
235 BOOL ret;
237 if (!IsValidCodePage(cp))
239 SetLastError(ERROR_INVALID_PARAMETER);
240 return FALSE;
243 SERVER_START_REQ(set_console_input_info)
245 req->handle = 0;
246 req->mask = SET_CONSOLE_INPUT_INFO_OUTPUT_CODEPAGE;
247 req->output_cp = cp;
248 ret = !wine_server_call_err(req);
250 SERVER_END_REQ;
252 return ret;
256 /***********************************************************************
257 * Beep (KERNEL32.@)
259 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
261 static const char beep = '\a';
262 /* dwFreq and dwDur are ignored by Win95 */
263 if (isatty(2)) write( 2, &beep, 1 );
264 return TRUE;
268 /******************************************************************
269 * OpenConsoleW (KERNEL32.@)
271 * Undocumented
272 * Open a handle to the current process console.
273 * Returns INVALID_HANDLE_VALUE on failure.
275 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
277 HANDLE output;
278 HANDLE ret;
280 if (strcmpiW(coninW, name) == 0)
281 output = (HANDLE) FALSE;
282 else if (strcmpiW(conoutW, name) == 0)
283 output = (HANDLE) TRUE;
284 else
286 SetLastError(ERROR_INVALID_NAME);
287 return INVALID_HANDLE_VALUE;
289 if (creation != OPEN_EXISTING)
291 SetLastError(ERROR_INVALID_PARAMETER);
292 return INVALID_HANDLE_VALUE;
295 SERVER_START_REQ( open_console )
297 req->from = wine_server_obj_handle( output );
298 req->access = access;
299 req->attributes = inherit ? OBJ_INHERIT : 0;
300 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
301 SetLastError(0);
302 wine_server_call_err( req );
303 ret = wine_server_ptr_handle( reply->handle );
305 SERVER_END_REQ;
306 if (ret)
307 ret = console_handle_map(ret);
308 else
310 /* likely, we're not attached to wineconsole
311 * let's try to return a handle to the unix-console
313 int fd = open("/dev/tty", output ? O_WRONLY : O_RDONLY);
314 ret = INVALID_HANDLE_VALUE;
315 if (fd != -1)
317 DWORD access = (output ? GENERIC_WRITE : GENERIC_READ) | SYNCHRONIZE;
318 wine_server_fd_to_handle(fd, access, inherit ? OBJ_INHERIT : 0, &ret);
319 close(fd);
322 return ret;
325 /******************************************************************
326 * VerifyConsoleIoHandle (KERNEL32.@)
328 * Undocumented
330 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
332 BOOL ret;
334 if (!is_console_handle(handle)) return FALSE;
335 SERVER_START_REQ(get_console_mode)
337 req->handle = console_handle_unmap(handle);
338 ret = !wine_server_call_err( req );
340 SERVER_END_REQ;
341 return ret;
344 /******************************************************************
345 * DuplicateConsoleHandle (KERNEL32.@)
347 * Undocumented
349 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
350 DWORD options)
352 HANDLE ret;
354 if (!is_console_handle(handle) ||
355 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
356 GetCurrentProcess(), &ret, access, inherit, options))
357 return INVALID_HANDLE_VALUE;
358 return console_handle_map(ret);
361 /******************************************************************
362 * CloseConsoleHandle (KERNEL32.@)
364 * Undocumented
366 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
368 if (!is_console_handle(handle))
370 SetLastError(ERROR_INVALID_PARAMETER);
371 return FALSE;
373 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
376 /******************************************************************
377 * GetConsoleInputWaitHandle (KERNEL32.@)
379 * Undocumented
381 HANDLE WINAPI GetConsoleInputWaitHandle(void)
383 if (!console_wait_event)
385 SERVER_START_REQ(get_console_wait_event)
387 if (!wine_server_call_err( req ))
388 console_wait_event = wine_server_ptr_handle( reply->handle );
390 SERVER_END_REQ;
392 return console_wait_event;
396 /******************************************************************************
397 * WriteConsoleInputA [KERNEL32.@]
399 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
400 DWORD count, LPDWORD written )
402 INPUT_RECORD *recW;
403 BOOL ret;
405 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
406 memcpy( recW, buffer, count*sizeof(*recW) );
407 input_records_AtoW( recW, count );
408 ret = WriteConsoleInputW( handle, recW, count, written );
409 HeapFree( GetProcessHeap(), 0, recW );
410 return ret;
414 /******************************************************************************
415 * WriteConsoleInputW [KERNEL32.@]
417 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
418 DWORD count, LPDWORD written )
420 BOOL ret;
422 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
424 if (written) *written = 0;
425 SERVER_START_REQ( write_console_input )
427 req->handle = console_handle_unmap(handle);
428 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
429 if ((ret = !wine_server_call_err( req )) && written)
430 *written = reply->written;
432 SERVER_END_REQ;
434 return ret;
438 /***********************************************************************
439 * WriteConsoleOutputA (KERNEL32.@)
441 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
442 COORD size, COORD coord, LPSMALL_RECT region )
444 int y;
445 BOOL ret;
446 COORD new_size, new_coord;
447 CHAR_INFO *ciw;
449 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
450 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
452 if (new_size.X <= 0 || new_size.Y <= 0)
454 region->Bottom = region->Top + new_size.Y - 1;
455 region->Right = region->Left + new_size.X - 1;
456 return TRUE;
459 /* only copy the useful rectangle */
460 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
461 return FALSE;
462 for (y = 0; y < new_size.Y; y++)
464 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
465 new_size.X * sizeof(CHAR_INFO) );
466 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
468 new_coord.X = new_coord.Y = 0;
469 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
470 HeapFree( GetProcessHeap(), 0, ciw );
471 return ret;
475 /***********************************************************************
476 * WriteConsoleOutputW (KERNEL32.@)
478 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
479 COORD size, COORD coord, LPSMALL_RECT region )
481 int width, height, y;
482 BOOL ret = TRUE;
484 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
485 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
486 region->Left, region->Top, region->Right, region->Bottom);
488 width = min( region->Right - region->Left + 1, size.X - coord.X );
489 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
491 if (width > 0 && height > 0)
493 for (y = 0; y < height; y++)
495 SERVER_START_REQ( write_console_output )
497 req->handle = console_handle_unmap(hConsoleOutput);
498 req->x = region->Left;
499 req->y = region->Top + y;
500 req->mode = CHAR_INFO_MODE_TEXTATTR;
501 req->wrap = FALSE;
502 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
503 width * sizeof(CHAR_INFO));
504 if ((ret = !wine_server_call_err( req )))
506 width = min( width, reply->width - region->Left );
507 height = min( height, reply->height - region->Top );
510 SERVER_END_REQ;
511 if (!ret) break;
514 region->Bottom = region->Top + height - 1;
515 region->Right = region->Left + width - 1;
516 return ret;
520 /******************************************************************************
521 * WriteConsoleOutputCharacterA [KERNEL32.@]
523 * See WriteConsoleOutputCharacterW.
525 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
526 COORD coord, LPDWORD lpNumCharsWritten )
528 BOOL ret;
529 LPWSTR strW;
530 DWORD lenW;
532 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
533 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
535 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
537 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
539 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
540 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
542 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
543 HeapFree( GetProcessHeap(), 0, strW );
544 return ret;
548 /******************************************************************************
549 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
550 * the console screen buffer
552 * PARAMS
553 * hConsoleOutput [I] Handle to screen buffer
554 * attr [I] Pointer to buffer with write attributes
555 * length [I] Number of cells to write to
556 * coord [I] Coords of first cell
557 * lpNumAttrsWritten [O] Pointer to number of cells written
559 * RETURNS
560 * Success: TRUE
561 * Failure: FALSE
564 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
565 COORD coord, LPDWORD lpNumAttrsWritten )
567 BOOL ret;
569 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
571 SERVER_START_REQ( write_console_output )
573 req->handle = console_handle_unmap(hConsoleOutput);
574 req->x = coord.X;
575 req->y = coord.Y;
576 req->mode = CHAR_INFO_MODE_ATTR;
577 req->wrap = TRUE;
578 wine_server_add_data( req, attr, length * sizeof(WORD) );
579 if ((ret = !wine_server_call_err( req )))
581 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
584 SERVER_END_REQ;
585 return ret;
589 /******************************************************************************
590 * FillConsoleOutputCharacterA [KERNEL32.@]
592 * See FillConsoleOutputCharacterW.
594 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
595 COORD coord, LPDWORD lpNumCharsWritten )
597 WCHAR wch;
599 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
600 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
604 /******************************************************************************
605 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
607 * PARAMS
608 * hConsoleOutput [I] Handle to screen buffer
609 * ch [I] Character to write
610 * length [I] Number of cells to write to
611 * coord [I] Coords of first cell
612 * lpNumCharsWritten [O] Pointer to number of cells written
614 * RETURNS
615 * Success: TRUE
616 * Failure: FALSE
618 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
619 COORD coord, LPDWORD lpNumCharsWritten)
621 BOOL ret;
623 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
624 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
626 SERVER_START_REQ( fill_console_output )
628 req->handle = console_handle_unmap(hConsoleOutput);
629 req->x = coord.X;
630 req->y = coord.Y;
631 req->mode = CHAR_INFO_MODE_TEXT;
632 req->wrap = TRUE;
633 req->data.ch = ch;
634 req->count = length;
635 if ((ret = !wine_server_call_err( req )))
637 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
640 SERVER_END_REQ;
641 return ret;
645 /******************************************************************************
646 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
648 * PARAMS
649 * hConsoleOutput [I] Handle to screen buffer
650 * attr [I] Color attribute to write
651 * length [I] Number of cells to write to
652 * coord [I] Coords of first cell
653 * lpNumAttrsWritten [O] Pointer to number of cells written
655 * RETURNS
656 * Success: TRUE
657 * Failure: FALSE
659 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
660 COORD coord, LPDWORD lpNumAttrsWritten )
662 BOOL ret;
664 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
665 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
667 SERVER_START_REQ( fill_console_output )
669 req->handle = console_handle_unmap(hConsoleOutput);
670 req->x = coord.X;
671 req->y = coord.Y;
672 req->mode = CHAR_INFO_MODE_ATTR;
673 req->wrap = TRUE;
674 req->data.attr = attr;
675 req->count = length;
676 if ((ret = !wine_server_call_err( req )))
678 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
681 SERVER_END_REQ;
682 return ret;
686 /******************************************************************************
687 * ReadConsoleOutputCharacterA [KERNEL32.@]
690 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
691 COORD coord, LPDWORD read_count)
693 DWORD read;
694 BOOL ret;
695 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
697 if (read_count) *read_count = 0;
698 if (!wptr) return FALSE;
700 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
702 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
703 if (read_count) *read_count = read;
705 HeapFree( GetProcessHeap(), 0, wptr );
706 return ret;
710 /******************************************************************************
711 * ReadConsoleOutputCharacterW [KERNEL32.@]
714 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
715 COORD coord, LPDWORD read_count )
717 BOOL ret;
719 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
721 SERVER_START_REQ( read_console_output )
723 req->handle = console_handle_unmap(hConsoleOutput);
724 req->x = coord.X;
725 req->y = coord.Y;
726 req->mode = CHAR_INFO_MODE_TEXT;
727 req->wrap = TRUE;
728 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
729 if ((ret = !wine_server_call_err( req )))
731 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
734 SERVER_END_REQ;
735 return ret;
739 /******************************************************************************
740 * ReadConsoleOutputAttribute [KERNEL32.@]
742 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
743 COORD coord, LPDWORD read_count)
745 BOOL ret;
747 TRACE("(%p,%p,%d,%dx%d,%p)\n",
748 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
750 SERVER_START_REQ( read_console_output )
752 req->handle = console_handle_unmap(hConsoleOutput);
753 req->x = coord.X;
754 req->y = coord.Y;
755 req->mode = CHAR_INFO_MODE_ATTR;
756 req->wrap = TRUE;
757 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
758 if ((ret = !wine_server_call_err( req )))
760 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
763 SERVER_END_REQ;
764 return ret;
768 /******************************************************************************
769 * ReadConsoleOutputA [KERNEL32.@]
772 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
773 COORD coord, LPSMALL_RECT region )
775 BOOL ret;
776 int y;
778 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
779 if (ret && region->Right >= region->Left)
781 for (y = 0; y <= region->Bottom - region->Top; y++)
783 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
784 region->Right - region->Left + 1 );
787 return ret;
791 /******************************************************************************
792 * ReadConsoleOutputW [KERNEL32.@]
794 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
795 * think we need to be *that* compatible. -- AJ
797 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
798 COORD coord, LPSMALL_RECT region )
800 int width, height, y;
801 BOOL ret = TRUE;
803 width = min( region->Right - region->Left + 1, size.X - coord.X );
804 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
806 if (width > 0 && height > 0)
808 for (y = 0; y < height; y++)
810 SERVER_START_REQ( read_console_output )
812 req->handle = console_handle_unmap(hConsoleOutput);
813 req->x = region->Left;
814 req->y = region->Top + y;
815 req->mode = CHAR_INFO_MODE_TEXTATTR;
816 req->wrap = FALSE;
817 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
818 width * sizeof(CHAR_INFO) );
819 if ((ret = !wine_server_call_err( req )))
821 width = min( width, reply->width - region->Left );
822 height = min( height, reply->height - region->Top );
825 SERVER_END_REQ;
826 if (!ret) break;
829 region->Bottom = region->Top + height - 1;
830 region->Right = region->Left + width - 1;
831 return ret;
835 /******************************************************************************
836 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
838 * PARAMS
839 * handle [I] Handle to console input buffer
840 * buffer [O] Address of buffer for read data
841 * count [I] Number of records to read
842 * pRead [O] Address of number of records read
844 * RETURNS
845 * Success: TRUE
846 * Failure: FALSE
848 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
850 DWORD read;
852 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
853 input_records_WtoA( buffer, read );
854 if (pRead) *pRead = read;
855 return TRUE;
859 /***********************************************************************
860 * PeekConsoleInputA (KERNEL32.@)
862 * Gets 'count' first events (or less) from input queue.
864 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
866 DWORD read;
868 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
869 input_records_WtoA( buffer, read );
870 if (pRead) *pRead = read;
871 return TRUE;
875 /***********************************************************************
876 * PeekConsoleInputW (KERNEL32.@)
878 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
880 BOOL ret;
881 SERVER_START_REQ( read_console_input )
883 req->handle = console_handle_unmap(handle);
884 req->flush = FALSE;
885 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
886 if ((ret = !wine_server_call_err( req )))
888 if (read) *read = count ? reply->read : 0;
891 SERVER_END_REQ;
892 return ret;
896 /***********************************************************************
897 * GetNumberOfConsoleInputEvents (KERNEL32.@)
899 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
901 BOOL ret;
902 SERVER_START_REQ( read_console_input )
904 req->handle = console_handle_unmap(handle);
905 req->flush = FALSE;
906 if ((ret = !wine_server_call_err( req )))
908 if (nrofevents) *nrofevents = reply->read;
911 SERVER_END_REQ;
912 return ret;
916 /******************************************************************************
917 * read_console_input
919 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
921 * Returns
922 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
924 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
925 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
927 enum read_console_input_return ret;
929 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
930 return rci_timeout;
931 SERVER_START_REQ( read_console_input )
933 req->handle = console_handle_unmap(handle);
934 req->flush = TRUE;
935 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
936 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
937 else ret = rci_gotone;
939 SERVER_END_REQ;
941 return ret;
945 /***********************************************************************
946 * FlushConsoleInputBuffer (KERNEL32.@)
948 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
950 enum read_console_input_return last;
951 INPUT_RECORD ir;
953 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
955 return last == rci_timeout;
959 /***********************************************************************
960 * SetConsoleTitleA (KERNEL32.@)
962 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
964 LPWSTR titleW;
965 BOOL ret;
967 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
968 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
969 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
970 ret = SetConsoleTitleW(titleW);
971 HeapFree(GetProcessHeap(), 0, titleW);
972 return ret;
976 /***********************************************************************
977 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
979 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
981 FIXME( "stub %p\n", layoutName);
982 return TRUE;
985 /***********************************************************************
986 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
988 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
990 FIXME( "stub %p\n", layoutName);
991 return TRUE;
994 static WCHAR input_exe[MAX_PATH + 1];
996 /***********************************************************************
997 * GetConsoleInputExeNameW (KERNEL32.@)
999 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1001 TRACE("%u %p\n", buflen, buffer);
1003 RtlEnterCriticalSection(&CONSOLE_CritSect);
1004 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1005 else SetLastError(ERROR_BUFFER_OVERFLOW);
1006 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1008 return TRUE;
1011 /***********************************************************************
1012 * GetConsoleInputExeNameA (KERNEL32.@)
1014 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1016 TRACE("%u %p\n", buflen, buffer);
1018 RtlEnterCriticalSection(&CONSOLE_CritSect);
1019 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1020 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1021 else SetLastError(ERROR_BUFFER_OVERFLOW);
1022 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1024 return TRUE;
1027 /***********************************************************************
1028 * GetConsoleTitleA (KERNEL32.@)
1030 * See GetConsoleTitleW.
1032 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1034 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1035 DWORD ret;
1037 if (!ptr) return 0;
1038 ret = GetConsoleTitleW( ptr, size );
1039 if (ret)
1041 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1042 ret = strlen(title);
1044 HeapFree(GetProcessHeap(), 0, ptr);
1045 return ret;
1049 /******************************************************************************
1050 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1052 * PARAMS
1053 * title [O] Address of buffer for title
1054 * size [I] Size of buffer
1056 * RETURNS
1057 * Success: Length of string copied
1058 * Failure: 0
1060 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1062 DWORD ret = 0;
1064 SERVER_START_REQ( get_console_input_info )
1066 req->handle = 0;
1067 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1068 if (!wine_server_call_err( req ))
1070 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1071 title[ret] = 0;
1074 SERVER_END_REQ;
1075 return ret;
1079 /***********************************************************************
1080 * GetLargestConsoleWindowSize (KERNEL32.@)
1082 * NOTE
1083 * This should return a COORD, but calling convention for returning
1084 * structures is different between Windows and gcc on i386.
1086 * VERSION: [i386]
1088 #ifdef __i386__
1089 #undef GetLargestConsoleWindowSize
1090 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1092 union {
1093 COORD c;
1094 DWORD w;
1095 } x;
1096 x.c.X = 80;
1097 x.c.Y = 24;
1098 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1099 return x.w;
1101 #endif /* defined(__i386__) */
1104 /***********************************************************************
1105 * GetLargestConsoleWindowSize (KERNEL32.@)
1107 * NOTE
1108 * This should return a COORD, but calling convention for returning
1109 * structures is different between Windows and gcc on i386.
1111 * VERSION: [!i386]
1113 #ifndef __i386__
1114 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1116 COORD c;
1117 c.X = 80;
1118 c.Y = 24;
1119 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1120 return c;
1122 #endif /* defined(__i386__) */
1124 static WCHAR* S_EditString /* = NULL */;
1125 static unsigned S_EditStrPos /* = 0 */;
1127 /***********************************************************************
1128 * FreeConsole (KERNEL32.@)
1130 BOOL WINAPI FreeConsole(VOID)
1132 BOOL ret;
1134 /* invalidate local copy of input event handle */
1135 console_wait_event = 0;
1137 SERVER_START_REQ(free_console)
1139 ret = !wine_server_call_err( req );
1141 SERVER_END_REQ;
1142 return ret;
1145 /******************************************************************
1146 * start_console_renderer
1148 * helper for AllocConsole
1149 * starts the renderer process
1151 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1152 HANDLE hEvent)
1154 char buffer[1024];
1155 int ret;
1156 PROCESS_INFORMATION pi;
1158 /* FIXME: use dynamic allocation for most of the buffers below */
1159 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1160 if ((ret > -1) && (ret < sizeof(buffer)) &&
1161 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1162 NULL, NULL, si, &pi))
1164 HANDLE wh[2];
1165 DWORD ret;
1167 wh[0] = hEvent;
1168 wh[1] = pi.hProcess;
1169 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1171 CloseHandle(pi.hThread);
1172 CloseHandle(pi.hProcess);
1174 if (ret != WAIT_OBJECT_0) return FALSE;
1176 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1177 pi.dwProcessId, pi.dwThreadId);
1179 return TRUE;
1181 return FALSE;
1184 static BOOL start_console_renderer(STARTUPINFOA* si)
1186 HANDLE hEvent = 0;
1187 LPSTR p;
1188 OBJECT_ATTRIBUTES attr;
1189 BOOL ret = FALSE;
1191 attr.Length = sizeof(attr);
1192 attr.RootDirectory = 0;
1193 attr.Attributes = OBJ_INHERIT;
1194 attr.ObjectName = NULL;
1195 attr.SecurityDescriptor = NULL;
1196 attr.SecurityQualityOfService = NULL;
1198 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1199 if (!hEvent) return FALSE;
1201 /* first try environment variable */
1202 if ((p = getenv("WINECONSOLE")) != NULL)
1204 ret = start_console_renderer_helper(p, si, hEvent);
1205 if (!ret)
1206 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1207 "trying default access\n", p);
1210 /* then try the regular PATH */
1211 if (!ret)
1212 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1214 CloseHandle(hEvent);
1215 return ret;
1218 /***********************************************************************
1219 * AllocConsole (KERNEL32.@)
1221 * creates an xterm with a pty to our program
1223 BOOL WINAPI AllocConsole(void)
1225 HANDLE handle_in = INVALID_HANDLE_VALUE;
1226 HANDLE handle_out = INVALID_HANDLE_VALUE;
1227 HANDLE handle_err = INVALID_HANDLE_VALUE;
1228 STARTUPINFOA siCurrent;
1229 STARTUPINFOA siConsole;
1230 char buffer[1024];
1232 TRACE("()\n");
1234 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1235 FALSE, OPEN_EXISTING );
1237 if (VerifyConsoleIoHandle(handle_in))
1239 /* we already have a console opened on this process, don't create a new one */
1240 CloseHandle(handle_in);
1241 return FALSE;
1243 /* happens when we're running on a Unix console */
1244 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1246 /* invalidate local copy of input event handle */
1247 console_wait_event = 0;
1249 GetStartupInfoA(&siCurrent);
1251 memset(&siConsole, 0, sizeof(siConsole));
1252 siConsole.cb = sizeof(siConsole);
1253 /* setup a view arguments for wineconsole (it'll use them as default values) */
1254 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1256 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1257 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1258 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1260 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1262 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1263 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1265 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1267 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1268 siConsole.wShowWindow = siCurrent.wShowWindow;
1270 /* FIXME (should pass the unicode form) */
1271 if (siCurrent.lpTitle)
1272 siConsole.lpTitle = siCurrent.lpTitle;
1273 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1275 buffer[sizeof(buffer) - 1] = '\0';
1276 siConsole.lpTitle = buffer;
1279 if (!start_console_renderer(&siConsole))
1280 goto the_end;
1282 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1283 /* all std I/O handles are inheritable by default */
1284 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1285 TRUE, OPEN_EXISTING );
1286 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1288 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1289 TRUE, OPEN_EXISTING );
1290 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1292 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1293 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1294 goto the_end;
1295 } else {
1296 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1297 handle_in = siCurrent.hStdInput;
1298 handle_out = siCurrent.hStdOutput;
1299 handle_err = siCurrent.hStdError;
1302 /* NT resets the STD_*_HANDLEs on console alloc */
1303 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1304 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1305 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1307 SetLastError(ERROR_SUCCESS);
1309 return TRUE;
1311 the_end:
1312 ERR("Can't allocate console\n");
1313 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1314 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1315 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1316 FreeConsole();
1317 return FALSE;
1321 /***********************************************************************
1322 * ReadConsoleA (KERNEL32.@)
1324 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1325 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1327 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1328 DWORD ncr = 0;
1329 BOOL ret;
1331 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1332 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1334 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1335 HeapFree(GetProcessHeap(), 0, ptr);
1337 return ret;
1340 /***********************************************************************
1341 * ReadConsoleW (KERNEL32.@)
1343 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1344 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1346 DWORD charsread;
1347 LPWSTR xbuf = lpBuffer;
1348 DWORD mode;
1350 TRACE("(%p,%p,%d,%p,%p)\n",
1351 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1353 if (!GetConsoleMode(hConsoleInput, &mode))
1354 return FALSE;
1356 if (mode & ENABLE_LINE_INPUT)
1358 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1360 HeapFree(GetProcessHeap(), 0, S_EditString);
1361 if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1362 return FALSE;
1363 S_EditStrPos = 0;
1365 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1366 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1367 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1368 S_EditStrPos += charsread;
1370 else
1372 INPUT_RECORD ir;
1373 DWORD timeout = INFINITE;
1375 /* FIXME: should we read at least 1 char? The SDK does not say */
1376 /* wait for at least one available input record (it doesn't mean we'll have
1377 * chars stored in xbuf...)
1379 * Although SDK doc keeps silence about 1 char, SDK examples assume
1380 * that we should wait for at least one character (not key). --KS
1382 charsread = 0;
1385 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1386 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1387 ir.Event.KeyEvent.uChar.UnicodeChar)
1389 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1390 timeout = 0;
1392 } while (charsread < nNumberOfCharsToRead);
1393 /* nothing has been read */
1394 if (timeout == INFINITE) return FALSE;
1397 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1399 return TRUE;
1403 /***********************************************************************
1404 * ReadConsoleInputW (KERNEL32.@)
1406 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1407 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1409 DWORD idx = 0;
1410 DWORD timeout = INFINITE;
1412 if (!nLength)
1414 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1415 return TRUE;
1418 /* loop until we get at least one event */
1419 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1420 ++idx < nLength)
1421 timeout = 0;
1423 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1424 return idx != 0;
1428 /******************************************************************************
1429 * WriteConsoleOutputCharacterW [KERNEL32.@]
1431 * Copy character to consecutive cells in the console screen buffer.
1433 * PARAMS
1434 * hConsoleOutput [I] Handle to screen buffer
1435 * str [I] Pointer to buffer with chars to write
1436 * length [I] Number of cells to write to
1437 * coord [I] Coords of first cell
1438 * lpNumCharsWritten [O] Pointer to number of cells written
1440 * RETURNS
1441 * Success: TRUE
1442 * Failure: FALSE
1445 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1446 COORD coord, LPDWORD lpNumCharsWritten )
1448 BOOL ret;
1450 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1451 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1453 SERVER_START_REQ( write_console_output )
1455 req->handle = console_handle_unmap(hConsoleOutput);
1456 req->x = coord.X;
1457 req->y = coord.Y;
1458 req->mode = CHAR_INFO_MODE_TEXT;
1459 req->wrap = TRUE;
1460 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1461 if ((ret = !wine_server_call_err( req )))
1463 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1466 SERVER_END_REQ;
1467 return ret;
1471 /******************************************************************************
1472 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1474 * PARAMS
1475 * title [I] Address of new title
1477 * RETURNS
1478 * Success: TRUE
1479 * Failure: FALSE
1481 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1483 BOOL ret;
1485 TRACE("(%s)\n", debugstr_w(title));
1486 SERVER_START_REQ( set_console_input_info )
1488 req->handle = 0;
1489 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1490 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1491 ret = !wine_server_call_err( req );
1493 SERVER_END_REQ;
1494 return ret;
1498 /***********************************************************************
1499 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1501 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1503 FIXME("(%p): stub\n", nrofbuttons);
1504 *nrofbuttons = 2;
1505 return TRUE;
1508 /******************************************************************************
1509 * SetConsoleInputExeNameW [KERNEL32.@]
1511 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1513 TRACE("(%s)\n", debugstr_w(name));
1515 if (!name || !name[0])
1517 SetLastError(ERROR_INVALID_PARAMETER);
1518 return FALSE;
1521 RtlEnterCriticalSection(&CONSOLE_CritSect);
1522 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1523 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1525 return TRUE;
1528 /******************************************************************************
1529 * SetConsoleInputExeNameA [KERNEL32.@]
1531 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1533 int len;
1534 LPWSTR nameW;
1535 BOOL ret;
1537 if (!name || !name[0])
1539 SetLastError(ERROR_INVALID_PARAMETER);
1540 return FALSE;
1543 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1544 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1546 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1547 ret = SetConsoleInputExeNameW(nameW);
1548 HeapFree(GetProcessHeap(), 0, nameW);
1550 return ret;
1553 /******************************************************************
1554 * CONSOLE_DefaultHandler
1556 * Final control event handler
1558 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1560 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1561 ExitProcess(0);
1562 /* should never go here */
1563 return TRUE;
1566 /******************************************************************************
1567 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1569 * PARAMS
1570 * func [I] Address of handler function
1571 * add [I] Handler to add or remove
1573 * RETURNS
1574 * Success: TRUE
1575 * Failure: FALSE
1578 struct ConsoleHandler
1580 PHANDLER_ROUTINE handler;
1581 struct ConsoleHandler* next;
1584 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1585 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1587 /*****************************************************************************/
1589 /******************************************************************
1590 * SetConsoleCtrlHandler (KERNEL32.@)
1592 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1594 BOOL ret = TRUE;
1596 TRACE("(%p,%i)\n", func, add);
1598 if (!func)
1600 RtlEnterCriticalSection(&CONSOLE_CritSect);
1601 if (add)
1602 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1603 else
1604 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1605 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1607 else if (add)
1609 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1611 if (!ch) return FALSE;
1612 ch->handler = func;
1613 RtlEnterCriticalSection(&CONSOLE_CritSect);
1614 ch->next = CONSOLE_Handlers;
1615 CONSOLE_Handlers = ch;
1616 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1618 else
1620 struct ConsoleHandler** ch;
1621 RtlEnterCriticalSection(&CONSOLE_CritSect);
1622 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1624 if ((*ch)->handler == func) break;
1626 if (*ch)
1628 struct ConsoleHandler* rch = *ch;
1630 /* sanity check */
1631 if (rch == &CONSOLE_DefaultConsoleHandler)
1633 ERR("Who's trying to remove default handler???\n");
1634 SetLastError(ERROR_INVALID_PARAMETER);
1635 ret = FALSE;
1637 else
1639 *ch = rch->next;
1640 HeapFree(GetProcessHeap(), 0, rch);
1643 else
1645 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1646 SetLastError(ERROR_INVALID_PARAMETER);
1647 ret = FALSE;
1649 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1651 return ret;
1654 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1656 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1657 return EXCEPTION_EXECUTE_HANDLER;
1660 /******************************************************************
1661 * CONSOLE_SendEventThread
1663 * Internal helper to pass an event to the list on installed handlers
1665 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1667 DWORD_PTR event = (DWORD_PTR)pmt;
1668 struct ConsoleHandler* ch;
1670 if (event == CTRL_C_EVENT)
1672 BOOL caught_by_dbg = TRUE;
1673 /* First, try to pass the ctrl-C event to the debugger (if any)
1674 * If it continues, there's nothing more to do
1675 * Otherwise, we need to send the ctrl-C event to the handlers
1677 __TRY
1679 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1681 __EXCEPT(CONSOLE_CtrlEventHandler)
1683 caught_by_dbg = FALSE;
1685 __ENDTRY;
1686 if (caught_by_dbg) return 0;
1687 /* the debugger didn't continue... so, pass to ctrl handlers */
1689 RtlEnterCriticalSection(&CONSOLE_CritSect);
1690 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1692 if (ch->handler(event)) break;
1694 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1695 return 1;
1698 /******************************************************************
1699 * CONSOLE_HandleCtrlC
1701 * Check whether the shall manipulate CtrlC events
1703 int CONSOLE_HandleCtrlC(unsigned sig)
1705 /* FIXME: better test whether a console is attached to this process ??? */
1706 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1707 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1709 /* check if we have to ignore ctrl-C events */
1710 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1712 /* Create a separate thread to signal all the events.
1713 * This is needed because:
1714 * - this function can be called in an Unix signal handler (hence on an
1715 * different stack than the thread that's running). This breaks the
1716 * Win32 exception mechanisms (where the thread's stack is checked).
1717 * - since the current thread, while processing the signal, can hold the
1718 * console critical section, we need another execution environment where
1719 * we can wait on this critical section
1721 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1723 return 1;
1726 /******************************************************************************
1727 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1729 * PARAMS
1730 * dwCtrlEvent [I] Type of event
1731 * dwProcessGroupID [I] Process group ID to send event to
1733 * RETURNS
1734 * Success: True
1735 * Failure: False (and *should* [but doesn't] set LastError)
1737 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1738 DWORD dwProcessGroupID)
1740 BOOL ret;
1742 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
1744 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1746 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
1747 return FALSE;
1750 SERVER_START_REQ( send_console_signal )
1752 req->signal = dwCtrlEvent;
1753 req->group_id = dwProcessGroupID;
1754 ret = !wine_server_call_err( req );
1756 SERVER_END_REQ;
1758 /* FIXME: Shall this function be synchronous, i.e., only return when all events
1759 * have been handled by all processes in the given group?
1760 * As of today, we don't wait...
1762 return ret;
1766 /******************************************************************************
1767 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
1769 * PARAMS
1770 * dwDesiredAccess [I] Access flag
1771 * dwShareMode [I] Buffer share mode
1772 * sa [I] Security attributes
1773 * dwFlags [I] Type of buffer to create
1774 * lpScreenBufferData [I] Reserved
1776 * NOTES
1777 * Should call SetLastError
1779 * RETURNS
1780 * Success: Handle to new console screen buffer
1781 * Failure: INVALID_HANDLE_VALUE
1783 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1784 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1785 LPVOID lpScreenBufferData)
1787 HANDLE ret = INVALID_HANDLE_VALUE;
1789 TRACE("(%d,%d,%p,%d,%p)\n",
1790 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1792 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1794 SetLastError(ERROR_INVALID_PARAMETER);
1795 return INVALID_HANDLE_VALUE;
1798 SERVER_START_REQ(create_console_output)
1800 req->handle_in = 0;
1801 req->access = dwDesiredAccess;
1802 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
1803 req->share = dwShareMode;
1804 if (!wine_server_call_err( req ))
1805 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
1807 SERVER_END_REQ;
1809 return ret;
1813 /***********************************************************************
1814 * GetConsoleScreenBufferInfo (KERNEL32.@)
1816 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1818 BOOL ret;
1820 SERVER_START_REQ(get_console_output_info)
1822 req->handle = console_handle_unmap(hConsoleOutput);
1823 if ((ret = !wine_server_call_err( req )))
1825 csbi->dwSize.X = reply->width;
1826 csbi->dwSize.Y = reply->height;
1827 csbi->dwCursorPosition.X = reply->cursor_x;
1828 csbi->dwCursorPosition.Y = reply->cursor_y;
1829 csbi->wAttributes = reply->attr;
1830 csbi->srWindow.Left = reply->win_left;
1831 csbi->srWindow.Right = reply->win_right;
1832 csbi->srWindow.Top = reply->win_top;
1833 csbi->srWindow.Bottom = reply->win_bottom;
1834 csbi->dwMaximumWindowSize.X = reply->max_width;
1835 csbi->dwMaximumWindowSize.Y = reply->max_height;
1838 SERVER_END_REQ;
1840 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
1841 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1842 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1843 csbi->wAttributes,
1844 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1845 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1847 return ret;
1851 /******************************************************************************
1852 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
1854 * RETURNS
1855 * Success: TRUE
1856 * Failure: FALSE
1858 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1860 BOOL ret;
1862 TRACE("(%p)\n", hConsoleOutput);
1864 SERVER_START_REQ( set_console_input_info )
1866 req->handle = 0;
1867 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1868 req->active_sb = wine_server_obj_handle( hConsoleOutput );
1869 ret = !wine_server_call_err( req );
1871 SERVER_END_REQ;
1872 return ret;
1876 /***********************************************************************
1877 * GetConsoleMode (KERNEL32.@)
1879 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1881 BOOL ret;
1883 SERVER_START_REQ(get_console_mode)
1885 req->handle = console_handle_unmap(hcon);
1886 ret = !wine_server_call_err( req );
1887 if (ret && mode) *mode = reply->mode;
1889 SERVER_END_REQ;
1890 return ret;
1894 /******************************************************************************
1895 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
1897 * PARAMS
1898 * hcon [I] Handle to console input or screen buffer
1899 * mode [I] Input or output mode to set
1901 * RETURNS
1902 * Success: TRUE
1903 * Failure: FALSE
1905 * mode:
1906 * ENABLE_PROCESSED_INPUT 0x01
1907 * ENABLE_LINE_INPUT 0x02
1908 * ENABLE_ECHO_INPUT 0x04
1909 * ENABLE_WINDOW_INPUT 0x08
1910 * ENABLE_MOUSE_INPUT 0x10
1912 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1914 BOOL ret;
1916 SERVER_START_REQ(set_console_mode)
1918 req->handle = console_handle_unmap(hcon);
1919 req->mode = mode;
1920 ret = !wine_server_call_err( req );
1922 SERVER_END_REQ;
1923 /* FIXME: when resetting a console input to editline mode, I think we should
1924 * empty the S_EditString buffer
1927 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
1929 return ret;
1933 /******************************************************************
1934 * CONSOLE_WriteChars
1936 * WriteConsoleOutput helper: hides server call semantics
1937 * writes a string at a given pos with standard attribute
1939 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1941 int written = -1;
1943 if (!nc) return 0;
1945 SERVER_START_REQ( write_console_output )
1947 req->handle = console_handle_unmap(hCon);
1948 req->x = pos->X;
1949 req->y = pos->Y;
1950 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1951 req->wrap = FALSE;
1952 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1953 if (!wine_server_call_err( req )) written = reply->written;
1955 SERVER_END_REQ;
1957 if (written > 0) pos->X += written;
1958 return written;
1961 /******************************************************************
1962 * next_line
1964 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1967 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1969 SMALL_RECT src;
1970 CHAR_INFO ci;
1971 COORD dst;
1973 csbi->dwCursorPosition.X = 0;
1974 csbi->dwCursorPosition.Y++;
1976 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1978 src.Top = 1;
1979 src.Bottom = csbi->dwSize.Y - 1;
1980 src.Left = 0;
1981 src.Right = csbi->dwSize.X - 1;
1983 dst.X = 0;
1984 dst.Y = 0;
1986 ci.Attributes = csbi->wAttributes;
1987 ci.Char.UnicodeChar = ' ';
1989 csbi->dwCursorPosition.Y--;
1990 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1991 return 0;
1992 return 1;
1995 /******************************************************************
1996 * write_block
1998 * WriteConsoleOutput helper: writes a block of non special characters
1999 * Block can spread on several lines, and wrapping, if needed, is
2000 * handled
2003 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2004 DWORD mode, LPCWSTR ptr, int len)
2006 int blk; /* number of chars to write on current line */
2007 int done; /* number of chars already written */
2009 if (len <= 0) return 1;
2011 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2013 for (done = 0; done < len; done += blk)
2015 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2017 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2018 return 0;
2019 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2020 return 0;
2023 else
2025 int pos = csbi->dwCursorPosition.X;
2026 /* FIXME: we could reduce the number of loops
2027 * but, in most cases we wouldn't gain lots of time (it would only
2028 * happen if we're asked to overwrite more than twice the part of the line,
2029 * which is unlikely
2031 for (blk = done = 0; done < len; done += blk)
2033 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2035 csbi->dwCursorPosition.X = pos;
2036 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2037 return 0;
2041 return 1;
2044 /***********************************************************************
2045 * WriteConsoleW (KERNEL32.@)
2047 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2048 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2050 DWORD mode;
2051 DWORD nw = 0;
2052 const WCHAR* psz = lpBuffer;
2053 CONSOLE_SCREEN_BUFFER_INFO csbi;
2054 int k, first = 0;
2056 TRACE("%p %s %d %p %p\n",
2057 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2058 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2060 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2062 if (!GetConsoleMode(hConsoleOutput, &mode) ||
2063 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2064 return FALSE;
2066 if (!nNumberOfCharsToWrite) return TRUE;
2068 if (mode & ENABLE_PROCESSED_OUTPUT)
2070 unsigned int i;
2072 for (i = 0; i < nNumberOfCharsToWrite; i++)
2074 switch (psz[i])
2076 case '\b': case '\t': case '\n': case '\a': case '\r':
2077 /* don't handle here the i-th char... done below */
2078 if ((k = i - first) > 0)
2080 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2081 goto the_end;
2082 nw += k;
2084 first = i + 1;
2085 nw++;
2087 switch (psz[i])
2089 case '\b':
2090 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2091 break;
2092 case '\t':
2094 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2096 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2097 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2098 goto the_end;
2100 break;
2101 case '\n':
2102 next_line(hConsoleOutput, &csbi);
2103 break;
2104 case '\a':
2105 Beep(400, 300);
2106 break;
2107 case '\r':
2108 csbi.dwCursorPosition.X = 0;
2109 break;
2110 default:
2111 break;
2116 /* write the remaining block (if any) if processed output is enabled, or the
2117 * entire buffer otherwise
2119 if ((k = nNumberOfCharsToWrite - first) > 0)
2121 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2122 goto the_end;
2123 nw += k;
2126 the_end:
2127 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2128 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2129 return nw != 0;
2133 /***********************************************************************
2134 * WriteConsoleA (KERNEL32.@)
2136 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2137 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2139 BOOL ret;
2140 LPWSTR xstring;
2141 DWORD n;
2143 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2145 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2146 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2147 if (!xstring) return 0;
2149 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2151 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2153 HeapFree(GetProcessHeap(), 0, xstring);
2155 return ret;
2158 /******************************************************************************
2159 * SetConsoleCursorPosition [KERNEL32.@]
2160 * Sets the cursor position in console
2162 * PARAMS
2163 * hConsoleOutput [I] Handle of console screen buffer
2164 * dwCursorPosition [I] New cursor position coordinates
2166 * RETURNS
2167 * Success: TRUE
2168 * Failure: FALSE
2170 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2172 BOOL ret;
2173 CONSOLE_SCREEN_BUFFER_INFO csbi;
2174 int do_move = 0;
2175 int w, h;
2177 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2179 SERVER_START_REQ(set_console_output_info)
2181 req->handle = console_handle_unmap(hcon);
2182 req->cursor_x = pos.X;
2183 req->cursor_y = pos.Y;
2184 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2185 ret = !wine_server_call_err( req );
2187 SERVER_END_REQ;
2189 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2190 return FALSE;
2192 /* if cursor is no longer visible, scroll the visible window... */
2193 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2194 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2195 if (pos.X < csbi.srWindow.Left)
2197 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2198 do_move++;
2200 else if (pos.X > csbi.srWindow.Right)
2202 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2203 do_move++;
2205 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2207 if (pos.Y < csbi.srWindow.Top)
2209 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2210 do_move++;
2212 else if (pos.Y > csbi.srWindow.Bottom)
2214 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2215 do_move++;
2217 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2219 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2221 return ret;
2224 /******************************************************************************
2225 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2227 * PARAMS
2228 * hcon [I] Handle to console screen buffer
2229 * cinfo [O] Address of cursor information
2231 * RETURNS
2232 * Success: TRUE
2233 * Failure: FALSE
2235 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2237 BOOL ret;
2239 SERVER_START_REQ(get_console_output_info)
2241 req->handle = console_handle_unmap(hCon);
2242 ret = !wine_server_call_err( req );
2243 if (ret && cinfo)
2245 cinfo->dwSize = reply->cursor_size;
2246 cinfo->bVisible = reply->cursor_visible;
2249 SERVER_END_REQ;
2251 if (!ret) return FALSE;
2253 if (!cinfo)
2255 SetLastError(ERROR_INVALID_ACCESS);
2256 ret = FALSE;
2258 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2260 return ret;
2264 /******************************************************************************
2265 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2267 * PARAMS
2268 * hcon [I] Handle to console screen buffer
2269 * cinfo [I] Address of cursor information
2270 * RETURNS
2271 * Success: TRUE
2272 * Failure: FALSE
2274 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2276 BOOL ret;
2278 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2279 SERVER_START_REQ(set_console_output_info)
2281 req->handle = console_handle_unmap(hCon);
2282 req->cursor_size = cinfo->dwSize;
2283 req->cursor_visible = cinfo->bVisible;
2284 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2285 ret = !wine_server_call_err( req );
2287 SERVER_END_REQ;
2288 return ret;
2292 /******************************************************************************
2293 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2295 * PARAMS
2296 * hcon [I] Handle to console screen buffer
2297 * bAbsolute [I] Coordinate type flag
2298 * window [I] Address of new window rectangle
2299 * RETURNS
2300 * Success: TRUE
2301 * Failure: FALSE
2303 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2305 SMALL_RECT p = *window;
2306 BOOL ret;
2308 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2310 if (!bAbsolute)
2312 CONSOLE_SCREEN_BUFFER_INFO csbi;
2314 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2315 return FALSE;
2316 p.Left += csbi.srWindow.Left;
2317 p.Top += csbi.srWindow.Top;
2318 p.Right += csbi.srWindow.Right;
2319 p.Bottom += csbi.srWindow.Bottom;
2321 SERVER_START_REQ(set_console_output_info)
2323 req->handle = console_handle_unmap(hCon);
2324 req->win_left = p.Left;
2325 req->win_top = p.Top;
2326 req->win_right = p.Right;
2327 req->win_bottom = p.Bottom;
2328 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2329 ret = !wine_server_call_err( req );
2331 SERVER_END_REQ;
2333 return ret;
2337 /******************************************************************************
2338 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2340 * Sets the foreground and background color attributes of characters
2341 * written to the screen buffer.
2343 * RETURNS
2344 * Success: TRUE
2345 * Failure: FALSE
2347 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2349 BOOL ret;
2351 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2352 SERVER_START_REQ(set_console_output_info)
2354 req->handle = console_handle_unmap(hConsoleOutput);
2355 req->attr = wAttr;
2356 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2357 ret = !wine_server_call_err( req );
2359 SERVER_END_REQ;
2360 return ret;
2364 /******************************************************************************
2365 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2367 * PARAMS
2368 * hConsoleOutput [I] Handle to console screen buffer
2369 * dwSize [I] New size in character rows and cols
2371 * RETURNS
2372 * Success: TRUE
2373 * Failure: FALSE
2375 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2377 BOOL ret;
2379 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2380 SERVER_START_REQ(set_console_output_info)
2382 req->handle = console_handle_unmap(hConsoleOutput);
2383 req->width = dwSize.X;
2384 req->height = dwSize.Y;
2385 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2386 ret = !wine_server_call_err( req );
2388 SERVER_END_REQ;
2389 return ret;
2393 /******************************************************************************
2394 * ScrollConsoleScreenBufferA [KERNEL32.@]
2397 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2398 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2399 LPCHAR_INFO lpFill)
2401 CHAR_INFO ciw;
2403 ciw.Attributes = lpFill->Attributes;
2404 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2406 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2407 dwDestOrigin, &ciw);
2410 /******************************************************************
2411 * CONSOLE_FillLineUniform
2413 * Helper function for ScrollConsoleScreenBufferW
2414 * Fills a part of a line with a constant character info
2416 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2418 SERVER_START_REQ( fill_console_output )
2420 req->handle = console_handle_unmap(hConsoleOutput);
2421 req->mode = CHAR_INFO_MODE_TEXTATTR;
2422 req->x = i;
2423 req->y = j;
2424 req->count = len;
2425 req->wrap = FALSE;
2426 req->data.ch = lpFill->Char.UnicodeChar;
2427 req->data.attr = lpFill->Attributes;
2428 wine_server_call_err( req );
2430 SERVER_END_REQ;
2433 /******************************************************************************
2434 * ScrollConsoleScreenBufferW [KERNEL32.@]
2438 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2439 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2440 LPCHAR_INFO lpFill)
2442 SMALL_RECT dst;
2443 DWORD ret;
2444 int i, j;
2445 int start = -1;
2446 SMALL_RECT clip;
2447 CONSOLE_SCREEN_BUFFER_INFO csbi;
2448 BOOL inside;
2449 COORD src;
2451 if (lpClipRect)
2452 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2453 lpScrollRect->Left, lpScrollRect->Top,
2454 lpScrollRect->Right, lpScrollRect->Bottom,
2455 lpClipRect->Left, lpClipRect->Top,
2456 lpClipRect->Right, lpClipRect->Bottom,
2457 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2458 else
2459 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2460 lpScrollRect->Left, lpScrollRect->Top,
2461 lpScrollRect->Right, lpScrollRect->Bottom,
2462 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2464 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2465 return FALSE;
2467 src.X = lpScrollRect->Left;
2468 src.Y = lpScrollRect->Top;
2470 /* step 1: get dst rect */
2471 dst.Left = dwDestOrigin.X;
2472 dst.Top = dwDestOrigin.Y;
2473 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2474 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2476 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2477 if (lpClipRect)
2479 clip.Left = max(0, lpClipRect->Left);
2480 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2481 clip.Top = max(0, lpClipRect->Top);
2482 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2484 else
2486 clip.Left = 0;
2487 clip.Right = csbi.dwSize.X - 1;
2488 clip.Top = 0;
2489 clip.Bottom = csbi.dwSize.Y - 1;
2491 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2493 /* step 2b: clip dst rect */
2494 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2495 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2496 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2497 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2499 /* step 3: transfer the bits */
2500 SERVER_START_REQ(move_console_output)
2502 req->handle = console_handle_unmap(hConsoleOutput);
2503 req->x_src = src.X;
2504 req->y_src = src.Y;
2505 req->x_dst = dst.Left;
2506 req->y_dst = dst.Top;
2507 req->w = dst.Right - dst.Left + 1;
2508 req->h = dst.Bottom - dst.Top + 1;
2509 ret = !wine_server_call_err( req );
2511 SERVER_END_REQ;
2513 if (!ret) return FALSE;
2515 /* step 4: clean out the exposed part */
2517 /* have to write cell [i,j] if it is not in dst rect (because it has already
2518 * been written to by the scroll) and is in clip (we shall not write
2519 * outside of clip)
2521 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2523 inside = dst.Top <= j && j <= dst.Bottom;
2524 start = -1;
2525 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2527 if (inside && dst.Left <= i && i <= dst.Right)
2529 if (start != -1)
2531 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2532 start = -1;
2535 else
2537 if (start == -1) start = i;
2540 if (start != -1)
2541 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2544 return TRUE;
2547 /******************************************************************
2548 * AttachConsole (KERNEL32.@)
2550 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2552 FIXME("stub %x\n",dwProcessId);
2553 return TRUE;
2556 /******************************************************************
2557 * GetConsoleDisplayMode (KERNEL32.@)
2559 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2561 TRACE("semi-stub: %p\n", lpModeFlags);
2562 /* It is safe to successfully report windowed mode */
2563 *lpModeFlags = 0;
2564 return TRUE;
2567 /******************************************************************
2568 * SetConsoleDisplayMode (KERNEL32.@)
2570 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2571 COORD *lpNewScreenBufferDimensions)
2573 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2574 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2575 if (dwFlags == 1)
2577 /* We cannot switch to fullscreen */
2578 return FALSE;
2580 return TRUE;
2584 /* ====================================================================
2586 * Console manipulation functions
2588 * ====================================================================*/
2590 /* some missing functions...
2591 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2592 * should get the right API and implement them
2593 * GetConsoleCommandHistory[AW] (dword dword dword)
2594 * GetConsoleCommandHistoryLength[AW]
2595 * SetConsoleCommandHistoryMode
2596 * SetConsoleNumberOfCommands[AW]
2598 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2600 int len = 0;
2602 SERVER_START_REQ( get_console_input_history )
2604 req->handle = 0;
2605 req->index = idx;
2606 if (buf && buf_len > 1)
2608 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2610 if (!wine_server_call_err( req ))
2612 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2613 len = reply->total / sizeof(WCHAR) + 1;
2616 SERVER_END_REQ;
2617 return len;
2620 /******************************************************************
2621 * CONSOLE_AppendHistory
2625 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2627 size_t len = strlenW(ptr);
2628 BOOL ret;
2630 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2631 if (!len) return FALSE;
2633 SERVER_START_REQ( append_console_input_history )
2635 req->handle = 0;
2636 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2637 ret = !wine_server_call_err( req );
2639 SERVER_END_REQ;
2640 return ret;
2643 /******************************************************************
2644 * CONSOLE_GetNumHistoryEntries
2648 unsigned CONSOLE_GetNumHistoryEntries(void)
2650 unsigned ret = -1;
2651 SERVER_START_REQ(get_console_input_info)
2653 req->handle = 0;
2654 if (!wine_server_call_err( req )) ret = reply->history_index;
2656 SERVER_END_REQ;
2657 return ret;
2660 /******************************************************************
2661 * CONSOLE_GetEditionMode
2665 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2667 unsigned ret = FALSE;
2668 SERVER_START_REQ(get_console_input_info)
2670 req->handle = console_handle_unmap(hConIn);
2671 if ((ret = !wine_server_call_err( req )))
2672 *mode = reply->edition_mode;
2674 SERVER_END_REQ;
2675 return ret;
2678 /******************************************************************
2679 * GetConsoleAliasW
2682 * RETURNS
2683 * 0 if an error occurred, non-zero for success
2686 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
2687 DWORD TargetBufferLength, LPWSTR lpExename)
2689 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
2690 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2691 return 0;
2694 /******************************************************************
2695 * GetConsoleProcessList (KERNEL32.@)
2697 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
2699 FIXME("(%p,%d): stub\n", processlist, processcount);
2701 if (!processlist || processcount < 1)
2703 SetLastError(ERROR_INVALID_PARAMETER);
2704 return 0;
2707 return 0;