libwine: Remove __wine_main_arg* from the public header.
[wine/zf.git] / dlls / kernel32 / console.c
blob472d5139901a0d54afef0a80c327f07c6289d86f
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,2010 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 #include <limits.h>
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
41 #include <assert.h>
42 #ifdef HAVE_TERMIOS_H
43 # include <termios.h>
44 #endif
45 #ifdef HAVE_SYS_POLL_H
46 # include <sys/poll.h>
47 #endif
49 #define NONAMELESSUNION
50 #include "ntstatus.h"
51 #define WIN32_NO_STATUS
52 #include "windef.h"
53 #include "winbase.h"
54 #include "winnls.h"
55 #include "winerror.h"
56 #include "wincon.h"
57 #include "wine/server.h"
58 #include "wine/exception.h"
59 #include "wine/unicode.h"
60 #include "wine/debug.h"
61 #include "excpt.h"
62 #include "console_private.h"
63 #include "kernel_private.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(console);
67 static CRITICAL_SECTION CONSOLE_CritSect;
68 static CRITICAL_SECTION_DEBUG critsect_debug =
70 0, 0, &CONSOLE_CritSect,
71 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
72 0, 0, { (DWORD_PTR)(__FILE__ ": CONSOLE_CritSect") }
74 static CRITICAL_SECTION CONSOLE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
76 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
77 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
79 /* FIXME: this is not thread safe */
80 static HANDLE console_wait_event;
82 /* map input records to ASCII */
83 static void input_records_WtoA( INPUT_RECORD *buffer, int count )
85 UINT cp = GetConsoleCP();
86 int i;
87 char ch;
89 for (i = 0; i < count; i++)
91 if (buffer[i].EventType != KEY_EVENT) continue;
92 WideCharToMultiByte( cp, 0, &buffer[i].Event.KeyEvent.uChar.UnicodeChar, 1, &ch, 1, NULL, NULL );
93 buffer[i].Event.KeyEvent.uChar.AsciiChar = ch;
97 static struct termios S_termios; /* saved termios for bare consoles */
98 static BOOL S_termios_raw /* = FALSE */;
100 /* The scheme for bare consoles for managing raw/cooked settings is as follows:
101 * - a bare console is created for all CUI programs started from command line (without
102 * wineconsole) (let's call those PS)
103 * - of course, every child of a PS which requires console inheritance will get it
104 * - the console termios attributes are saved at the start of program which is attached to be
105 * bare console
106 * - if any program attached to a bare console requests input from console, the console is
107 * turned into raw mode
108 * - when the program which created the bare console (the program started from command line)
109 * exits, it will restore the console termios attributes it saved at startup (this
110 * will put back the console into cooked mode if it had been put in raw mode)
111 * - if any other program attached to this bare console is still alive, the Unix shell will put
112 * it in the background, hence forbidding access to the console. Therefore, reading console
113 * input will not be available when the bare console creator has died.
114 * FIXME: This is a limitation of current implementation
117 /* returns the fd for a bare console (-1 otherwise) */
118 static int get_console_bare_fd(HANDLE hin)
120 int fd;
122 if (is_console_handle(hin) &&
123 wine_server_handle_to_fd(wine_server_ptr_handle(console_handle_unmap(hin)),
124 0, &fd, NULL) == STATUS_SUCCESS)
125 return fd;
126 return -1;
129 static BOOL save_console_mode(HANDLE hin)
131 int fd;
132 BOOL ret;
134 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
135 ret = tcgetattr(fd, &S_termios) >= 0;
136 close(fd);
137 return ret;
140 static BOOL put_console_into_raw_mode(int fd)
142 RtlEnterCriticalSection(&CONSOLE_CritSect);
143 if (!S_termios_raw)
145 struct termios term = S_termios;
147 term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
148 term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
149 term.c_cflag &= ~(CSIZE | PARENB);
150 term.c_cflag |= CS8;
151 /* FIXME: we should actually disable output processing here
152 * and let kernel32/console.c do the job (with support of enable/disable of
153 * processed output)
155 /* term.c_oflag &= ~(OPOST); */
156 term.c_cc[VMIN] = 1;
157 term.c_cc[VTIME] = 0;
158 S_termios_raw = tcsetattr(fd, TCSANOW, &term) >= 0;
160 RtlLeaveCriticalSection(&CONSOLE_CritSect);
162 return S_termios_raw;
165 /* put back the console in cooked mode iff we're the process which created the bare console
166 * we don't test if this process has set the console in raw mode as it could be one of its
167 * children who did it
169 static BOOL restore_console_mode(HANDLE hin)
171 int fd;
172 BOOL ret = TRUE;
174 if (S_termios_raw)
176 if ((fd = get_console_bare_fd(hin)) == -1) return FALSE;
177 ret = tcsetattr(fd, TCSANOW, &S_termios) >= 0;
178 close(fd);
181 if (RtlGetCurrentPeb()->ProcessParameters->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
182 TERM_Exit();
184 return ret;
187 /******************************************************************************
188 * GetConsoleWindow [KERNEL32.@] Get hwnd of the console window.
190 * RETURNS
191 * Success: hwnd of the console window.
192 * Failure: NULL
194 HWND WINAPI GetConsoleWindow(VOID)
196 HWND hWnd = NULL;
198 SERVER_START_REQ(get_console_input_info)
200 req->handle = 0;
201 if (!wine_server_call_err(req)) hWnd = wine_server_ptr_handle( reply->win );
203 SERVER_END_REQ;
205 return hWnd;
209 /***********************************************************************
210 * Beep (KERNEL32.@)
212 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
214 static const char beep = '\a';
215 /* dwFreq and dwDur are ignored by Win95 */
216 if (isatty(2)) write( 2, &beep, 1 );
217 return TRUE;
221 /******************************************************************
222 * OpenConsoleW (KERNEL32.@)
224 * Undocumented
225 * Open a handle to the current process console.
226 * Returns INVALID_HANDLE_VALUE on failure.
228 HANDLE WINAPI OpenConsoleW(LPCWSTR name, DWORD access, BOOL inherit, DWORD creation)
230 HANDLE output = INVALID_HANDLE_VALUE;
231 HANDLE ret;
233 TRACE("(%s, 0x%08x, %d, %u)\n", debugstr_w(name), access, inherit, creation);
235 if (name)
237 if (strcmpiW(coninW, name) == 0)
238 output = (HANDLE) FALSE;
239 else if (strcmpiW(conoutW, name) == 0)
240 output = (HANDLE) TRUE;
243 if (output == INVALID_HANDLE_VALUE || creation != OPEN_EXISTING)
245 SetLastError(ERROR_INVALID_PARAMETER);
246 return INVALID_HANDLE_VALUE;
249 SERVER_START_REQ( open_console )
251 req->from = wine_server_obj_handle( output );
252 req->access = access;
253 req->attributes = inherit ? OBJ_INHERIT : 0;
254 req->share = FILE_SHARE_READ | FILE_SHARE_WRITE;
255 wine_server_call_err( req );
256 ret = wine_server_ptr_handle( reply->handle );
258 SERVER_END_REQ;
259 if (ret)
260 ret = console_handle_map(ret);
262 return ret;
265 /******************************************************************
266 * VerifyConsoleIoHandle (KERNEL32.@)
268 * Undocumented
270 BOOL WINAPI VerifyConsoleIoHandle(HANDLE handle)
272 BOOL ret;
274 if (!is_console_handle(handle)) return FALSE;
275 SERVER_START_REQ(get_console_mode)
277 req->handle = console_handle_unmap(handle);
278 ret = !wine_server_call( req );
280 SERVER_END_REQ;
281 return ret;
284 /******************************************************************
285 * DuplicateConsoleHandle (KERNEL32.@)
287 * Undocumented
289 HANDLE WINAPI DuplicateConsoleHandle(HANDLE handle, DWORD access, BOOL inherit,
290 DWORD options)
292 HANDLE ret;
294 if (!is_console_handle(handle) ||
295 !DuplicateHandle(GetCurrentProcess(), wine_server_ptr_handle(console_handle_unmap(handle)),
296 GetCurrentProcess(), &ret, access, inherit, options))
297 return INVALID_HANDLE_VALUE;
298 return console_handle_map(ret);
301 /******************************************************************
302 * CloseConsoleHandle (KERNEL32.@)
304 * Undocumented
306 BOOL WINAPI CloseConsoleHandle(HANDLE handle)
308 if (!is_console_handle(handle))
310 SetLastError(ERROR_INVALID_PARAMETER);
311 return FALSE;
313 return CloseHandle(wine_server_ptr_handle(console_handle_unmap(handle)));
316 /******************************************************************
317 * GetConsoleInputWaitHandle (KERNEL32.@)
319 * Undocumented
321 HANDLE WINAPI GetConsoleInputWaitHandle(void)
323 if (!console_wait_event)
325 SERVER_START_REQ(get_console_wait_event)
327 if (!wine_server_call_err( req ))
328 console_wait_event = wine_server_ptr_handle( reply->event );
330 SERVER_END_REQ;
332 return console_wait_event;
336 /******************************************************************************
337 * read_console_input
339 * Helper function for ReadConsole, ReadConsoleInput and FlushConsoleInputBuffer
341 * Returns
342 * 0 for error, 1 for no INPUT_RECORD ready, 2 with INPUT_RECORD ready
344 enum read_console_input_return {rci_error = 0, rci_timeout = 1, rci_gotone = 2};
346 static enum read_console_input_return bare_console_fetch_input(HANDLE handle, int fd, DWORD timeout)
348 enum read_console_input_return ret;
349 char input[8];
350 WCHAR inputw[8];
351 int i;
352 size_t idx = 0, idxw;
353 unsigned numEvent;
354 INPUT_RECORD ir[8];
355 DWORD written;
356 struct pollfd pollfd;
357 BOOL locked = FALSE, next_char;
361 if (idx == sizeof(input))
363 FIXME("buffer too small (%s)\n", wine_dbgstr_an(input, idx));
364 ret = rci_error;
365 break;
367 pollfd.fd = fd;
368 pollfd.events = POLLIN;
369 pollfd.revents = 0;
370 next_char = FALSE;
372 switch (poll(&pollfd, 1, timeout))
374 case 1:
375 if (!locked)
377 RtlEnterCriticalSection(&CONSOLE_CritSect);
378 locked = TRUE;
380 i = read(fd, &input[idx], 1);
381 if (i < 0)
383 ret = rci_error;
384 break;
386 if (i == 0)
388 /* actually another thread likely beat us to reading the char
389 * return rci_gotone, while not perfect, it should work in most of the cases (as the new event
390 * should be now in the queue, fed from the other thread)
392 ret = rci_gotone;
393 break;
396 idx++;
397 numEvent = TERM_FillInputRecord(input, idx, ir);
398 switch (numEvent)
400 case 0:
401 /* we need more char(s) to tell if it matches a key-db entry. wait 1/2s for next char */
402 timeout = 500;
403 next_char = TRUE;
404 break;
405 case -1:
406 /* we haven't found the string into key-db, push full input string into server */
407 idxw = MultiByteToWideChar(CP_UNIXCP, 0, input, idx, inputw, ARRAY_SIZE(inputw));
409 /* we cannot translate yet... likely we need more chars (wait max 1/2s for next char) */
410 if (idxw == 0)
412 timeout = 500;
413 next_char = TRUE;
414 break;
416 for (i = 0; i < idxw; i++)
418 numEvent = TERM_FillSimpleChar(inputw[i], ir);
419 WriteConsoleInputW(handle, ir, numEvent, &written);
421 ret = rci_gotone;
422 break;
423 default:
424 /* we got a transformation from key-db... push this into server */
425 ret = WriteConsoleInputW(handle, ir, numEvent, &written) ? rci_gotone : rci_error;
426 break;
428 break;
429 case 0: ret = rci_timeout; break;
430 default: ret = rci_error; break;
432 } while (next_char);
433 if (locked) RtlLeaveCriticalSection(&CONSOLE_CritSect);
435 return ret;
438 static enum read_console_input_return read_console_input(HANDLE handle, PINPUT_RECORD ir, DWORD timeout)
440 int fd;
441 enum read_console_input_return ret;
443 if ((fd = get_console_bare_fd(handle)) != -1)
445 put_console_into_raw_mode(fd);
446 if (WaitForSingleObject(GetConsoleInputWaitHandle(), 0) != WAIT_OBJECT_0)
448 ret = bare_console_fetch_input(handle, fd, timeout);
450 else ret = rci_gotone;
451 close(fd);
452 if (ret != rci_gotone) return ret;
454 else
456 if (!VerifyConsoleIoHandle(handle)) return rci_error;
458 if (WaitForSingleObject(GetConsoleInputWaitHandle(), timeout) != WAIT_OBJECT_0)
459 return rci_timeout;
462 SERVER_START_REQ( read_console_input )
464 req->handle = console_handle_unmap(handle);
465 req->flush = TRUE;
466 wine_server_set_reply( req, ir, sizeof(INPUT_RECORD) );
467 if (wine_server_call_err( req ) || !reply->read) ret = rci_error;
468 else ret = rci_gotone;
470 SERVER_END_REQ;
472 return ret;
476 /***********************************************************************
477 * FlushConsoleInputBuffer (KERNEL32.@)
479 BOOL WINAPI FlushConsoleInputBuffer( HANDLE handle )
481 enum read_console_input_return last;
482 INPUT_RECORD ir;
484 while ((last = read_console_input(handle, &ir, 0)) == rci_gotone);
486 return last == rci_timeout;
490 /***********************************************************************
491 * SetConsoleTitleA (KERNEL32.@)
493 BOOL WINAPI SetConsoleTitleA( LPCSTR title )
495 LPWSTR titleW;
496 BOOL ret;
498 DWORD len = MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, NULL, 0 );
499 if (!(titleW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) return FALSE;
500 MultiByteToWideChar( GetConsoleOutputCP(), 0, title, -1, titleW, len );
501 ret = SetConsoleTitleW(titleW);
502 HeapFree(GetProcessHeap(), 0, titleW);
503 return ret;
507 /***********************************************************************
508 * GetConsoleKeyboardLayoutNameA (KERNEL32.@)
510 BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR layoutName)
512 FIXME( "stub %p\n", layoutName);
513 return TRUE;
516 /***********************************************************************
517 * GetConsoleKeyboardLayoutNameW (KERNEL32.@)
519 BOOL WINAPI GetConsoleKeyboardLayoutNameW(LPWSTR layoutName)
521 static int once;
522 if (!once++)
523 FIXME( "stub %p\n", layoutName);
524 return TRUE;
527 /***********************************************************************
528 * GetConsoleTitleA (KERNEL32.@)
530 * See GetConsoleTitleW.
532 DWORD WINAPI GetConsoleTitleA(LPSTR title, DWORD size)
534 WCHAR *ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
535 DWORD ret;
537 if (!ptr) return 0;
538 ret = GetConsoleTitleW( ptr, size );
539 if (ret)
541 WideCharToMultiByte( GetConsoleOutputCP(), 0, ptr, ret + 1, title, size, NULL, NULL);
542 ret = strlen(title);
544 HeapFree(GetProcessHeap(), 0, ptr);
545 return ret;
549 static WCHAR* S_EditString /* = NULL */;
550 static unsigned S_EditStrPos /* = 0 */;
552 /***********************************************************************
553 * FreeConsole (KERNEL32.@)
555 BOOL WINAPI FreeConsole(VOID)
557 BOOL ret;
559 /* invalidate local copy of input event handle */
560 console_wait_event = 0;
562 SERVER_START_REQ(free_console)
564 ret = !wine_server_call_err( req );
566 SERVER_END_REQ;
567 return ret;
570 /******************************************************************
571 * start_console_renderer
573 * helper for AllocConsole
574 * starts the renderer process
576 static BOOL start_console_renderer_helper(const char* appname, STARTUPINFOA* si,
577 HANDLE hEvent)
579 char buffer[1024];
580 int ret;
581 PROCESS_INFORMATION pi;
583 /* FIXME: use dynamic allocation for most of the buffers below */
584 ret = snprintf(buffer, sizeof(buffer), "%s --use-event=%ld", appname, (DWORD_PTR)hEvent);
585 if ((ret > -1) && (ret < sizeof(buffer)) &&
586 CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS,
587 NULL, NULL, si, &pi))
589 HANDLE wh[2];
590 DWORD res;
592 wh[0] = hEvent;
593 wh[1] = pi.hProcess;
594 res = WaitForMultipleObjects(2, wh, FALSE, INFINITE);
596 CloseHandle(pi.hThread);
597 CloseHandle(pi.hProcess);
599 if (res != WAIT_OBJECT_0) return FALSE;
601 TRACE("Started wineconsole pid=%08x tid=%08x\n",
602 pi.dwProcessId, pi.dwThreadId);
604 return TRUE;
606 return FALSE;
609 static BOOL start_console_renderer(STARTUPINFOA* si)
611 HANDLE hEvent = 0;
612 LPSTR p;
613 OBJECT_ATTRIBUTES attr;
614 BOOL ret = FALSE;
616 attr.Length = sizeof(attr);
617 attr.RootDirectory = 0;
618 attr.Attributes = OBJ_INHERIT;
619 attr.ObjectName = NULL;
620 attr.SecurityDescriptor = NULL;
621 attr.SecurityQualityOfService = NULL;
623 NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE);
624 if (!hEvent) return FALSE;
626 /* first try environment variable */
627 if ((p = getenv("WINECONSOLE")) != NULL)
629 ret = start_console_renderer_helper(p, si, hEvent);
630 if (!ret)
631 ERR("Couldn't launch Wine console from WINECONSOLE env var (%s)... "
632 "trying default access\n", p);
635 /* then try the regular PATH */
636 if (!ret)
637 ret = start_console_renderer_helper("wineconsole", si, hEvent);
639 CloseHandle(hEvent);
640 return ret;
643 /***********************************************************************
644 * AllocConsole (KERNEL32.@)
646 * creates an xterm with a pty to our program
648 BOOL WINAPI AllocConsole(void)
650 HANDLE handle_in = INVALID_HANDLE_VALUE;
651 HANDLE handle_out = INVALID_HANDLE_VALUE;
652 HANDLE handle_err = INVALID_HANDLE_VALUE;
653 STARTUPINFOA siCurrent;
654 STARTUPINFOA siConsole;
655 char buffer[1024];
657 TRACE("()\n");
659 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
660 FALSE, OPEN_EXISTING );
662 if (VerifyConsoleIoHandle(handle_in))
664 /* we already have a console opened on this process, don't create a new one */
665 CloseHandle(handle_in);
666 return FALSE;
669 /* invalidate local copy of input event handle */
670 console_wait_event = 0;
672 GetStartupInfoA(&siCurrent);
674 memset(&siConsole, 0, sizeof(siConsole));
675 siConsole.cb = sizeof(siConsole);
676 /* setup a view arguments for wineconsole (it'll use them as default values) */
677 if (siCurrent.dwFlags & STARTF_USECOUNTCHARS)
679 siConsole.dwFlags |= STARTF_USECOUNTCHARS;
680 siConsole.dwXCountChars = siCurrent.dwXCountChars;
681 siConsole.dwYCountChars = siCurrent.dwYCountChars;
683 if (siCurrent.dwFlags & STARTF_USEFILLATTRIBUTE)
685 siConsole.dwFlags |= STARTF_USEFILLATTRIBUTE;
686 siConsole.dwFillAttribute = siCurrent.dwFillAttribute;
688 if (siCurrent.dwFlags & STARTF_USESHOWWINDOW)
690 siConsole.dwFlags |= STARTF_USESHOWWINDOW;
691 siConsole.wShowWindow = siCurrent.wShowWindow;
693 /* FIXME (should pass the unicode form) */
694 if (siCurrent.lpTitle)
695 siConsole.lpTitle = siCurrent.lpTitle;
696 else if (GetModuleFileNameA(0, buffer, sizeof(buffer)))
698 buffer[sizeof(buffer) - 1] = '\0';
699 siConsole.lpTitle = buffer;
702 if (!start_console_renderer(&siConsole))
703 goto the_end;
705 if( !(siCurrent.dwFlags & STARTF_USESTDHANDLES) ) {
706 /* all std I/O handles are inheritable by default */
707 handle_in = OpenConsoleW( coninW, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
708 TRUE, OPEN_EXISTING );
709 if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
711 handle_out = OpenConsoleW( conoutW, GENERIC_READ|GENERIC_WRITE,
712 TRUE, OPEN_EXISTING );
713 if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
715 if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(),
716 &handle_err, 0, TRUE, DUPLICATE_SAME_ACCESS))
717 goto the_end;
718 } else {
719 /* STARTF_USESTDHANDLES flag: use handles from StartupInfo */
720 handle_in = siCurrent.hStdInput;
721 handle_out = siCurrent.hStdOutput;
722 handle_err = siCurrent.hStdError;
725 /* NT resets the STD_*_HANDLEs on console alloc */
726 SetStdHandle(STD_INPUT_HANDLE, handle_in);
727 SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
728 SetStdHandle(STD_ERROR_HANDLE, handle_err);
730 SetLastError(ERROR_SUCCESS);
732 return TRUE;
734 the_end:
735 ERR("Can't allocate console\n");
736 if (handle_in != INVALID_HANDLE_VALUE) CloseHandle(handle_in);
737 if (handle_out != INVALID_HANDLE_VALUE) CloseHandle(handle_out);
738 if (handle_err != INVALID_HANDLE_VALUE) CloseHandle(handle_err);
739 FreeConsole();
740 return FALSE;
744 /***********************************************************************
745 * ReadConsoleA (KERNEL32.@)
747 BOOL WINAPI ReadConsoleA( HANDLE handle, LPVOID buffer, DWORD length, DWORD *ret_count, void *reserved )
749 LPWSTR strW = HeapAlloc( GetProcessHeap(), 0, length * sizeof(WCHAR) );
750 DWORD count = 0;
751 BOOL ret;
753 if (!strW)
755 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
756 return FALSE;
758 if ((ret = ReadConsoleW( handle, strW, length, &count, NULL )))
760 count = WideCharToMultiByte( GetConsoleCP(), 0, strW, count, buffer, length, NULL, NULL );
761 if (ret_count) *ret_count = count;
763 HeapFree( GetProcessHeap(), 0, strW );
764 return ret;
768 /***********************************************************************
769 * ReadConsoleW (KERNEL32.@)
771 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
772 DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
774 DWORD charsread;
775 LPWSTR xbuf = lpBuffer;
776 DWORD mode;
777 BOOL is_bare = FALSE;
778 int fd;
780 TRACE("(%p,%p,%d,%p,%p)\n",
781 hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
783 if (nNumberOfCharsToRead > INT_MAX)
785 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
786 return FALSE;
789 if (!GetConsoleMode(hConsoleInput, &mode))
790 return FALSE;
791 if ((fd = get_console_bare_fd(hConsoleInput)) != -1)
793 close(fd);
794 is_bare = TRUE;
796 if (mode & ENABLE_LINE_INPUT)
798 if (!S_EditString || S_EditString[S_EditStrPos] == 0)
800 HeapFree(GetProcessHeap(), 0, S_EditString);
801 if (!(S_EditString = CONSOLE_Readline(hConsoleInput, !is_bare)))
802 return FALSE;
803 S_EditStrPos = 0;
805 charsread = lstrlenW(&S_EditString[S_EditStrPos]);
806 if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
807 memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
808 S_EditStrPos += charsread;
810 else
812 INPUT_RECORD ir;
813 DWORD timeout = INFINITE;
815 /* FIXME: should we read at least 1 char? The SDK does not say */
816 /* wait for at least one available input record (it doesn't mean we'll have
817 * chars stored in xbuf...)
819 * Although SDK doc keeps silence about 1 char, SDK examples assume
820 * that we should wait for at least one character (not key). --KS
822 charsread = 0;
825 if (read_console_input(hConsoleInput, &ir, timeout) != rci_gotone) break;
826 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
827 ir.Event.KeyEvent.uChar.UnicodeChar)
829 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
830 timeout = 0;
832 } while (charsread < nNumberOfCharsToRead);
833 /* nothing has been read */
834 if (timeout == INFINITE) return FALSE;
837 if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
839 return TRUE;
843 /***********************************************************************
844 * ReadConsoleInputA (KERNEL32.@)
846 BOOL WINAPI ReadConsoleInputA( HANDLE handle, INPUT_RECORD *buffer, DWORD length, DWORD *count )
848 DWORD read;
850 if (!ReadConsoleInputW( handle, buffer, length, &read )) return FALSE;
851 input_records_WtoA( buffer, read );
852 if (count) *count = read;
853 return TRUE;
857 /***********************************************************************
858 * ReadConsoleInputW (KERNEL32.@)
860 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer,
861 DWORD nLength, LPDWORD lpNumberOfEventsRead)
863 DWORD idx = 0;
864 DWORD timeout = INFINITE;
866 if (!nLength)
868 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
869 return TRUE;
872 /* loop until we get at least one event */
873 while (read_console_input(hConsoleInput, &lpBuffer[idx], timeout) == rci_gotone &&
874 ++idx < nLength)
875 timeout = 0;
877 if (lpNumberOfEventsRead) *lpNumberOfEventsRead = idx;
878 return idx != 0;
882 /***********************************************************************
883 * GetNumberOfConsoleMouseButtons (KERNEL32.@)
885 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
887 FIXME("(%p): stub\n", nrofbuttons);
888 *nrofbuttons = 2;
889 return TRUE;
892 /******************************************************************
893 * CONSOLE_DefaultHandler
895 * Final control event handler
897 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
899 FIXME("Terminating process %x on event %x\n", GetCurrentProcessId(), dwCtrlType);
900 ExitProcess(0);
901 /* should never go here */
902 return TRUE;
905 /******************************************************************************
906 * SetConsoleCtrlHandler [KERNEL32.@] Adds function to calling process list
908 * PARAMS
909 * func [I] Address of handler function
910 * add [I] Handler to add or remove
912 * RETURNS
913 * Success: TRUE
914 * Failure: FALSE
917 struct ConsoleHandler
919 PHANDLER_ROUTINE handler;
920 struct ConsoleHandler* next;
923 static struct ConsoleHandler CONSOLE_DefaultConsoleHandler = {CONSOLE_DefaultHandler, NULL};
924 static struct ConsoleHandler* CONSOLE_Handlers = &CONSOLE_DefaultConsoleHandler;
926 /*****************************************************************************/
928 /******************************************************************
929 * SetConsoleCtrlHandler (KERNEL32.@)
931 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
933 BOOL ret = TRUE;
935 TRACE("(%p,%i)\n", func, add);
937 if (!func)
939 RtlEnterCriticalSection(&CONSOLE_CritSect);
940 if (add)
941 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags |= 1;
942 else
943 NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags &= ~1;
944 RtlLeaveCriticalSection(&CONSOLE_CritSect);
946 else if (add)
948 struct ConsoleHandler* ch = HeapAlloc(GetProcessHeap(), 0, sizeof(struct ConsoleHandler));
950 if (!ch) return FALSE;
951 ch->handler = func;
952 RtlEnterCriticalSection(&CONSOLE_CritSect);
953 ch->next = CONSOLE_Handlers;
954 CONSOLE_Handlers = ch;
955 RtlLeaveCriticalSection(&CONSOLE_CritSect);
957 else
959 struct ConsoleHandler** ch;
960 RtlEnterCriticalSection(&CONSOLE_CritSect);
961 for (ch = &CONSOLE_Handlers; *ch; ch = &(*ch)->next)
963 if ((*ch)->handler == func) break;
965 if (*ch)
967 struct ConsoleHandler* rch = *ch;
969 /* sanity check */
970 if (rch == &CONSOLE_DefaultConsoleHandler)
972 ERR("Who's trying to remove default handler???\n");
973 SetLastError(ERROR_INVALID_PARAMETER);
974 ret = FALSE;
976 else
978 *ch = rch->next;
979 HeapFree(GetProcessHeap(), 0, rch);
982 else
984 WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
985 SetLastError(ERROR_INVALID_PARAMETER);
986 ret = FALSE;
988 RtlLeaveCriticalSection(&CONSOLE_CritSect);
990 return ret;
993 static LONG WINAPI CONSOLE_CtrlEventHandler(EXCEPTION_POINTERS *eptr)
995 TRACE("(%x)\n", eptr->ExceptionRecord->ExceptionCode);
996 return EXCEPTION_EXECUTE_HANDLER;
999 /******************************************************************
1000 * CONSOLE_SendEventThread
1002 * Internal helper to pass an event to the list on installed handlers
1004 static DWORD WINAPI CONSOLE_SendEventThread(void* pmt)
1006 DWORD_PTR event = (DWORD_PTR)pmt;
1007 struct ConsoleHandler* ch;
1009 if (event == CTRL_C_EVENT)
1011 BOOL caught_by_dbg = TRUE;
1012 /* First, try to pass the ctrl-C event to the debugger (if any)
1013 * If it continues, there's nothing more to do
1014 * Otherwise, we need to send the ctrl-C event to the handlers
1016 __TRY
1018 RaiseException( DBG_CONTROL_C, 0, 0, NULL );
1020 __EXCEPT(CONSOLE_CtrlEventHandler)
1022 caught_by_dbg = FALSE;
1024 __ENDTRY;
1025 if (caught_by_dbg) return 0;
1026 /* the debugger didn't continue... so, pass to ctrl handlers */
1028 RtlEnterCriticalSection(&CONSOLE_CritSect);
1029 for (ch = CONSOLE_Handlers; ch; ch = ch->next)
1031 if (ch->handler(event)) break;
1033 RtlLeaveCriticalSection(&CONSOLE_CritSect);
1034 return 1;
1037 /******************************************************************
1038 * CONSOLE_HandleCtrlC
1040 * Check whether the shall manipulate CtrlC events
1042 int CONSOLE_HandleCtrlC(unsigned sig)
1044 HANDLE thread;
1046 /* FIXME: better test whether a console is attached to this process ??? */
1047 extern unsigned CONSOLE_GetNumHistoryEntries(void);
1048 if (CONSOLE_GetNumHistoryEntries() == (unsigned)-1) return 0;
1050 /* check if we have to ignore ctrl-C events */
1051 if (!(NtCurrentTeb()->Peb->ProcessParameters->ConsoleFlags & 1))
1053 /* Create a separate thread to signal all the events.
1054 * This is needed because:
1055 * - this function can be called in an Unix signal handler (hence on an
1056 * different stack than the thread that's running). This breaks the
1057 * Win32 exception mechanisms (where the thread's stack is checked).
1058 * - since the current thread, while processing the signal, can hold the
1059 * console critical section, we need another execution environment where
1060 * we can wait on this critical section
1062 thread = CreateThread(NULL, 0, CONSOLE_SendEventThread, (void*)CTRL_C_EVENT, 0, NULL);
1063 if (thread == NULL)
1064 return 0;
1066 CloseHandle(thread);
1068 return 1;
1071 /******************************************************************
1072 * CONSOLE_WriteChars
1074 * WriteConsoleOutput helper: hides server call semantics
1075 * writes a string at a given pos with standard attribute
1077 static int CONSOLE_WriteChars(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
1079 int written = -1;
1081 if (!nc) return 0;
1083 SERVER_START_REQ( write_console_output )
1085 req->handle = console_handle_unmap(hCon);
1086 req->x = pos->X;
1087 req->y = pos->Y;
1088 req->mode = CHAR_INFO_MODE_TEXTSTDATTR;
1089 req->wrap = FALSE;
1090 wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
1091 if (!wine_server_call_err( req )) written = reply->written;
1093 SERVER_END_REQ;
1095 if (written > 0) pos->X += written;
1096 return written;
1099 /******************************************************************
1100 * next_line
1102 * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
1105 static BOOL next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
1107 SMALL_RECT src;
1108 CHAR_INFO ci;
1109 COORD dst;
1111 csbi->dwCursorPosition.X = 0;
1112 csbi->dwCursorPosition.Y++;
1114 if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return TRUE;
1116 src.Top = 1;
1117 src.Bottom = csbi->dwSize.Y - 1;
1118 src.Left = 0;
1119 src.Right = csbi->dwSize.X - 1;
1121 dst.X = 0;
1122 dst.Y = 0;
1124 ci.Attributes = csbi->wAttributes;
1125 ci.Char.UnicodeChar = ' ';
1127 csbi->dwCursorPosition.Y--;
1128 if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
1129 return FALSE;
1130 return TRUE;
1133 /******************************************************************
1134 * write_block
1136 * WriteConsoleOutput helper: writes a block of non special characters
1137 * Block can spread on several lines, and wrapping, if needed, is
1138 * handled
1141 static BOOL write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
1142 DWORD mode, LPCWSTR ptr, int len)
1144 int blk; /* number of chars to write on current line */
1145 int done; /* number of chars already written */
1147 if (len <= 0) return TRUE;
1149 if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
1151 for (done = 0; done < len; done += blk)
1153 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1155 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1156 return FALSE;
1157 if (csbi->dwCursorPosition.X == csbi->dwSize.X && !next_line(hCon, csbi))
1158 return FALSE;
1161 else
1163 int pos = csbi->dwCursorPosition.X;
1164 /* FIXME: we could reduce the number of loops
1165 * but, in most cases we wouldn't gain lots of time (it would only
1166 * happen if we're asked to overwrite more than twice the part of the line,
1167 * which is unlikely
1169 for (done = 0; done < len; done += blk)
1171 blk = min(len - done, csbi->dwSize.X - csbi->dwCursorPosition.X);
1173 csbi->dwCursorPosition.X = pos;
1174 if (CONSOLE_WriteChars(hCon, ptr + done, blk, &csbi->dwCursorPosition) != blk)
1175 return FALSE;
1179 return TRUE;
1183 /***********************************************************************
1184 * WriteConsoleA (KERNEL32.@)
1186 BOOL WINAPI DECLSPEC_HOTPATCH WriteConsoleA( HANDLE handle, LPCVOID buffer, DWORD length,
1187 DWORD *written, void *reserved )
1189 UINT cp = GetConsoleOutputCP();
1190 LPWSTR strW;
1191 DWORD lenW;
1192 BOOL ret;
1194 if (written) *written = 0;
1195 lenW = MultiByteToWideChar( cp, 0, buffer, length, NULL, 0 );
1196 if (!(strW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
1197 MultiByteToWideChar( cp, 0, buffer, length, strW, lenW );
1198 ret = WriteConsoleW( handle, strW, lenW, written, 0 );
1199 HeapFree( GetProcessHeap(), 0, strW );
1200 return ret;
1204 /***********************************************************************
1205 * WriteConsoleW (KERNEL32.@)
1207 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
1208 LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
1210 DWORD mode;
1211 DWORD nw = 0;
1212 const WCHAR* psz = lpBuffer;
1213 CONSOLE_SCREEN_BUFFER_INFO csbi;
1214 int k, first = 0, fd;
1216 TRACE("%p %s %d %p %p\n",
1217 hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
1218 nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
1220 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1222 if ((fd = get_console_bare_fd(hConsoleOutput)) != -1)
1224 char* ptr;
1225 unsigned len;
1226 HANDLE hFile;
1227 NTSTATUS status;
1228 IO_STATUS_BLOCK iosb;
1230 close(fd);
1231 /* FIXME: mode ENABLED_OUTPUT is not processed (or actually we rely on underlying Unix/TTY fd
1232 * to do the job
1234 len = WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0, NULL, NULL);
1235 if ((ptr = HeapAlloc(GetProcessHeap(), 0, len)) == NULL)
1236 return FALSE;
1238 WideCharToMultiByte(CP_UNIXCP, 0, lpBuffer, nNumberOfCharsToWrite, ptr, len, NULL, NULL);
1239 hFile = wine_server_ptr_handle(console_handle_unmap(hConsoleOutput));
1240 status = NtWriteFile(hFile, NULL, NULL, NULL, &iosb, ptr, len, 0, NULL);
1241 if (status == STATUS_PENDING)
1243 WaitForSingleObject(hFile, INFINITE);
1244 status = iosb.u.Status;
1247 if (status != STATUS_PENDING && lpNumberOfCharsWritten)
1249 if (iosb.Information == len)
1250 *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
1251 else
1252 FIXME("Conversion not supported yet\n");
1254 HeapFree(GetProcessHeap(), 0, ptr);
1255 if (status != STATUS_SUCCESS)
1257 SetLastError(RtlNtStatusToDosError(status));
1258 return FALSE;
1260 return TRUE;
1263 if (!GetConsoleMode(hConsoleOutput, &mode) || !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1264 return FALSE;
1266 if (!nNumberOfCharsToWrite) return TRUE;
1268 if (mode & ENABLE_PROCESSED_OUTPUT)
1270 unsigned int i;
1272 for (i = 0; i < nNumberOfCharsToWrite; i++)
1274 switch (psz[i])
1276 case '\b': case '\t': case '\n': case '\a': case '\r':
1277 /* don't handle here the i-th char... done below */
1278 if ((k = i - first) > 0)
1280 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1281 goto the_end;
1282 nw += k;
1284 first = i + 1;
1285 nw++;
1287 switch (psz[i])
1289 case '\b':
1290 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
1291 break;
1292 case '\t':
1294 static const WCHAR tmp[] = {' ',' ',' ',' ',' ',' ',' ',' '};
1295 if (!write_block(hConsoleOutput, &csbi, mode, tmp,
1296 ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
1297 goto the_end;
1299 break;
1300 case '\n':
1301 next_line(hConsoleOutput, &csbi);
1302 break;
1303 case '\a':
1304 Beep(400, 300);
1305 break;
1306 case '\r':
1307 csbi.dwCursorPosition.X = 0;
1308 break;
1309 default:
1310 break;
1315 /* write the remaining block (if any) if processed output is enabled, or the
1316 * entire buffer otherwise
1318 if ((k = nNumberOfCharsToWrite - first) > 0)
1320 if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
1321 goto the_end;
1322 nw += k;
1325 the_end:
1326 SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
1327 if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
1328 return nw != 0;
1332 /******************************************************************
1333 * CONSOLE_FillLineUniform
1335 * Helper function for ScrollConsoleScreenBufferW
1336 * Fills a part of a line with a constant character info
1338 void CONSOLE_FillLineUniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
1340 SERVER_START_REQ( fill_console_output )
1342 req->handle = console_handle_unmap(hConsoleOutput);
1343 req->mode = CHAR_INFO_MODE_TEXTATTR;
1344 req->x = i;
1345 req->y = j;
1346 req->count = len;
1347 req->wrap = FALSE;
1348 req->data.ch = lpFill->Char.UnicodeChar;
1349 req->data.attr = lpFill->Attributes;
1350 wine_server_call_err( req );
1352 SERVER_END_REQ;
1355 /******************************************************************
1356 * GetConsoleDisplayMode (KERNEL32.@)
1358 BOOL WINAPI GetConsoleDisplayMode(LPDWORD lpModeFlags)
1360 TRACE("semi-stub: %p\n", lpModeFlags);
1361 /* It is safe to successfully report windowed mode */
1362 *lpModeFlags = 0;
1363 return TRUE;
1366 /******************************************************************
1367 * SetConsoleDisplayMode (KERNEL32.@)
1369 BOOL WINAPI SetConsoleDisplayMode(HANDLE hConsoleOutput, DWORD dwFlags,
1370 COORD *lpNewScreenBufferDimensions)
1372 TRACE("(%p, %x, (%d, %d))\n", hConsoleOutput, dwFlags,
1373 lpNewScreenBufferDimensions->X, lpNewScreenBufferDimensions->Y);
1374 if (dwFlags == 1)
1376 /* We cannot switch to fullscreen */
1377 return FALSE;
1379 return TRUE;
1383 /* ====================================================================
1385 * Console manipulation functions
1387 * ====================================================================*/
1389 /* some missing functions...
1390 * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
1391 * should get the right API and implement them
1392 * SetConsoleCommandHistoryMode
1393 * SetConsoleNumberOfCommands[AW]
1395 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
1397 int len = 0;
1399 SERVER_START_REQ( get_console_input_history )
1401 req->handle = 0;
1402 req->index = idx;
1403 if (buf && buf_len > 1)
1405 wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
1407 if (!wine_server_call_err( req ))
1409 if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
1410 len = reply->total / sizeof(WCHAR) + 1;
1413 SERVER_END_REQ;
1414 return len;
1417 /******************************************************************
1418 * CONSOLE_AppendHistory
1422 BOOL CONSOLE_AppendHistory(const WCHAR* ptr)
1424 size_t len = strlenW(ptr);
1425 BOOL ret;
1427 while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
1428 if (!len) return FALSE;
1430 SERVER_START_REQ( append_console_input_history )
1432 req->handle = 0;
1433 wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
1434 ret = !wine_server_call_err( req );
1436 SERVER_END_REQ;
1437 return ret;
1440 /******************************************************************
1441 * CONSOLE_GetNumHistoryEntries
1445 unsigned CONSOLE_GetNumHistoryEntries(void)
1447 unsigned ret = -1;
1448 SERVER_START_REQ(get_console_input_info)
1450 req->handle = 0;
1451 if (!wine_server_call_err( req )) ret = reply->history_index;
1453 SERVER_END_REQ;
1454 return ret;
1457 /******************************************************************
1458 * CONSOLE_GetEditionMode
1462 BOOL CONSOLE_GetEditionMode(HANDLE hConIn, int* mode)
1464 unsigned ret = 0;
1465 SERVER_START_REQ(get_console_input_info)
1467 req->handle = console_handle_unmap(hConIn);
1468 if ((ret = !wine_server_call_err( req )))
1469 *mode = reply->edition_mode;
1471 SERVER_END_REQ;
1472 return ret;
1475 /******************************************************************
1476 * GetConsoleAliasW
1479 * RETURNS
1480 * 0 if an error occurred, non-zero for success
1483 DWORD WINAPI GetConsoleAliasW(LPWSTR lpSource, LPWSTR lpTargetBuffer,
1484 DWORD TargetBufferLength, LPWSTR lpExename)
1486 FIXME("(%s,%p,%d,%s): stub\n", debugstr_w(lpSource), lpTargetBuffer, TargetBufferLength, debugstr_w(lpExename));
1487 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1488 return 0;
1491 /******************************************************************
1492 * GetConsoleProcessList (KERNEL32.@)
1494 DWORD WINAPI GetConsoleProcessList(LPDWORD processlist, DWORD processcount)
1496 FIXME("(%p,%d): stub\n", processlist, processcount);
1498 if (!processlist || processcount < 1)
1500 SetLastError(ERROR_INVALID_PARAMETER);
1501 return 0;
1504 return 0;
1507 BOOL CONSOLE_Init(RTL_USER_PROCESS_PARAMETERS *params)
1509 memset(&S_termios, 0, sizeof(S_termios));
1510 if (params->ConsoleHandle == KERNEL32_CONSOLE_SHELL)
1512 HANDLE conin;
1514 /* FIXME: to be done even if program is a GUI ? */
1515 /* This is wine specific: we have no parent (we're started from unix)
1516 * so, create a simple console with bare handles
1518 TERM_Init();
1519 wine_server_send_fd(0);
1520 SERVER_START_REQ( alloc_console )
1522 req->access = GENERIC_READ | GENERIC_WRITE;
1523 req->attributes = OBJ_INHERIT;
1524 req->pid = 0xffffffff;
1525 req->input_fd = 0;
1526 wine_server_call( req );
1527 conin = wine_server_ptr_handle( reply->handle_in );
1528 /* reply->event shouldn't be created by server */
1530 SERVER_END_REQ;
1532 if (!params->hStdInput)
1533 params->hStdInput = conin;
1535 if (!params->hStdOutput)
1537 wine_server_send_fd(1);
1538 SERVER_START_REQ( create_console_output )
1540 req->handle_in = wine_server_obj_handle(conin);
1541 req->access = GENERIC_WRITE|GENERIC_READ;
1542 req->attributes = OBJ_INHERIT;
1543 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
1544 req->fd = 1;
1545 wine_server_call(req);
1546 params->hStdOutput = wine_server_ptr_handle(reply->handle_out);
1548 SERVER_END_REQ;
1550 if (!params->hStdError)
1552 wine_server_send_fd(2);
1553 SERVER_START_REQ( create_console_output )
1555 req->handle_in = wine_server_obj_handle(conin);
1556 req->access = GENERIC_WRITE|GENERIC_READ;
1557 req->attributes = OBJ_INHERIT;
1558 req->share = FILE_SHARE_READ|FILE_SHARE_WRITE;
1559 req->fd = 2;
1560 wine_server_call(req);
1561 params->hStdError = wine_server_ptr_handle(reply->handle_out);
1563 SERVER_END_REQ;
1567 /* convert value from server:
1568 * + INVALID_HANDLE_VALUE => TEB: 0, STARTUPINFO: INVALID_HANDLE_VALUE
1569 * + 0 => TEB: 0, STARTUPINFO: INVALID_HANDLE_VALUE
1570 * + console handle needs to be mapped
1572 if (!params->hStdInput || params->hStdInput == INVALID_HANDLE_VALUE)
1573 params->hStdInput = 0;
1574 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdInput)))
1576 params->hStdInput = console_handle_map(params->hStdInput);
1577 save_console_mode(params->hStdInput);
1580 if (!params->hStdOutput || params->hStdOutput == INVALID_HANDLE_VALUE)
1581 params->hStdOutput = 0;
1582 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdOutput)))
1583 params->hStdOutput = console_handle_map(params->hStdOutput);
1585 if (!params->hStdError || params->hStdError == INVALID_HANDLE_VALUE)
1586 params->hStdError = 0;
1587 else if (VerifyConsoleIoHandle(console_handle_map(params->hStdError)))
1588 params->hStdError = console_handle_map(params->hStdError);
1590 return TRUE;
1593 BOOL CONSOLE_Exit(void)
1595 /* the console is in raw mode, put it back in cooked mode */
1596 return restore_console_mode(GetStdHandle(STD_INPUT_HANDLE));
1599 /* Undocumented, called by native doskey.exe */
1600 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
1601 DWORD WINAPI GetConsoleCommandHistoryA(DWORD unknown1, DWORD unknown2, DWORD unknown3)
1603 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
1604 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1605 return 0;
1608 /* Undocumented, called by native doskey.exe */
1609 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
1610 DWORD WINAPI GetConsoleCommandHistoryW(DWORD unknown1, DWORD unknown2, DWORD unknown3)
1612 FIXME(": (0x%x, 0x%x, 0x%x) stub!\n", unknown1, unknown2, unknown3);
1613 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1614 return 0;
1617 /* Undocumented, called by native doskey.exe */
1618 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
1619 DWORD WINAPI GetConsoleCommandHistoryLengthA(LPCSTR unknown)
1621 FIXME(": (%s) stub!\n", debugstr_a(unknown));
1622 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1623 return 0;
1626 /* Undocumented, called by native doskey.exe */
1627 /* FIXME: Should use CONSOLE_GetHistory() above for full implementation */
1628 DWORD WINAPI GetConsoleCommandHistoryLengthW(LPCWSTR unknown)
1630 FIXME(": (%s) stub!\n", debugstr_w(unknown));
1631 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1632 return 0;
1635 DWORD WINAPI GetConsoleAliasesLengthA(LPSTR unknown)
1637 FIXME(": (%s) stub!\n", debugstr_a(unknown));
1638 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1639 return 0;
1642 DWORD WINAPI GetConsoleAliasesLengthW(LPWSTR unknown)
1644 FIXME(": (%s) stub!\n", debugstr_w(unknown));
1645 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1646 return 0;
1649 DWORD WINAPI GetConsoleAliasExesLengthA(void)
1651 FIXME(": stub!\n");
1652 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1653 return 0;
1656 DWORD WINAPI GetConsoleAliasExesLengthW(void)
1658 FIXME(": stub!\n");
1659 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1660 return 0;
1663 VOID WINAPI ExpungeConsoleCommandHistoryA(LPCSTR unknown)
1665 FIXME(": (%s) stub!\n", debugstr_a(unknown));
1666 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1669 VOID WINAPI ExpungeConsoleCommandHistoryW(LPCWSTR unknown)
1671 FIXME(": (%s) stub!\n", debugstr_w(unknown));
1672 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1675 BOOL WINAPI AddConsoleAliasA(LPSTR source, LPSTR target, LPSTR exename)
1677 FIXME(": (%s, %s, %s) stub!\n", debugstr_a(source), debugstr_a(target), debugstr_a(exename));
1678 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1679 return FALSE;
1682 BOOL WINAPI AddConsoleAliasW(LPWSTR source, LPWSTR target, LPWSTR exename)
1684 FIXME(": (%s, %s, %s) stub!\n", debugstr_w(source), debugstr_w(target), debugstr_w(exename));
1685 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1686 return FALSE;
1690 BOOL WINAPI SetConsoleIcon(HICON icon)
1692 FIXME(": (%p) stub!\n", icon);
1693 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1694 return FALSE;
1697 DWORD WINAPI GetNumberOfConsoleFonts(void)
1699 return 1;
1702 BOOL WINAPI SetConsoleFont(HANDLE hConsole, DWORD index)
1704 FIXME("(%p, %u): stub!\n", hConsole, index);
1705 SetLastError(LOWORD(E_NOTIMPL) /* win10 1709+ */);
1706 return FALSE;
1709 BOOL WINAPI SetConsoleKeyShortcuts(BOOL set, BYTE keys, VOID *a, DWORD b)
1711 FIXME(": (%u %u %p %u) stub!\n", set, keys, a, b);
1712 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1713 return FALSE;
1717 BOOL WINAPI GetCurrentConsoleFontEx(HANDLE hConsole, BOOL maxwindow, CONSOLE_FONT_INFOEX *fontinfo)
1719 BOOL ret;
1720 struct
1722 unsigned int color_map[16];
1723 WCHAR face_name[LF_FACESIZE];
1724 } data;
1726 if (fontinfo->cbSize != sizeof(CONSOLE_FONT_INFOEX))
1728 SetLastError(ERROR_INVALID_PARAMETER);
1729 return FALSE;
1732 SERVER_START_REQ(get_console_output_info)
1734 req->handle = console_handle_unmap(hConsole);
1735 wine_server_set_reply( req, &data, sizeof(data) - sizeof(WCHAR) );
1736 if ((ret = !wine_server_call_err(req)))
1738 fontinfo->nFont = 0;
1739 if (maxwindow)
1741 fontinfo->dwFontSize.X = min(reply->width, reply->max_width);
1742 fontinfo->dwFontSize.Y = min(reply->height, reply->max_height);
1744 else
1746 fontinfo->dwFontSize.X = reply->win_right - reply->win_left + 1;
1747 fontinfo->dwFontSize.Y = reply->win_bottom - reply->win_top + 1;
1749 if (wine_server_reply_size( reply ) > sizeof(data.color_map))
1751 data_size_t len = wine_server_reply_size( reply ) - sizeof(data.color_map);
1752 memcpy( fontinfo->FaceName, data.face_name, len );
1753 fontinfo->FaceName[len / sizeof(WCHAR)] = 0;
1755 else
1756 fontinfo->FaceName[0] = 0;
1757 fontinfo->FontFamily = reply->font_pitch_family;
1758 fontinfo->FontWeight = reply->font_weight;
1761 SERVER_END_REQ;
1762 return ret;
1765 BOOL WINAPI GetCurrentConsoleFont(HANDLE hConsole, BOOL maxwindow, CONSOLE_FONT_INFO *fontinfo)
1767 BOOL ret;
1768 CONSOLE_FONT_INFOEX res;
1770 res.cbSize = sizeof(CONSOLE_FONT_INFOEX);
1772 ret = GetCurrentConsoleFontEx(hConsole, maxwindow, &res);
1773 if(ret)
1775 fontinfo->nFont = res.nFont;
1776 fontinfo->dwFontSize.X = res.dwFontSize.X;
1777 fontinfo->dwFontSize.Y = res.dwFontSize.Y;
1779 return ret;
1782 static COORD get_console_font_size(HANDLE hConsole, DWORD index)
1784 COORD c = {0,0};
1786 if (index >= GetNumberOfConsoleFonts())
1788 SetLastError(ERROR_INVALID_PARAMETER);
1789 return c;
1792 SERVER_START_REQ(get_console_output_info)
1794 req->handle = console_handle_unmap(hConsole);
1795 if (!wine_server_call_err(req))
1797 c.X = reply->font_width;
1798 c.Y = reply->font_height;
1801 SERVER_END_REQ;
1802 return c;
1805 #if defined(__i386__) && !defined(__MINGW32__)
1806 #undef GetConsoleFontSize
1807 DWORD WINAPI GetConsoleFontSize(HANDLE hConsole, DWORD index)
1809 union {
1810 COORD c;
1811 DWORD w;
1812 } x;
1814 x.c = get_console_font_size(hConsole, index);
1815 return x.w;
1817 #else
1818 COORD WINAPI GetConsoleFontSize(HANDLE hConsole, DWORD index)
1820 return get_console_font_size(hConsole, index);
1822 #endif /* !defined(__i386__) */
1824 BOOL WINAPI GetConsoleFontInfo(HANDLE hConsole, BOOL maximize, DWORD numfonts, CONSOLE_FONT_INFO *info)
1826 FIXME("(%p %d %u %p): stub!\n", hConsole, maximize, numfonts, info);
1827 SetLastError(LOWORD(E_NOTIMPL) /* win10 1709+ */);
1828 return FALSE;
1831 BOOL WINAPI SetCurrentConsoleFontEx(HANDLE hConsole, BOOL maxwindow, CONSOLE_FONT_INFOEX *cfix)
1833 FIXME("(%p %d %p): stub!\n", hConsole, maxwindow, cfix);
1834 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1835 return FALSE;