msxml3: Add test to highlight another difference between XSLPattern and XPath.
[wine/hramrach.git] / dlls / kernel32 / console.c
blobf682ca1452f828173a4277e865bd5630707b6a3c
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 = INVALID_HANDLE_VALUE;
278 HANDLE ret;
280 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
282 if (name)
284 if (strcmpiW(coninW, name) == 0)
285 output = (HANDLE) FALSE;
286 else if (strcmpiW(conoutW, name) == 0)
287 output = (HANDLE) TRUE;
290 if (output == INVALID_HANDLE_VALUE)
292 SetLastError(ERROR_INVALID_PARAMETER);
293 return INVALID_HANDLE_VALUE;
295 else if (creation != OPEN_EXISTING)
297 if (!creation || creation == CREATE_NEW || creation == CREATE_ALWAYS)
298 SetLastError(ERROR_SHARING_VIOLATION);
299 else
300 SetLastError(ERROR_INVALID_PARAMETER);
301 return INVALID_HANDLE_VALUE;
304 SERVER_START_REQ( open_console )
306 req->from = wine_server_obj_handle( output );
307 req->access = access;
308 req->attributes = inherit ? OBJ_INHERIT : 0;
309 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
310 wine_server_call_err( req );
311 ret = wine_server_ptr_handle( reply->handle );
313 SERVER_END_REQ;
314 if (ret)
315 ret = console_handle_map(ret);
316 else
318 /* likely, we're not attached to wineconsole
319 * let's try to return a handle to the unix-console
321 int fd = open("/dev/tty", output ? O_WRONLY : O_RDONLY);
322 ret = INVALID_HANDLE_VALUE;
323 if (fd != -1)
325 DWORD access = (output ? GENERIC_WRITE : GENERIC_READ) | SYNCHRONIZE;
326 wine_server_fd_to_handle(fd, access, inherit ? OBJ_INHERIT : 0, &ret);
327 close(fd);
330 return ret;
333 /******************************************************************
334 * VerifyConsoleIoHandle (KERNEL32.@)
336 * Undocumented
338 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
340 BOOL ret;
342 if (!is_console_handle(handle)) return FALSE;
343 SERVER_START_REQ(get_console_mode)
345 req->handle = console_handle_unmap(handle);
346 ret = !wine_server_call_err( req );
348 SERVER_END_REQ;
349 return ret;
352 /******************************************************************
353 * DuplicateConsoleHandle (KERNEL32.@)
355 * Undocumented
357 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
358 DWORD options)
360 HANDLE ret;
362 if (!is_console_handle(handle) ||
363 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
364 GetCurrentProcess(), &ret, access, inherit, options))
365 return INVALID_HANDLE_VALUE;
366 return console_handle_map(ret);
369 /******************************************************************
370 * CloseConsoleHandle (KERNEL32.@)
372 * Undocumented
374 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
376 if (!is_console_handle(handle))
378 SetLastError(ERROR_INVALID_PARAMETER);
379 return FALSE;
381 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
384 /******************************************************************
385 * GetConsoleInputWaitHandle (KERNEL32.@)
387 * Undocumented
389 HANDLE WINAPI GetConsoleInputWaitHandle(void)
391 if (!console_wait_event)
393 SERVER_START_REQ(get_console_wait_event)
395 if (!wine_server_call_err( req ))
396 console_wait_event = wine_server_ptr_handle( reply->handle );
398 SERVER_END_REQ;
400 return console_wait_event;
404 /******************************************************************************
405 * WriteConsoleInputA [KERNEL32.@]
407 BOOL WINAPI WriteConsoleInputA( HANDLE handle, const INPUT_RECORD *buffer,
408 DWORD count, LPDWORD written )
410 INPUT_RECORD *recW;
411 BOOL ret;
413 if (!(recW = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*recW) ))) return FALSE;
414 memcpy( recW, buffer, count*sizeof(*recW) );
415 input_records_AtoW( recW, count );
416 ret = WriteConsoleInputW( handle, recW, count, written );
417 HeapFree( GetProcessHeap(), 0, recW );
418 return ret;
422 /******************************************************************************
423 * WriteConsoleInputW [KERNEL32.@]
425 BOOL WINAPI WriteConsoleInputW( HANDLE handle, const INPUT_RECORD *buffer,
426 DWORD count, LPDWORD written )
428 BOOL ret;
430 TRACE("(%p,%p,%d,%p)\n", handle, buffer, count, written);
432 if (written) *written = 0;
433 SERVER_START_REQ( write_console_input )
435 req->handle = console_handle_unmap(handle);
436 wine_server_add_data( req, buffer, count * sizeof(INPUT_RECORD) );
437 if ((ret = !wine_server_call_err( req )) && written)
438 *written = reply->written;
440 SERVER_END_REQ;
442 return ret;
446 /***********************************************************************
447 * WriteConsoleOutputA (KERNEL32.@)
449 BOOL WINAPI WriteConsoleOutputA( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
450 COORD size, COORD coord, LPSMALL_RECT region )
452 int y;
453 BOOL ret;
454 COORD new_size, new_coord;
455 CHAR_INFO *ciw;
457 new_size.X = min( region->Right - region->Left + 1, size.X - coord.X );
458 new_size.Y = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
460 if (new_size.X <= 0 || new_size.Y <= 0)
462 region->Bottom = region->Top + new_size.Y - 1;
463 region->Right = region->Left + new_size.X - 1;
464 return TRUE;
467 /* only copy the useful rectangle */
468 if (!(ciw = HeapAlloc( GetProcessHeap(), 0, sizeof(CHAR_INFO) * new_size.X * new_size.Y )))
469 return FALSE;
470 for (y = 0; y < new_size.Y; y++)
472 memcpy( &ciw[y * new_size.X], &lpBuffer[(y + coord.Y) * size.X + coord.X],
473 new_size.X * sizeof(CHAR_INFO) );
474 char_info_AtoW( &ciw[ y * new_size.X ], new_size.X );
476 new_coord.X = new_coord.Y = 0;
477 ret = WriteConsoleOutputW( hConsoleOutput, ciw, new_size, new_coord, region );
478 HeapFree( GetProcessHeap(), 0, ciw );
479 return ret;
483 /***********************************************************************
484 * WriteConsoleOutputW (KERNEL32.@)
486 BOOL WINAPI WriteConsoleOutputW( HANDLE hConsoleOutput, const CHAR_INFO *lpBuffer,
487 COORD size, COORD coord, LPSMALL_RECT region )
489 int width, height, y;
490 BOOL ret = TRUE;
492 TRACE("(%p,%p,(%d,%d),(%d,%d),(%d,%dx%d,%d)\n",
493 hConsoleOutput, lpBuffer, size.X, size.Y, coord.X, coord.Y,
494 region->Left, region->Top, region->Right, region->Bottom);
496 width = min( region->Right - region->Left + 1, size.X - coord.X );
497 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
499 if (width > 0 && height > 0)
501 for (y = 0; y < height; y++)
503 SERVER_START_REQ( write_console_output )
505 req->handle = console_handle_unmap(hConsoleOutput);
506 req->x = region->Left;
507 req->y = region->Top + y;
508 req->mode = CHAR_INFO_MODE_TEXTATTR;
509 req->wrap = FALSE;
510 wine_server_add_data( req, &lpBuffer[(y + coord.Y) * size.X + coord.X],
511 width * sizeof(CHAR_INFO));
512 if ((ret = !wine_server_call_err( req )))
514 width = min( width, reply->width - region->Left );
515 height = min( height, reply->height - region->Top );
518 SERVER_END_REQ;
519 if (!ret) break;
522 region->Bottom = region->Top + height - 1;
523 region->Right = region->Left + width - 1;
524 return ret;
528 /******************************************************************************
529 * WriteConsoleOutputCharacterA [KERNEL32.@]
531 * See WriteConsoleOutputCharacterW.
533 BOOL WINAPI WriteConsoleOutputCharacterA( HANDLE hConsoleOutput, LPCSTR str, DWORD length,
534 COORD coord, LPDWORD lpNumCharsWritten )
536 BOOL ret;
537 LPWSTR strW;
538 DWORD lenW;
540 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
541 debugstr_an(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
543 lenW = MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, NULL, 0 );
545 if (lpNumCharsWritten) *lpNumCharsWritten = 0;
547 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
548 MultiByteToWideChar( GetConsoleOutputCP(), 0, str, length, strW, lenW );
550 ret = WriteConsoleOutputCharacterW( hConsoleOutput, strW, lenW, coord, lpNumCharsWritten );
551 HeapFree( GetProcessHeap(), 0, strW );
552 return ret;
556 /******************************************************************************
557 * WriteConsoleOutputAttribute [KERNEL32.@] Sets attributes for some cells in
558 * the console screen buffer
560 * PARAMS
561 * hConsoleOutput [I] Handle to screen buffer
562 * attr [I] Pointer to buffer with write attributes
563 * length [I] Number of cells to write to
564 * coord [I] Coords of first cell
565 * lpNumAttrsWritten [O] Pointer to number of cells written
567 * RETURNS
568 * Success: TRUE
569 * Failure: FALSE
572 BOOL WINAPI WriteConsoleOutputAttribute( HANDLE hConsoleOutput, CONST WORD *attr, DWORD length,
573 COORD coord, LPDWORD lpNumAttrsWritten )
575 BOOL ret;
577 TRACE("(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput,attr,length,coord.X,coord.Y,lpNumAttrsWritten);
579 SERVER_START_REQ( write_console_output )
581 req->handle = console_handle_unmap(hConsoleOutput);
582 req->x = coord.X;
583 req->y = coord.Y;
584 req->mode = CHAR_INFO_MODE_ATTR;
585 req->wrap = TRUE;
586 wine_server_add_data( req, attr, length * sizeof(WORD) );
587 if ((ret = !wine_server_call_err( req )))
589 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
592 SERVER_END_REQ;
593 return ret;
597 /******************************************************************************
598 * FillConsoleOutputCharacterA [KERNEL32.@]
600 * See FillConsoleOutputCharacterW.
602 BOOL WINAPI FillConsoleOutputCharacterA( HANDLE hConsoleOutput, CHAR ch, DWORD length,
603 COORD coord, LPDWORD lpNumCharsWritten )
605 WCHAR wch;
607 MultiByteToWideChar( GetConsoleOutputCP(), 0, &ch, 1, &wch, 1 );
608 return FillConsoleOutputCharacterW(hConsoleOutput, wch, length, coord, lpNumCharsWritten);
612 /******************************************************************************
613 * FillConsoleOutputCharacterW [KERNEL32.@] Writes characters to console
615 * PARAMS
616 * hConsoleOutput [I] Handle to screen buffer
617 * ch [I] Character to write
618 * length [I] Number of cells to write to
619 * coord [I] Coords of first cell
620 * lpNumCharsWritten [O] Pointer to number of cells written
622 * RETURNS
623 * Success: TRUE
624 * Failure: FALSE
626 BOOL WINAPI FillConsoleOutputCharacterW( HANDLE hConsoleOutput, WCHAR ch, DWORD length,
627 COORD coord, LPDWORD lpNumCharsWritten)
629 BOOL ret;
631 TRACE("(%p,%s,%d,(%dx%d),%p)\n",
632 hConsoleOutput, debugstr_wn(&ch, 1), length, coord.X, coord.Y, lpNumCharsWritten);
634 SERVER_START_REQ( fill_console_output )
636 req->handle = console_handle_unmap(hConsoleOutput);
637 req->x = coord.X;
638 req->y = coord.Y;
639 req->mode = CHAR_INFO_MODE_TEXT;
640 req->wrap = TRUE;
641 req->data.ch = ch;
642 req->count = length;
643 if ((ret = !wine_server_call_err( req )))
645 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
648 SERVER_END_REQ;
649 return ret;
653 /******************************************************************************
654 * FillConsoleOutputAttribute [KERNEL32.@] Sets attributes for console
656 * PARAMS
657 * hConsoleOutput [I] Handle to screen buffer
658 * attr [I] Color attribute to write
659 * length [I] Number of cells to write to
660 * coord [I] Coords of first cell
661 * lpNumAttrsWritten [O] Pointer to number of cells written
663 * RETURNS
664 * Success: TRUE
665 * Failure: FALSE
667 BOOL WINAPI FillConsoleOutputAttribute( HANDLE hConsoleOutput, WORD attr, DWORD length,
668 COORD coord, LPDWORD lpNumAttrsWritten )
670 BOOL ret;
672 TRACE("(%p,%d,%d,(%dx%d),%p)\n",
673 hConsoleOutput, attr, length, coord.X, coord.Y, lpNumAttrsWritten);
675 SERVER_START_REQ( fill_console_output )
677 req->handle = console_handle_unmap(hConsoleOutput);
678 req->x = coord.X;
679 req->y = coord.Y;
680 req->mode = CHAR_INFO_MODE_ATTR;
681 req->wrap = TRUE;
682 req->data.attr = attr;
683 req->count = length;
684 if ((ret = !wine_server_call_err( req )))
686 if (lpNumAttrsWritten) *lpNumAttrsWritten = reply->written;
689 SERVER_END_REQ;
690 return ret;
694 /******************************************************************************
695 * ReadConsoleOutputCharacterA [KERNEL32.@]
698 BOOL WINAPI ReadConsoleOutputCharacterA(HANDLE hConsoleOutput, LPSTR lpstr, DWORD count,
699 COORD coord, LPDWORD read_count)
701 DWORD read;
702 BOOL ret;
703 LPWSTR wptr = HeapAlloc(GetProcessHeap(), 0, count * sizeof(WCHAR));
705 if (read_count) *read_count = 0;
706 if (!wptr) return FALSE;
708 if ((ret = ReadConsoleOutputCharacterW( hConsoleOutput, wptr, count, coord, &read )))
710 read = WideCharToMultiByte( GetConsoleOutputCP(), 0, wptr, read, lpstr, count, NULL, NULL);
711 if (read_count) *read_count = read;
713 HeapFree( GetProcessHeap(), 0, wptr );
714 return ret;
718 /******************************************************************************
719 * ReadConsoleOutputCharacterW [KERNEL32.@]
722 BOOL WINAPI ReadConsoleOutputCharacterW( HANDLE hConsoleOutput, LPWSTR buffer, DWORD count,
723 COORD coord, LPDWORD read_count )
725 BOOL ret;
727 TRACE( "(%p,%p,%d,%dx%d,%p)\n", hConsoleOutput, buffer, count, coord.X, coord.Y, read_count );
729 SERVER_START_REQ( read_console_output )
731 req->handle = console_handle_unmap(hConsoleOutput);
732 req->x = coord.X;
733 req->y = coord.Y;
734 req->mode = CHAR_INFO_MODE_TEXT;
735 req->wrap = TRUE;
736 wine_server_set_reply( req, buffer, count * sizeof(WCHAR) );
737 if ((ret = !wine_server_call_err( req )))
739 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WCHAR);
742 SERVER_END_REQ;
743 return ret;
747 /******************************************************************************
748 * ReadConsoleOutputAttribute [KERNEL32.@]
750 BOOL WINAPI ReadConsoleOutputAttribute(HANDLE hConsoleOutput, LPWORD lpAttribute, DWORD length,
751 COORD coord, LPDWORD read_count)
753 BOOL ret;
755 TRACE("(%p,%p,%d,%dx%d,%p)\n",
756 hConsoleOutput, lpAttribute, length, coord.X, coord.Y, read_count);
758 SERVER_START_REQ( read_console_output )
760 req->handle = console_handle_unmap(hConsoleOutput);
761 req->x = coord.X;
762 req->y = coord.Y;
763 req->mode = CHAR_INFO_MODE_ATTR;
764 req->wrap = TRUE;
765 wine_server_set_reply( req, lpAttribute, length * sizeof(WORD) );
766 if ((ret = !wine_server_call_err( req )))
768 if (read_count) *read_count = wine_server_reply_size(reply) / sizeof(WORD);
771 SERVER_END_REQ;
772 return ret;
776 /******************************************************************************
777 * ReadConsoleOutputA [KERNEL32.@]
780 BOOL WINAPI ReadConsoleOutputA( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
781 COORD coord, LPSMALL_RECT region )
783 BOOL ret;
784 int y;
786 ret = ReadConsoleOutputW( hConsoleOutput, lpBuffer, size, coord, region );
787 if (ret && region->Right >= region->Left)
789 for (y = 0; y <= region->Bottom - region->Top; y++)
791 char_info_WtoA( &lpBuffer[(coord.Y + y) * size.X + coord.X],
792 region->Right - region->Left + 1 );
795 return ret;
799 /******************************************************************************
800 * ReadConsoleOutputW [KERNEL32.@]
802 * NOTE: The NT4 (sp5) kernel crashes on me if size is (0,0). I don't
803 * think we need to be *that* compatible. -- AJ
805 BOOL WINAPI ReadConsoleOutputW( HANDLE hConsoleOutput, LPCHAR_INFO lpBuffer, COORD size,
806 COORD coord, LPSMALL_RECT region )
808 int width, height, y;
809 BOOL ret = TRUE;
811 width = min( region->Right - region->Left + 1, size.X - coord.X );
812 height = min( region->Bottom - region->Top + 1, size.Y - coord.Y );
814 if (width > 0 && height > 0)
816 for (y = 0; y < height; y++)
818 SERVER_START_REQ( read_console_output )
820 req->handle = console_handle_unmap(hConsoleOutput);
821 req->x = region->Left;
822 req->y = region->Top + y;
823 req->mode = CHAR_INFO_MODE_TEXTATTR;
824 req->wrap = FALSE;
825 wine_server_set_reply( req, &lpBuffer[(y+coord.Y) * size.X + coord.X],
826 width * sizeof(CHAR_INFO) );
827 if ((ret = !wine_server_call_err( req )))
829 width = min( width, reply->width - region->Left );
830 height = min( height, reply->height - region->Top );
833 SERVER_END_REQ;
834 if (!ret) break;
837 region->Bottom = region->Top + height - 1;
838 region->Right = region->Left + width - 1;
839 return ret;
843 /******************************************************************************
844 * ReadConsoleInputA [KERNEL32.@] Reads data from a console
846 * PARAMS
847 * handle [I] Handle to console input buffer
848 * buffer [O] Address of buffer for read data
849 * count [I] Number of records to read
850 * pRead [O] Address of number of records read
852 * RETURNS
853 * Success: TRUE
854 * Failure: FALSE
856 BOOL WINAPI ReadConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
858 DWORD read;
860 if (!ReadConsoleInputW( handle, buffer, count, &read )) return FALSE;
861 input_records_WtoA( buffer, read );
862 if (pRead) *pRead = read;
863 return TRUE;
867 /***********************************************************************
868 * PeekConsoleInputA (KERNEL32.@)
870 * Gets 'count' first events (or less) from input queue.
872 BOOL WINAPI PeekConsoleInputA( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD pRead )
874 DWORD read;
876 if (!PeekConsoleInputW( handle, buffer, count, &read )) return FALSE;
877 input_records_WtoA( buffer, read );
878 if (pRead) *pRead = read;
879 return TRUE;
883 /***********************************************************************
884 * PeekConsoleInputW (KERNEL32.@)
886 BOOL WINAPI PeekConsoleInputW( HANDLE handle, PINPUT_RECORD buffer, DWORD count, LPDWORD read )
888 BOOL ret;
889 SERVER_START_REQ( read_console_input )
891 req->handle = console_handle_unmap(handle);
892 req->flush = FALSE;
893 wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
894 if ((ret = !wine_server_call_err( req )))
896 if (read) *read = count ? reply->read : 0;
899 SERVER_END_REQ;
900 return ret;
904 /***********************************************************************
905 * GetNumberOfConsoleInputEvents (KERNEL32.@)
907 BOOL WINAPI GetNumberOfConsoleInputEvents( HANDLE handle, LPDWORD nrofevents )
909 BOOL ret;
910 SERVER_START_REQ( read_console_input )
912 req->handle = console_handle_unmap(handle);
913 req->flush = FALSE;
914 if ((ret = !wine_server_call_err( req )))
916 if (nrofevents) *nrofevents = reply->read;
919 SERVER_END_REQ;
920 return ret;
924 /******************************************************************************
925 * read_console_input
927 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
929 * Returns
930 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
932 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
933 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
935 enum read_console_input_return ret;
937 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
938 return rci_timeout;
939 SERVER_START_REQ( read_console_input )
941 req->handle = console_handle_unmap(handle);
942 req->flush = TRUE;
943 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
944 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
945 else ret = rci_gotone;
947 SERVER_END_REQ;
949 return ret;
953 /***********************************************************************
954 * FlushConsoleInputBuffer (KERNEL32.@)
956 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
958 enum read_console_input_return last;
959 INPUT_RECORD ir;
961 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
963 return last == rci_timeout;
967 /***********************************************************************
968 * SetConsoleTitleA (KERNEL32.@)
970 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
972 LPWSTR titleW;
973 BOOL ret;
975 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
976 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
977 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
978 ret = SetConsoleTitleW(titleW);
979 HeapFree(GetProcessHeap(), 0, titleW);
980 return ret;
984 /***********************************************************************
985 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
987 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
989 FIXME( "stub %p\n", layoutName);
990 return TRUE;
993 /***********************************************************************
994 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
996 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
998 FIXME( "stub %p\n", layoutName);
999 return TRUE;
1002 static WCHAR input_exe[MAX_PATH + 1];
1004 /***********************************************************************
1005 * GetConsoleInputExeNameW (KERNEL32.@)
1007 BOOL WINAPI GetConsoleInputExeNameW(DWORD buflen, LPWSTR buffer)
1009 TRACE("%u %p\n", buflen, buffer);
1011 RtlEnterCriticalSection(&CONSOLE_CritSect);
1012 if (buflen > strlenW(input_exe)) strcpyW(buffer, input_exe);
1013 else SetLastError(ERROR_BUFFER_OVERFLOW);
1014 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1016 return TRUE;
1019 /***********************************************************************
1020 * GetConsoleInputExeNameA (KERNEL32.@)
1022 BOOL WINAPI GetConsoleInputExeNameA(DWORD buflen, LPSTR buffer)
1024 TRACE("%u %p\n", buflen, buffer);
1026 RtlEnterCriticalSection(&CONSOLE_CritSect);
1027 if (WideCharToMultiByte(CP_ACP, 0, input_exe, -1, NULL, 0, NULL, NULL) <= buflen)
1028 WideCharToMultiByte(CP_ACP, 0, input_exe, -1, buffer, buflen, NULL, NULL);
1029 else SetLastError(ERROR_BUFFER_OVERFLOW);
1030 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1032 return TRUE;
1035 /***********************************************************************
1036 * GetConsoleTitleA (KERNEL32.@)
1038 * See GetConsoleTitleW.
1040 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
1042 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1043 DWORD ret;
1045 if (!ptr) return 0;
1046 ret = GetConsoleTitleW( ptr, size );
1047 if (ret)
1049 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
1050 ret = strlen(title);
1052 HeapFree(GetProcessHeap(), 0, ptr);
1053 return ret;
1057 /******************************************************************************
1058 * GetConsoleTitleW [KERNEL32.@] Retrieves title string for console
1060 * PARAMS
1061 * title [O] Address of buffer for title
1062 * size [I] Size of buffer
1064 * RETURNS
1065 * Success: Length of string copied
1066 * Failure: 0
1068 DWORD WINAPI GetConsoleTitleW(LPWSTR title, DWORD size)
1070 DWORD ret = 0;
1072 SERVER_START_REQ( get_console_input_info )
1074 req->handle = 0;
1075 wine_server_set_reply( req, title, (size-1) * sizeof(WCHAR) );
1076 if (!wine_server_call_err( req ))
1078 ret = wine_server_reply_size(reply) / sizeof(WCHAR);
1079 title[ret] = 0;
1082 SERVER_END_REQ;
1083 return ret;
1087 /***********************************************************************
1088 * GetLargestConsoleWindowSize (KERNEL32.@)
1090 * NOTE
1091 * This should return a COORD, but calling convention for returning
1092 * structures is different between Windows and gcc on i386.
1094 * VERSION: [i386]
1096 #ifdef __i386__
1097 #undef GetLargestConsoleWindowSize
1098 DWORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1100 union {
1101 COORD c;
1102 DWORD w;
1103 } x;
1104 x.c.X = 80;
1105 x.c.Y = 24;
1106 TRACE("(%p), returning %dx%d (%x)\n", hConsoleOutput, x.c.X, x.c.Y, x.w);
1107 return x.w;
1109 #endif /* defined(__i386__) */
1112 /***********************************************************************
1113 * GetLargestConsoleWindowSize (KERNEL32.@)
1115 * NOTE
1116 * This should return a COORD, but calling convention for returning
1117 * structures is different between Windows and gcc on i386.
1119 * VERSION: [!i386]
1121 #ifndef __i386__
1122 COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput)
1124 COORD c;
1125 c.X = 80;
1126 c.Y = 24;
1127 TRACE("(%p), returning %dx%d\n", hConsoleOutput, c.X, c.Y);
1128 return c;
1130 #endif /* defined(__i386__) */
1132 static WCHAR* S_EditString /* = NULL */;
1133 static unsigned S_EditStrPos /* = 0 */;
1135 /***********************************************************************
1136 * FreeConsole (KERNEL32.@)
1138 BOOL WINAPI FreeConsole(VOID)
1140 BOOL ret;
1142 /* invalidate local copy of input event handle */
1143 console_wait_event = 0;
1145 SERVER_START_REQ(free_console)
1147 ret = !wine_server_call_err( req );
1149 SERVER_END_REQ;
1150 return ret;
1153 /******************************************************************
1154 * start_console_renderer
1156 * helper for AllocConsole
1157 * starts the renderer process
1159 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
1160 HANDLE hEvent)
1162 char buffer[1024];
1163 int ret;
1164 PROCESS_INFORMATION pi;
1166 /* FIXME: use dynamic allocation for most of the buffers below */
1167 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
1168 if ((ret > -1) && (ret < sizeof(buffer)) &&
1169 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
1170 NULL, NULL, si, &pi))
1172 HANDLE wh[2];
1173 DWORD ret;
1175 wh[0] = hEvent;
1176 wh[1] = pi.hProcess;
1177 ret = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
1179 CloseHandle(pi.hThread);
1180 CloseHandle(pi.hProcess);
1182 if (ret != WAIT_OBJECT_0) return FALSE;
1184 TRACE("Started wineconsole pid=%08x tid=%08x\n",
1185 pi.dwProcessId, pi.dwThreadId);
1187 return TRUE;
1189 return FALSE;
1192 static BOOL start_console_renderer(STARTUPINFOA* si)
1194 HANDLE hEvent = 0;
1195 LPSTR p;
1196 OBJECT_ATTRIBUTES attr;
1197 BOOL ret = FALSE;
1199 attr.Length = sizeof(attr);
1200 attr.RootDirectory = 0;
1201 attr.Attributes = OBJ_INHERIT;
1202 attr.ObjectName = NULL;
1203 attr.SecurityDescriptor = NULL;
1204 attr.SecurityQualityOfService = NULL;
1206 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
1207 if (!hEvent) return FALSE;
1209 /* first try environment variable */
1210 if ((p = getenv("WINECONSOLE")) != NULL)
1212 ret = start_console_renderer_helper(p, si, hEvent);
1213 if (!ret)
1214 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
1215 "trying default access\n", p);
1218 /* then try the regular PATH */
1219 if (!ret)
1220 ret = start_console_renderer_helper("wineconsole", si, hEvent);
1222 CloseHandle(hEvent);
1223 return ret;
1226 /***********************************************************************
1227 * AllocConsole (KERNEL32.@)
1229 * creates an xterm with a pty to our program
1231 BOOL WINAPI AllocConsole(void)
1233 HANDLE handle_in = INVALID_HANDLE_VALUE;
1234 HANDLE handle_out = INVALID_HANDLE_VALUE;
1235 HANDLE handle_err = INVALID_HANDLE_VALUE;
1236 STARTUPINFOA siCurrent;
1237 STARTUPINFOA siConsole;
1238 char buffer[1024];
1240 TRACE("()\n");
1242 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1243 FALSE, OPEN_EXISTING );
1245 if (VerifyConsoleIoHandle(handle_in))
1247 /* we already have a console opened on this process, don't create a new one */
1248 CloseHandle(handle_in);
1249 return FALSE;
1251 /* happens when we're running on a Unix console */
1252 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1254 /* invalidate local copy of input event handle */
1255 console_wait_event = 0;
1257 GetStartupInfoA(&siCurrent);
1259 memset(&siConsole, 0, sizeof(siConsole));
1260 siConsole.cb = sizeof(siConsole);
1261 /* setup a view arguments for wineconsole (it'll use them as default values) */
1262 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
1264 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
1265 siConsole.dwXCountChars = siCurrent.dwXCountChars;
1266 siConsole.dwYCountChars = siCurrent.dwYCountChars;
1268 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
1270 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
1271 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
1273 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
1275 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
1276 siConsole.wShowWindow = siCurrent.wShowWindow;
1278 /* FIXME (should pass the unicode form) */
1279 if (siCurrent.lpTitle)
1280 siConsole.lpTitle = siCurrent.lpTitle;
1281 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
1283 buffer[sizeof(buffer) - 1] = '\0';
1284 siConsole.lpTitle = buffer;
1287 if (!start_console_renderer(&siConsole))
1288 goto the_end;
1290 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
1291 /* all std I/O handles are inheritable by default */
1292 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
1293 TRUE, OPEN_EXISTING );
1294 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
1296 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
1297 TRUE, OPEN_EXISTING );
1298 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
1300 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
1301 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
1302 goto the_end;
1303 } else {
1304 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
1305 handle_in = siCurrent.hStdInput;
1306 handle_out = siCurrent.hStdOutput;
1307 handle_err = siCurrent.hStdError;
1310 /* NT resets the STD_*_HANDLEs on console alloc */
1311 SetStdHandle(STD_INPUT_HANDLE, handle_in);
1312 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
1313 SetStdHandle(STD_ERROR_HANDLE, handle_err);
1315 SetLastError(ERROR_SUCCESS);
1317 return TRUE;
1319 the_end:
1320 ERR("Can't allocate console\n");
1321 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
1322 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
1323 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
1324 FreeConsole();
1325 return FALSE;
1329 /***********************************************************************
1330 * ReadConsoleA (KERNEL32.@)
1332 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
1333 LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1335 LPWSTR ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
1336 DWORD ncr = 0;
1337 BOOL ret;
1339 if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, NULL)))
1340 ncr = WideCharToMultiByte(GetConsoleCP(), 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
1342 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
1343 HeapFree(GetProcessHeap(), 0, ptr);
1345 return ret;
1348 /***********************************************************************
1349 * ReadConsoleW (KERNEL32.@)
1351 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
1352 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
1354 DWORD charsread;
1355 LPWSTR xbuf = lpBuffer;
1356 DWORD mode;
1358 TRACE("(%p,%p,%d,%p,%p)\n",
1359 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
1361 if (!GetConsoleMode(hConsoleInput, &mode))
1362 return FALSE;
1364 if (mode & ENABLE_LINE_INPUT)
1366 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
1368 HeapFree(GetProcessHeap(), 0, S_EditString);
1369 if (!(S_EditString = CONSOLE_Readline(hConsoleInput)))
1370 return FALSE;
1371 S_EditStrPos = 0;
1373 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
1374 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
1375 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
1376 S_EditStrPos += charsread;
1378 else
1380 INPUT_RECORD ir;
1381 DWORD timeout = INFINITE;
1383 /* FIXME: should we read at least 1 char? The SDK does not say */
1384 /* wait for at least one available input record (it doesn't mean we'll have
1385 * chars stored in xbuf...)
1387 * Although SDK doc keeps silence about 1 char, SDK examples assume
1388 * that we should wait for at least one character (not key). --KS
1390 charsread = 0;
1393 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
1394 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
1395 ir.Event.KeyEvent.uChar.UnicodeChar)
1397 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
1398 timeout = 0;
1400 } while (charsread < nNumberOfCharsToRead);
1401 /* nothing has been read */
1402 if (timeout == INFINITE) return FALSE;
1405 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
1407 return TRUE;
1411 /***********************************************************************
1412 * ReadConsoleInputW (KERNEL32.@)
1414 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
1415 DWORD nLength, LPDWORD lpNumberOfEventsRead)
1417 DWORD idx = 0;
1418 DWORD timeout = INFINITE;
1420 if (!nLength)
1422 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
1423 return TRUE;
1426 /* loop until we get at least one event */
1427 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
1428 ++idx < nLength)
1429 timeout = 0;
1431 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
1432 return idx != 0;
1436 /******************************************************************************
1437 * WriteConsoleOutputCharacterW [KERNEL32.@]
1439 * Copy character to consecutive cells in the console screen buffer.
1441 * PARAMS
1442 * hConsoleOutput [I] Handle to screen buffer
1443 * str [I] Pointer to buffer with chars to write
1444 * length [I] Number of cells to write to
1445 * coord [I] Coords of first cell
1446 * lpNumCharsWritten [O] Pointer to number of cells written
1448 * RETURNS
1449 * Success: TRUE
1450 * Failure: FALSE
1453 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
1454 COORD coord, LPDWORD lpNumCharsWritten )
1456 BOOL ret;
1458 TRACE("(%p,%s,%d,%dx%d,%p)\n", hConsoleOutput,
1459 debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
1461 SERVER_START_REQ( write_console_output )
1463 req->handle = console_handle_unmap(hConsoleOutput);
1464 req->x = coord.X;
1465 req->y = coord.Y;
1466 req->mode = CHAR_INFO_MODE_TEXT;
1467 req->wrap = TRUE;
1468 wine_server_add_data( req, str, length * sizeof(WCHAR) );
1469 if ((ret = !wine_server_call_err( req )))
1471 if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
1474 SERVER_END_REQ;
1475 return ret;
1479 /******************************************************************************
1480 * SetConsoleTitleW [KERNEL32.@] Sets title bar string for console
1482 * PARAMS
1483 * title [I] Address of new title
1485 * RETURNS
1486 * Success: TRUE
1487 * Failure: FALSE
1489 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
1491 BOOL ret;
1493 TRACE("(%s)\n", debugstr_w(title));
1494 SERVER_START_REQ( set_console_input_info )
1496 req->handle = 0;
1497 req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
1498 wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
1499 ret = !wine_server_call_err( req );
1501 SERVER_END_REQ;
1502 return ret;
1506 /***********************************************************************
1507 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
1509 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
1511 FIXME("(%p): stub\n", nrofbuttons);
1512 *nrofbuttons = 2;
1513 return TRUE;
1516 /******************************************************************************
1517 * SetConsoleInputExeNameW [KERNEL32.@]
1519 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
1521 TRACE("(%s)\n", debugstr_w(name));
1523 if (!name || !name[0])
1525 SetLastError(ERROR_INVALID_PARAMETER);
1526 return FALSE;
1529 RtlEnterCriticalSection(&CONSOLE_CritSect);
1530 if (strlenW(name) < sizeof(input_exe)/sizeof(WCHAR)) strcpyW(input_exe, name);
1531 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1533 return TRUE;
1536 /******************************************************************************
1537 * SetConsoleInputExeNameA [KERNEL32.@]
1539 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
1541 int len;
1542 LPWSTR nameW;
1543 BOOL ret;
1545 if (!name || !name[0])
1547 SetLastError(ERROR_INVALID_PARAMETER);
1548 return FALSE;
1551 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
1552 if (!(nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
1554 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
1555 ret = SetConsoleInputExeNameW(nameW);
1556 HeapFree(GetProcessHeap(), 0, nameW);
1558 return ret;
1561 /******************************************************************
1562 * CONSOLE_DefaultHandler
1564 * Final control event handler
1566 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
1568 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
1569 ExitProcess(0);
1570 /* should never go here */
1571 return TRUE;
1574 /******************************************************************************
1575 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
1577 * PARAMS
1578 * func [I] Address of handler function
1579 * add [I] Handler to add or remove
1581 * RETURNS
1582 * Success: TRUE
1583 * Failure: FALSE
1586 struct ConsoleHandler
1588 PHANDLER_ROUTINE handler;
1589 struct ConsoleHandler* next;
1592 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
1593 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
1595 /*****************************************************************************/
1597 /******************************************************************
1598 * SetConsoleCtrlHandler (KERNEL32.@)
1600 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
1602 BOOL ret = TRUE;
1604 TRACE("(%p,%i)\n", func, add);
1606 if (!func)
1608 RtlEnterCriticalSection(&CONSOLE_CritSect);
1609 if (add)
1610 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
1611 else
1612 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
1613 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1615 else if (add)
1617 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
1619 if (!ch) return FALSE;
1620 ch->handler = func;
1621 RtlEnterCriticalSection(&CONSOLE_CritSect);
1622 ch->next = CONSOLE_Handlers;
1623 CONSOLE_Handlers = ch;
1624 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1626 else
1628 struct ConsoleHandler** ch;
1629 RtlEnterCriticalSection(&CONSOLE_CritSect);
1630 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
1632 if ((*ch)->handler == func) break;
1634 if (*ch)
1636 struct ConsoleHandler* rch = *ch;
1638 /* sanity check */
1639 if (rch == &CONSOLE_DefaultConsoleHandler)
1641 ERR("Who's trying to remove default handler???\n");
1642 SetLastError(ERROR_INVALID_PARAMETER);
1643 ret = FALSE;
1645 else
1647 *ch = rch->next;
1648 HeapFree(GetProcessHeap(), 0, rch);
1651 else
1653 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
1654 SetLastError(ERROR_INVALID_PARAMETER);
1655 ret = FALSE;
1657 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1659 return ret;
1662 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
1664 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
1665 return EXCEPTION_EXECUTE_HANDLER;
1668 /******************************************************************
1669 * CONSOLE_SendEventThread
1671 * Internal helper to pass an event to the list on installed handlers
1673 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1675 DWORD_PTR event = (DWORD_PTR)pmt;
1676 struct ConsoleHandler* ch;
1678 if (event == CTRL_C_EVENT)
1680 BOOL caught_by_dbg = TRUE;
1681 /* First, try to pass the ctrl-C event to the debugger (if any)
1682 * If it continues, there's nothing more to do
1683 * Otherwise, we need to send the ctrl-C event to the handlers
1685 __TRY
1687 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1689 __EXCEPT(CONSOLE_CtrlEventHandler)
1691 caught_by_dbg = FALSE;
1693 __ENDTRY;
1694 if (caught_by_dbg) return 0;
1695 /* the debugger didn't continue... so, pass to ctrl handlers */
1697 RtlEnterCriticalSection(&CONSOLE_CritSect);
1698 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1700 if (ch->handler(event)) break;
1702 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1703 return 1;
1706 /******************************************************************
1707 * CONSOLE_HandleCtrlC
1709 * Check whether the shall manipulate CtrlC events
1711 int CONSOLE_HandleCtrlC(unsigned sig)
1713 /* FIXME: better test whether a console is attached to this process ??? */
1714 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1715 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1717 /* check if we have to ignore ctrl-C events */
1718 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1720 /* Create a separate thread to signal all the events.
1721 * This is needed because:
1722 * - this function can be called in an Unix signal handler (hence on an
1723 * different stack than the thread that's running). This breaks the
1724 * Win32 exception mechanisms (where the thread's stack is checked).
1725 * - since the current thread, while processing the signal, can hold the
1726 * console critical section, we need another execution environment where
1727 * we can wait on this critical section
1729 CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1731 return 1;
1734 /******************************************************************************
1735 * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
1737 * PARAMS
1738 * dwCtrlEvent [I] Type of event
1739 * dwProcessGroupID [I] Process group ID to send event to
1741 * RETURNS
1742 * Success: True
1743 * Failure: False (and *should* [but doesn't] set LastError)
1745 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
1746 DWORD dwProcessGroupID)
1748 BOOL ret;
1750 TRACE("(%d, %d)\n", dwCtrlEvent, dwProcessGroupID);
1752 if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
1754 ERR("Invalid event %d for PGID %d\n", dwCtrlEvent, dwProcessGroupID);
1755 return FALSE;
1758 SERVER_START_REQ( send_console_signal )
1760 req->signal = dwCtrlEvent;
1761 req->group_id = dwProcessGroupID;
1762 ret = !wine_server_call_err( req );
1764 SERVER_END_REQ;
1766 /* FIXME: Shall this function be synchronous, i.e., only return when all events
1767 * have been handled by all processes in the given group?
1768 * As of today, we don't wait...
1770 return ret;
1774 /******************************************************************************
1775 * CreateConsoleScreenBuffer [KERNEL32.@] Creates a console screen buffer
1777 * PARAMS
1778 * dwDesiredAccess [I] Access flag
1779 * dwShareMode [I] Buffer share mode
1780 * sa [I] Security attributes
1781 * dwFlags [I] Type of buffer to create
1782 * lpScreenBufferData [I] Reserved
1784 * NOTES
1785 * Should call SetLastError
1787 * RETURNS
1788 * Success: Handle to new console screen buffer
1789 * Failure: INVALID_HANDLE_VALUE
1791 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode,
1792 LPSECURITY_ATTRIBUTES sa, DWORD dwFlags,
1793 LPVOID lpScreenBufferData)
1795 HANDLE ret = INVALID_HANDLE_VALUE;
1797 TRACE("(%d,%d,%p,%d,%p)\n",
1798 dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
1800 if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
1802 SetLastError(ERROR_INVALID_PARAMETER);
1803 return INVALID_HANDLE_VALUE;
1806 SERVER_START_REQ(create_console_output)
1808 req->handle_in = 0;
1809 req->access = dwDesiredAccess;
1810 req->attributes = (sa && sa->bInheritHandle) ? OBJ_INHERIT : 0;
1811 req->share = dwShareMode;
1812 if (!wine_server_call_err( req ))
1813 ret = console_handle_map( wine_server_ptr_handle( reply->handle_out ));
1815 SERVER_END_REQ;
1817 return ret;
1821 /***********************************************************************
1822 * GetConsoleScreenBufferInfo (KERNEL32.@)
1824 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
1826 BOOL ret;
1828 SERVER_START_REQ(get_console_output_info)
1830 req->handle = console_handle_unmap(hConsoleOutput);
1831 if ((ret = !wine_server_call_err( req )))
1833 csbi->dwSize.X = reply->width;
1834 csbi->dwSize.Y = reply->height;
1835 csbi->dwCursorPosition.X = reply->cursor_x;
1836 csbi->dwCursorPosition.Y = reply->cursor_y;
1837 csbi->wAttributes = reply->attr;
1838 csbi->srWindow.Left = reply->win_left;
1839 csbi->srWindow.Right = reply->win_right;
1840 csbi->srWindow.Top = reply->win_top;
1841 csbi->srWindow.Bottom = reply->win_bottom;
1842 csbi->dwMaximumWindowSize.X = reply->max_width;
1843 csbi->dwMaximumWindowSize.Y = reply->max_height;
1846 SERVER_END_REQ;
1848 TRACE("(%p,(%d,%d) (%d,%d) %d (%d,%d-%d,%d) (%d,%d)\n",
1849 hConsoleOutput, csbi->dwSize.X, csbi->dwSize.Y,
1850 csbi->dwCursorPosition.X, csbi->dwCursorPosition.Y,
1851 csbi->wAttributes,
1852 csbi->srWindow.Left, csbi->srWindow.Top, csbi->srWindow.Right, csbi->srWindow.Bottom,
1853 csbi->dwMaximumWindowSize.X, csbi->dwMaximumWindowSize.Y);
1855 return ret;
1859 /******************************************************************************
1860 * SetConsoleActiveScreenBuffer [KERNEL32.@] Sets buffer to current console
1862 * RETURNS
1863 * Success: TRUE
1864 * Failure: FALSE
1866 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
1868 BOOL ret;
1870 TRACE("(%p)\n", hConsoleOutput);
1872 SERVER_START_REQ( set_console_input_info )
1874 req->handle = 0;
1875 req->mask = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
1876 req->active_sb = wine_server_obj_handle( hConsoleOutput );
1877 ret = !wine_server_call_err( req );
1879 SERVER_END_REQ;
1880 return ret;
1884 /***********************************************************************
1885 * GetConsoleMode (KERNEL32.@)
1887 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
1889 BOOL ret;
1891 SERVER_START_REQ(get_console_mode)
1893 req->handle = console_handle_unmap(hcon);
1894 ret = !wine_server_call_err( req );
1895 if (ret && mode) *mode = reply->mode;
1897 SERVER_END_REQ;
1898 return ret;
1902 /******************************************************************************
1903 * SetConsoleMode [KERNEL32.@] Sets input mode of console's input buffer
1905 * PARAMS
1906 * hcon [I] Handle to console input or screen buffer
1907 * mode [I] Input or output mode to set
1909 * RETURNS
1910 * Success: TRUE
1911 * Failure: FALSE
1913 * mode:
1914 * ENABLE_PROCESSED_INPUT 0x01
1915 * ENABLE_LINE_INPUT 0x02
1916 * ENABLE_ECHO_INPUT 0x04
1917 * ENABLE_WINDOW_INPUT 0x08
1918 * ENABLE_MOUSE_INPUT 0x10
1920 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
1922 BOOL ret;
1924 SERVER_START_REQ(set_console_mode)
1926 req->handle = console_handle_unmap(hcon);
1927 req->mode = mode;
1928 ret = !wine_server_call_err( req );
1930 SERVER_END_REQ;
1931 /* FIXME: when resetting a console input to editline mode, I think we should
1932 * empty the S_EditString buffer
1935 TRACE("(%p,%x) retval == %d\n", hcon, mode, ret);
1937 return ret;
1941 /******************************************************************
1942 * CONSOLE_WriteChars
1944 * WriteConsoleOutput helper: hides server call semantics
1945 * writes a string at a given pos with standard attribute
1947 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1949 int written = -1;
1951 if (!nc) return 0;
1953 SERVER_START_REQ( write_console_output )
1955 req->handle = console_handle_unmap(hCon);
1956 req->x = pos->X;
1957 req->y = pos->Y;
1958 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1959 req->wrap = FALSE;
1960 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1961 if (!wine_server_call_err( req )) written = reply->written;
1963 SERVER_END_REQ;
1965 if (written > 0) pos->X += written;
1966 return written;
1969 /******************************************************************
1970 * next_line
1972 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1975 static int next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1977 SMALL_RECT src;
1978 CHAR_INFO ci;
1979 COORD dst;
1981 csbi->dwCursorPosition.X = 0;
1982 csbi->dwCursorPosition.Y++;
1984 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
1986 src.Top = 1;
1987 src.Bottom = csbi->dwSize.Y - 1;
1988 src.Left = 0;
1989 src.Right = csbi->dwSize.X - 1;
1991 dst.X = 0;
1992 dst.Y = 0;
1994 ci.Attributes = csbi->wAttributes;
1995 ci.Char.UnicodeChar = ' ';
1997 csbi->dwCursorPosition.Y--;
1998 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1999 return 0;
2000 return 1;
2003 /******************************************************************
2004 * write_block
2006 * WriteConsoleOutput helper: writes a block of non special characters
2007 * Block can spread on several lines, and wrapping, if needed, is
2008 * handled
2011 static int write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
2012 DWORD mode, LPCWSTR ptr, int len)
2014 int blk; /* number of chars to write on current line */
2015 int done; /* number of chars already written */
2017 if (len <= 0) return 1;
2019 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
2021 for (done = 0; done < len; done += blk)
2023 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2025 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2026 return 0;
2027 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
2028 return 0;
2031 else
2033 int pos = csbi->dwCursorPosition.X;
2034 /* FIXME: we could reduce the number of loops
2035 * but, in most cases we wouldn't gain lots of time (it would only
2036 * happen if we're asked to overwrite more than twice the part of the line,
2037 * which is unlikely
2039 for (blk = done = 0; done < len; done += blk)
2041 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
2043 csbi->dwCursorPosition.X = pos;
2044 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
2045 return 0;
2049 return 1;
2052 /***********************************************************************
2053 * WriteConsoleW (KERNEL32.@)
2055 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2056 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2058 DWORD mode;
2059 DWORD nw = 0;
2060 const WCHAR* psz = lpBuffer;
2061 CONSOLE_SCREEN_BUFFER_INFO csbi;
2062 int k, first = 0;
2064 TRACE("%p %s %d %p %p\n",
2065 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
2066 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
2068 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2070 if (!GetConsoleMode(hConsoleOutput, &mode) ||
2071 !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2072 return FALSE;
2074 if (!nNumberOfCharsToWrite) return TRUE;
2076 if (mode & ENABLE_PROCESSED_OUTPUT)
2078 unsigned int i;
2080 for (i = 0; i < nNumberOfCharsToWrite; i++)
2082 switch (psz[i])
2084 case '\b': case '\t': case '\n': case '\a': case '\r':
2085 /* don't handle here the i-th char... done below */
2086 if ((k = i - first) > 0)
2088 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2089 goto the_end;
2090 nw += k;
2092 first = i + 1;
2093 nw++;
2095 switch (psz[i])
2097 case '\b':
2098 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
2099 break;
2100 case '\t':
2102 WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
2104 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
2105 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
2106 goto the_end;
2108 break;
2109 case '\n':
2110 next_line(hConsoleOutput, &csbi);
2111 break;
2112 case '\a':
2113 Beep(400, 300);
2114 break;
2115 case '\r':
2116 csbi.dwCursorPosition.X = 0;
2117 break;
2118 default:
2119 break;
2124 /* write the remaining block (if any) if processed output is enabled, or the
2125 * entire buffer otherwise
2127 if ((k = nNumberOfCharsToWrite - first) > 0)
2129 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
2130 goto the_end;
2131 nw += k;
2134 the_end:
2135 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
2136 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
2137 return nw != 0;
2141 /***********************************************************************
2142 * WriteConsoleA (KERNEL32.@)
2144 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
2145 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
2147 BOOL ret;
2148 LPWSTR xstring;
2149 DWORD n;
2151 n = MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
2153 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
2154 xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
2155 if (!xstring) return 0;
2157 MultiByteToWideChar(GetConsoleOutputCP(), 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
2159 ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
2161 HeapFree(GetProcessHeap(), 0, xstring);
2163 return ret;
2166 /******************************************************************************
2167 * SetConsoleCursorPosition [KERNEL32.@]
2168 * Sets the cursor position in console
2170 * PARAMS
2171 * hConsoleOutput [I] Handle of console screen buffer
2172 * dwCursorPosition [I] New cursor position coordinates
2174 * RETURNS
2175 * Success: TRUE
2176 * Failure: FALSE
2178 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
2180 BOOL ret;
2181 CONSOLE_SCREEN_BUFFER_INFO csbi;
2182 int do_move = 0;
2183 int w, h;
2185 TRACE("%p %d %d\n", hcon, pos.X, pos.Y);
2187 SERVER_START_REQ(set_console_output_info)
2189 req->handle = console_handle_unmap(hcon);
2190 req->cursor_x = pos.X;
2191 req->cursor_y = pos.Y;
2192 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
2193 ret = !wine_server_call_err( req );
2195 SERVER_END_REQ;
2197 if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
2198 return FALSE;
2200 /* if cursor is no longer visible, scroll the visible window... */
2201 w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2202 h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2203 if (pos.X < csbi.srWindow.Left)
2205 csbi.srWindow.Left = min(pos.X, csbi.dwSize.X - w);
2206 do_move++;
2208 else if (pos.X > csbi.srWindow.Right)
2210 csbi.srWindow.Left = max(pos.X, w) - w + 1;
2211 do_move++;
2213 csbi.srWindow.Right = csbi.srWindow.Left + w - 1;
2215 if (pos.Y < csbi.srWindow.Top)
2217 csbi.srWindow.Top = min(pos.Y, csbi.dwSize.Y - h);
2218 do_move++;
2220 else if (pos.Y > csbi.srWindow.Bottom)
2222 csbi.srWindow.Top = max(pos.Y, h) - h + 1;
2223 do_move++;
2225 csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
2227 ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
2229 return ret;
2232 /******************************************************************************
2233 * GetConsoleCursorInfo [KERNEL32.@] Gets size and visibility of console
2235 * PARAMS
2236 * hcon [I] Handle to console screen buffer
2237 * cinfo [O] Address of cursor information
2239 * RETURNS
2240 * Success: TRUE
2241 * Failure: FALSE
2243 BOOL WINAPI GetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2245 BOOL ret;
2247 SERVER_START_REQ(get_console_output_info)
2249 req->handle = console_handle_unmap(hCon);
2250 ret = !wine_server_call_err( req );
2251 if (ret && cinfo)
2253 cinfo->dwSize = reply->cursor_size;
2254 cinfo->bVisible = reply->cursor_visible;
2257 SERVER_END_REQ;
2259 if (!ret) return FALSE;
2261 if (!cinfo)
2263 SetLastError(ERROR_INVALID_ACCESS);
2264 ret = FALSE;
2266 else TRACE("(%p) returning (%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2268 return ret;
2272 /******************************************************************************
2273 * SetConsoleCursorInfo [KERNEL32.@] Sets size and visibility of cursor
2275 * PARAMS
2276 * hcon [I] Handle to console screen buffer
2277 * cinfo [I] Address of cursor information
2278 * RETURNS
2279 * Success: TRUE
2280 * Failure: FALSE
2282 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
2284 BOOL ret;
2286 TRACE("(%p,%d,%d)\n", hCon, cinfo->dwSize, cinfo->bVisible);
2287 SERVER_START_REQ(set_console_output_info)
2289 req->handle = console_handle_unmap(hCon);
2290 req->cursor_size = cinfo->dwSize;
2291 req->cursor_visible = cinfo->bVisible;
2292 req->mask = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
2293 ret = !wine_server_call_err( req );
2295 SERVER_END_REQ;
2296 return ret;
2300 /******************************************************************************
2301 * SetConsoleWindowInfo [KERNEL32.@] Sets size and position of console
2303 * PARAMS
2304 * hcon [I] Handle to console screen buffer
2305 * bAbsolute [I] Coordinate type flag
2306 * window [I] Address of new window rectangle
2307 * RETURNS
2308 * Success: TRUE
2309 * Failure: FALSE
2311 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
2313 SMALL_RECT p = *window;
2314 BOOL ret;
2316 TRACE("(%p,%d,(%d,%d-%d,%d))\n", hCon, bAbsolute, p.Left, p.Top, p.Right, p.Bottom);
2318 if (!bAbsolute)
2320 CONSOLE_SCREEN_BUFFER_INFO csbi;
2322 if (!GetConsoleScreenBufferInfo(hCon, &csbi))
2323 return FALSE;
2324 p.Left += csbi.srWindow.Left;
2325 p.Top += csbi.srWindow.Top;
2326 p.Right += csbi.srWindow.Right;
2327 p.Bottom += csbi.srWindow.Bottom;
2329 SERVER_START_REQ(set_console_output_info)
2331 req->handle = console_handle_unmap(hCon);
2332 req->win_left = p.Left;
2333 req->win_top = p.Top;
2334 req->win_right = p.Right;
2335 req->win_bottom = p.Bottom;
2336 req->mask = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
2337 ret = !wine_server_call_err( req );
2339 SERVER_END_REQ;
2341 return ret;
2345 /******************************************************************************
2346 * SetConsoleTextAttribute [KERNEL32.@] Sets colors for text
2348 * Sets the foreground and background color attributes of characters
2349 * written to the screen buffer.
2351 * RETURNS
2352 * Success: TRUE
2353 * Failure: FALSE
2355 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
2357 BOOL ret;
2359 TRACE("(%p,%d)\n", hConsoleOutput, wAttr);
2360 SERVER_START_REQ(set_console_output_info)
2362 req->handle = console_handle_unmap(hConsoleOutput);
2363 req->attr = wAttr;
2364 req->mask = SET_CONSOLE_OUTPUT_INFO_ATTR;
2365 ret = !wine_server_call_err( req );
2367 SERVER_END_REQ;
2368 return ret;
2372 /******************************************************************************
2373 * SetConsoleScreenBufferSize [KERNEL32.@] Changes size of console
2375 * PARAMS
2376 * hConsoleOutput [I] Handle to console screen buffer
2377 * dwSize [I] New size in character rows and cols
2379 * RETURNS
2380 * Success: TRUE
2381 * Failure: FALSE
2383 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
2385 BOOL ret;
2387 TRACE("(%p,(%d,%d))\n", hConsoleOutput, dwSize.X, dwSize.Y);
2388 SERVER_START_REQ(set_console_output_info)
2390 req->handle = console_handle_unmap(hConsoleOutput);
2391 req->width = dwSize.X;
2392 req->height = dwSize.Y;
2393 req->mask = SET_CONSOLE_OUTPUT_INFO_SIZE;
2394 ret = !wine_server_call_err( req );
2396 SERVER_END_REQ;
2397 return ret;
2401 /******************************************************************************
2402 * ScrollConsoleScreenBufferA [KERNEL32.@]
2405 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2406 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2407 LPCHAR_INFO lpFill)
2409 CHAR_INFO ciw;
2411 ciw.Attributes = lpFill->Attributes;
2412 MultiByteToWideChar(GetConsoleOutputCP(), 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
2414 return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect,
2415 dwDestOrigin, &ciw);
2418 /******************************************************************
2419 * CONSOLE_FillLineUniform
2421 * Helper function for ScrollConsoleScreenBufferW
2422 * Fills a part of a line with a constant character info
2424 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
2426 SERVER_START_REQ( fill_console_output )
2428 req->handle = console_handle_unmap(hConsoleOutput);
2429 req->mode = CHAR_INFO_MODE_TEXTATTR;
2430 req->x = i;
2431 req->y = j;
2432 req->count = len;
2433 req->wrap = FALSE;
2434 req->data.ch = lpFill->Char.UnicodeChar;
2435 req->data.attr = lpFill->Attributes;
2436 wine_server_call_err( req );
2438 SERVER_END_REQ;
2441 /******************************************************************************
2442 * ScrollConsoleScreenBufferW [KERNEL32.@]
2446 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect,
2447 LPSMALL_RECT lpClipRect, COORD dwDestOrigin,
2448 LPCHAR_INFO lpFill)
2450 SMALL_RECT dst;
2451 DWORD ret;
2452 int i, j;
2453 int start = -1;
2454 SMALL_RECT clip;
2455 CONSOLE_SCREEN_BUFFER_INFO csbi;
2456 BOOL inside;
2457 COORD src;
2459 if (lpClipRect)
2460 TRACE("(%p,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput,
2461 lpScrollRect->Left, lpScrollRect->Top,
2462 lpScrollRect->Right, lpScrollRect->Bottom,
2463 lpClipRect->Left, lpClipRect->Top,
2464 lpClipRect->Right, lpClipRect->Bottom,
2465 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2466 else
2467 TRACE("(%p,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput,
2468 lpScrollRect->Left, lpScrollRect->Top,
2469 lpScrollRect->Right, lpScrollRect->Bottom,
2470 dwDestOrigin.X, dwDestOrigin.Y, lpFill);
2472 if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
2473 return FALSE;
2475 src.X = lpScrollRect->Left;
2476 src.Y = lpScrollRect->Top;
2478 /* step 1: get dst rect */
2479 dst.Left = dwDestOrigin.X;
2480 dst.Top = dwDestOrigin.Y;
2481 dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
2482 dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
2484 /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
2485 if (lpClipRect)
2487 clip.Left = max(0, lpClipRect->Left);
2488 clip.Right = min(csbi.dwSize.X - 1, lpClipRect->Right);
2489 clip.Top = max(0, lpClipRect->Top);
2490 clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
2492 else
2494 clip.Left = 0;
2495 clip.Right = csbi.dwSize.X - 1;
2496 clip.Top = 0;
2497 clip.Bottom = csbi.dwSize.Y - 1;
2499 if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
2501 /* step 2b: clip dst rect */
2502 if (dst.Left < clip.Left ) {src.X += clip.Left - dst.Left; dst.Left = clip.Left;}
2503 if (dst.Top < clip.Top ) {src.Y += clip.Top - dst.Top; dst.Top = clip.Top;}
2504 if (dst.Right > clip.Right ) dst.Right = clip.Right;
2505 if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
2507 /* step 3: transfer the bits */
2508 SERVER_START_REQ(move_console_output)
2510 req->handle = console_handle_unmap(hConsoleOutput);
2511 req->x_src = src.X;
2512 req->y_src = src.Y;
2513 req->x_dst = dst.Left;
2514 req->y_dst = dst.Top;
2515 req->w = dst.Right - dst.Left + 1;
2516 req->h = dst.Bottom - dst.Top + 1;
2517 ret = !wine_server_call_err( req );
2519 SERVER_END_REQ;
2521 if (!ret) return FALSE;
2523 /* step 4: clean out the exposed part */
2525 /* have to write cell [i,j] if it is not in dst rect (because it has already
2526 * been written to by the scroll) and is in clip (we shall not write
2527 * outside of clip)
2529 for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
2531 inside = dst.Top <= j && j <= dst.Bottom;
2532 start = -1;
2533 for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
2535 if (inside && dst.Left <= i && i <= dst.Right)
2537 if (start != -1)
2539 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2540 start = -1;
2543 else
2545 if (start == -1) start = i;
2548 if (start != -1)
2549 CONSOLE_FillLineUniform(hConsoleOutput, start, j, i - start, lpFill);
2552 return TRUE;
2555 /******************************************************************
2556 * AttachConsole (KERNEL32.@)
2558 BOOL WINAPI AttachConsole(DWORD dwProcessId)
2560 FIXME("stub %x\n",dwProcessId);
2561 return TRUE;
2564 /******************************************************************
2565 * GetConsoleDisplayMode (KERNEL32.@)
2567 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
2569 TRACE("semi-stub: %p\n", lpModeFlags);
2570 /* It is safe to successfully report windowed mode */
2571 *lpModeFlags = 0;
2572 return TRUE;
2575 /******************************************************************
2576 * SetConsoleDisplayMode (KERNEL32.@)
2578 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
2579 COORD *lpNewScreenBufferDimensions)
2581 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
2582 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
2583 if (dwFlags == 1)
2585 /* We cannot switch to fullscreen */
2586 return FALSE;
2588 return TRUE;
2592 /* ====================================================================
2594 * Console manipulation functions
2596 * ====================================================================*/
2598 /* some missing functions...
2599 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
2600 * should get the right API and implement them
2601 * GetConsoleCommandHistory[AW] (dword dword dword)
2602 * GetConsoleCommandHistoryLength[AW]
2603 * SetConsoleCommandHistoryMode
2604 * SetConsoleNumberOfCommands[AW]
2606 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
2608 int len = 0;
2610 SERVER_START_REQ( get_console_input_history )
2612 req->handle = 0;
2613 req->index = idx;
2614 if (buf && buf_len > 1)
2616 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
2618 if (!wine_server_call_err( req ))
2620 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
2621 len = reply->total / sizeof(WCHAR) + 1;
2624 SERVER_END_REQ;
2625 return len;
2628 /******************************************************************
2629 * CONSOLE_AppendHistory
2633 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
2635 size_t len = strlenW(ptr);
2636 BOOL ret;
2638 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
2639 if (!len) return FALSE;
2641 SERVER_START_REQ( append_console_input_history )
2643 req->handle = 0;
2644 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
2645 ret = !wine_server_call_err( req );
2647 SERVER_END_REQ;
2648 return ret;
2651 /******************************************************************
2652 * CONSOLE_GetNumHistoryEntries
2656 unsigned CONSOLE_GetNumHistoryEntries(void)
2658 unsigned ret = -1;
2659 SERVER_START_REQ(get_console_input_info)
2661 req->handle = 0;
2662 if (!wine_server_call_err( req )) ret = reply->history_index;
2664 SERVER_END_REQ;
2665 return ret;
2668 /******************************************************************
2669 * CONSOLE_GetEditionMode
2673 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
2675 unsigned ret = FALSE;
2676 SERVER_START_REQ(get_console_input_info)
2678 req->handle = console_handle_unmap(hConIn);
2679 if ((ret = !wine_server_call_err( req )))
2680 *mode = reply->edition_mode;
2682 SERVER_END_REQ;
2683 return ret;
2686 /******************************************************************
2687 * GetConsoleAliasW
2690 * RETURNS
2691 * 0 if an error occurred, non-zero for success
2694 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
2695 DWORD TargetBufferLength, LPWSTR lpExename)
2697 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
2698 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2699 return 0;
2702 /******************************************************************
2703 * GetConsoleProcessList (KERNEL32.@)
2705 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
2707 FIXME("(%p,%d): stub\n", processlist, processcount);
2709 if (!processlist || processcount < 1)
2711 SetLastError(ERROR_INVALID_PARAMETER);
2712 return 0;
2715 return 0;