Added LGPL standard comment, and copyright notices where necessary.
[wine] / win32 / console.c
1 /*
2  * Win32 kernel functions
3  *
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 Eric Pouech
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 /* Reference applications:
26  * -  IDA (interactive disassembler) full version 3.75. Works.
27  * -  LYNX/W32. Works mostly, some keys crash it.
28  */
29
30 #include "config.h"
31
32 #include <stdio.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <assert.h>
36
37 #include "winbase.h"
38 #include "winnls.h"
39 #include "winerror.h"
40 #include "wincon.h"
41 #include "heap.h"
42 #include "wine/server.h"
43 #include "wine/exception.h"
44 #include "wine/debug.h"
45 #include "options.h"
46 #include "msvcrt/excpt.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(console);
49
50 /* editline.c */
51 extern WCHAR* CONSOLE_Readline(HANDLE, int);
52
53 static WCHAR*   S_EditString /* = NULL */;
54 static unsigned S_EditStrPos /* = 0 */;
55
56 /***********************************************************************
57  *            FreeConsole (KERNEL32.@)
58  */
59 BOOL WINAPI FreeConsole(VOID)
60 {
61     BOOL ret;
62
63     SERVER_START_REQ(free_console)
64     {
65         ret = !wine_server_call_err( req );
66     }
67     SERVER_END_REQ;
68     return ret;
69 }
70
71 /******************************************************************
72  *              start_console_renderer
73  *
74  * helper for AllocConsole
75  * starts the renderer process
76  */
77 static  BOOL    start_console_renderer(void)
78 {
79     char                buffer[256];
80     int                 ret;
81     STARTUPINFOA        si;
82     PROCESS_INFORMATION pi;
83     HANDLE              hEvent = 0;
84     LPSTR               p, path = NULL;
85     OBJECT_ATTRIBUTES   attr;
86
87     attr.Length                   = sizeof(attr);
88     attr.RootDirectory            = 0;
89     attr.Attributes               = OBJ_INHERIT;
90     attr.ObjectName               = NULL;
91     attr.SecurityDescriptor       = NULL;
92     attr.SecurityQualityOfService = NULL;
93     
94     NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE);
95     if (!hEvent) return FALSE;
96
97     memset(&si, 0, sizeof(si));
98     si.cb = sizeof(si);
99
100     /* FIXME: use dynamic allocation for most of the buffers below */
101     /* first try environment variable */
102     if ((p = getenv("WINECONSOLE")) != NULL)
103     {
104         ret = snprintf(buffer, sizeof(buffer), "%s -- --use-event=%d", p, hEvent);
105         if ((ret > -1) && (ret < sizeof(buffer)) &&
106             CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
107             goto succeed;
108         ERR("Couldn't launch Wine console from WINECONSOLE env var... trying default access\n");
109     }
110
111     /* then the regular installation dir */
112     ret = snprintf(buffer, sizeof(buffer), "%s -- --use-event=%d", BINDIR "/wineconsole", hEvent);
113     if ((ret > -1) && (ret < sizeof(buffer)) &&
114         CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
115         goto succeed;
116
117     /* then try the dir where we were started from */
118     if ((path = HeapAlloc(GetProcessHeap(), 0, strlen(full_argv0) + sizeof(buffer))))
119     {
120         int     n;
121
122         if ((p = strrchr(strcpy( path, full_argv0 ), '/')))
123         {
124             p++;
125             sprintf(p, "wineconsole -- --use-event=%d", hEvent);
126             if (CreateProcessA(NULL, path, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
127                 goto succeed;
128             sprintf(p, "programs/wineconsole/wineconsole -- --use-event=%d", hEvent);
129             if (CreateProcessA(NULL, path, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
130                 goto succeed;
131         }
132
133         n = readlink(full_argv0, buffer, sizeof(buffer));
134         if (n != -1 && n < sizeof(buffer))
135         {
136             buffer[n] = 0;
137             if (buffer[0] == '/') /* absolute path ? */
138                 strcpy(path, buffer);
139             else if ((p = strrchr(strcpy( path, full_argv0 ), '/')))
140             {
141                 strcpy(p + 1, buffer);
142             }
143             else *path = 0;
144
145             if ((p = strrchr(path, '/')))
146             {
147                 p++;
148                 sprintf(p, "wineconsole -- --use-event=%d", hEvent);
149                 if (CreateProcessA(NULL, path, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
150                     goto succeed;
151                 sprintf(p, "programs/wineconsole/wineconsole -- --use-event=%d", hEvent);
152                 if (CreateProcessA(NULL, path, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
153                     goto succeed;
154             }
155         } else perror("readlink");
156
157         HeapFree(GetProcessHeap(), 0, path);    path = NULL;
158     }
159         
160     /* then try the regular PATH */
161     sprintf(buffer, "wineconsole -- --use-event=%d\n", hEvent);
162     if (CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
163         goto succeed;
164
165     goto the_end;
166
167  succeed:    
168     if (path) HeapFree(GetProcessHeap(), 0, path);
169     if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) goto the_end;
170     CloseHandle(hEvent);
171     
172     TRACE("Started wineconsole pid=%08lx tid=%08lx\n", pi.dwProcessId, pi.dwThreadId);
173
174     return TRUE;
175
176  the_end:
177     ERR("Can't allocate console\n");
178     if (path)           HeapFree(GetProcessHeap(), 0, path);
179     CloseHandle(hEvent);
180     return FALSE;
181 }
182
183 /***********************************************************************
184  *            AllocConsole (KERNEL32.@)
185  *
186  * creates an xterm with a pty to our program
187  */
188 BOOL WINAPI AllocConsole(void)
189 {
190     HANDLE              handle_in = INVALID_HANDLE_VALUE;
191     HANDLE              handle_out = INVALID_HANDLE_VALUE;
192     HANDLE              handle_err = INVALID_HANDLE_VALUE;
193     STARTUPINFOW si;
194
195     TRACE("()\n");
196
197     handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE, 
198                              0, NULL, OPEN_EXISTING, 0, 0 );
199
200     if (handle_in != INVALID_HANDLE_VALUE)
201     {
202         /* we already have a console opened on this process, don't create a new one */
203         CloseHandle(handle_in);
204         return FALSE;
205     }
206
207     if (!start_console_renderer())
208         goto the_end;
209
210     handle_in = CreateFileA( "CONIN$", GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE, 
211                              0, NULL, OPEN_EXISTING, 0, 0 );
212     if (handle_in == INVALID_HANDLE_VALUE) goto the_end;
213
214     handle_out = CreateFileA( "CONOUT$", GENERIC_READ|GENERIC_WRITE, 
215                              0, NULL, OPEN_EXISTING, 0, 0 );
216     if (handle_out == INVALID_HANDLE_VALUE) goto the_end;
217
218     if (!DuplicateHandle(GetCurrentProcess(), handle_out, GetCurrentProcess(), &handle_err,
219                          0, TRUE, DUPLICATE_SAME_ACCESS))
220         goto the_end;
221     
222     /* NT resets the STD_*_HANDLEs on console alloc */
223     SetStdHandle(STD_INPUT_HANDLE,  handle_in);
224     SetStdHandle(STD_OUTPUT_HANDLE, handle_out);
225     SetStdHandle(STD_ERROR_HANDLE,  handle_err);
226
227     GetStartupInfoW(&si);
228     if (si.dwFlags & STARTF_USESIZE)
229     {
230         COORD   c;
231         c.X = si.dwXCountChars;
232         c.Y = si.dwYCountChars;
233         SetConsoleScreenBufferSize(handle_out, c);
234     }
235     if (si.dwFlags & STARTF_USEFILLATTRIBUTE)
236         SetConsoleTextAttribute(handle_out, si.dwFillAttribute);
237     if (si.lpTitle)
238         SetConsoleTitleW(si.lpTitle);
239
240     SetLastError(ERROR_SUCCESS);
241
242     return TRUE;
243
244  the_end:
245     ERR("Can't allocate console\n");
246     if (handle_in != INVALID_HANDLE_VALUE)      CloseHandle(handle_in);
247     if (handle_out != INVALID_HANDLE_VALUE)     CloseHandle(handle_out);
248     if (handle_err != INVALID_HANDLE_VALUE)     CloseHandle(handle_err);
249     FreeConsole();
250     return FALSE;
251 }
252
253
254 /******************************************************************************
255  * read_console_input
256  *
257  * Helper function for ReadConsole, ReadConsoleInput and PeekConsoleInput
258  */
259 static BOOL read_console_input(HANDLE handle, LPINPUT_RECORD buffer, DWORD count,
260                                LPDWORD pRead, BOOL flush)
261 {
262     BOOL        ret;
263     unsigned    read = 0;
264     DWORD       mode;
265
266     SERVER_START_REQ( read_console_input )
267     {
268         req->handle = handle;
269         req->flush = flush;
270         wine_server_set_reply( req, buffer, count * sizeof(INPUT_RECORD) );
271         if ((ret = !wine_server_call_err( req ))) read = reply->read;
272     }
273     SERVER_END_REQ;
274     if (count && flush && GetConsoleMode(handle, &mode) && (mode & ENABLE_PROCESSED_INPUT))
275     {
276         int     i;
277
278         for (i = 0; i < read; i++)
279         {
280             if (buffer[i].EventType == KEY_EVENT && buffer[i].Event.KeyEvent.bKeyDown &&
281                 buffer[i].Event.KeyEvent.uChar.UnicodeChar == 'C' - 64 &&
282                 !(buffer[i].Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
283             {
284                 GenerateConsoleCtrlEvent(CTRL_C_EVENT, GetCurrentProcessId());
285                 /* FIXME: this is hackish, but it easily disables IR handling afterwards */
286                 buffer[i].Event.KeyEvent.uChar.UnicodeChar = 0;
287             }
288         }
289     }
290     if (pRead) *pRead = read;
291     return ret;
292 }
293
294
295 /***********************************************************************
296  *            ReadConsoleA   (KERNEL32.@)
297  */
298 BOOL WINAPI ReadConsoleA(HANDLE hConsoleInput, LPVOID lpBuffer, DWORD nNumberOfCharsToRead,
299                          LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
300 {
301     LPWSTR      ptr = HeapAlloc(GetProcessHeap(), 0, nNumberOfCharsToRead * sizeof(WCHAR));
302     DWORD       ncr = 0;
303     BOOL        ret;
304
305     if ((ret = ReadConsoleW(hConsoleInput, ptr, nNumberOfCharsToRead, &ncr, 0)))
306         ncr = WideCharToMultiByte(CP_ACP, 0, ptr, ncr, lpBuffer, nNumberOfCharsToRead, NULL, NULL);
307
308     if (lpNumberOfCharsRead) *lpNumberOfCharsRead = ncr;
309     HeapFree(GetProcessHeap(), 0, ptr);
310
311     return ret;
312 }
313
314 /***********************************************************************
315  *            ReadConsoleW   (KERNEL32.@)
316  */
317 BOOL WINAPI ReadConsoleW(HANDLE hConsoleInput, LPVOID lpBuffer,
318                          DWORD nNumberOfCharsToRead, LPDWORD lpNumberOfCharsRead, LPVOID lpReserved)
319 {
320     DWORD       charsread;
321     LPWSTR      xbuf = (LPWSTR)lpBuffer;
322     DWORD       mode;
323     
324     TRACE("(%d,%p,%ld,%p,%p)\n",
325           hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, lpReserved);
326     
327     if (!GetConsoleMode(hConsoleInput, &mode))
328         return FALSE;
329     
330     if (mode & ENABLE_LINE_INPUT)
331     {
332         if (!S_EditString || S_EditString[S_EditStrPos] == 0)
333         {
334             if (S_EditString) HeapFree(GetProcessHeap(), 0, S_EditString);
335             if (!(S_EditString = CONSOLE_Readline(hConsoleInput, mode & WINE_ENABLE_LINE_INPUT_EMACS)))
336                 return FALSE;
337             S_EditStrPos = 0;
338         }
339         charsread = lstrlenW(&S_EditString[S_EditStrPos]);
340         if (charsread > nNumberOfCharsToRead) charsread = nNumberOfCharsToRead;
341         memcpy(xbuf, &S_EditString[S_EditStrPos], charsread * sizeof(WCHAR));
342         S_EditStrPos += charsread;
343     }
344     else
345     {
346         INPUT_RECORD    ir;
347         DWORD           count;
348         
349         /* FIXME: should we read at least 1 char? The SDK does not say */
350         /* wait for at least one available input record (it doesn't mean we'll have
351          * chars stored in xbuf...
352          */
353         WaitForSingleObject(hConsoleInput, INFINITE);
354         for (charsread = 0; charsread < nNumberOfCharsToRead;)
355         {
356             if (!read_console_input(hConsoleInput, &ir, 1, &count, TRUE)) return FALSE;
357             if (count && ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
358                 ir.Event.KeyEvent.uChar.UnicodeChar &&
359                 !(ir.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
360             {
361                 xbuf[charsread++] = ir.Event.KeyEvent.uChar.UnicodeChar;
362             }
363         }
364     }
365
366     if (lpNumberOfCharsRead) *lpNumberOfCharsRead = charsread;
367
368     return TRUE;
369 }
370
371
372 /***********************************************************************
373  *            ReadConsoleInputW   (KERNEL32.@)
374  */
375 BOOL WINAPI ReadConsoleInputW(HANDLE hConsoleInput, LPINPUT_RECORD lpBuffer,
376                               DWORD nLength, LPDWORD lpNumberOfEventsRead)
377 {
378     DWORD count;
379         
380     if (!nLength)
381     {
382         if (lpNumberOfEventsRead) *lpNumberOfEventsRead = 0;
383         return TRUE;
384     }
385     
386     /* loop until we get at least one event */
387     for (;;)
388     {
389         WaitForSingleObject(hConsoleInput, INFINITE);
390         if (!read_console_input(hConsoleInput, lpBuffer, nLength, &count, TRUE))
391             return FALSE;
392         if (count)
393         {
394             if (lpNumberOfEventsRead) *lpNumberOfEventsRead = count;
395             return TRUE;
396         }
397     }
398 }
399
400
401 /******************************************************************************
402  * WriteConsoleOutputCharacterW [KERNEL32.@]  Copies character to consecutive
403  *                                            cells in the console screen buffer
404  *
405  * PARAMS
406  *    hConsoleOutput    [I] Handle to screen buffer
407  *    str               [I] Pointer to buffer with chars to write
408  *    length            [I] Number of cells to write to
409  *    coord             [I] Coords of first cell
410  *    lpNumCharsWritten [O] Pointer to number of cells written
411  *
412  * RETURNS
413  *    Success: TRUE
414  *    Failure: FALSE
415  * 
416  */
417 BOOL WINAPI WriteConsoleOutputCharacterW( HANDLE hConsoleOutput, LPCWSTR str, DWORD length,
418                                           COORD coord, LPDWORD lpNumCharsWritten )
419 {
420     BOOL ret;
421
422     TRACE("(%d,%s,%ld,%dx%d,%p)\n", hConsoleOutput,
423           debugstr_wn(str, length), length, coord.X, coord.Y, lpNumCharsWritten);
424
425     SERVER_START_REQ( write_console_output )
426     {
427         req->handle = hConsoleOutput;
428         req->x      = coord.X;
429         req->y      = coord.Y;
430         req->mode   = CHAR_INFO_MODE_TEXT;
431         req->wrap   = TRUE;
432         wine_server_add_data( req, str, length * sizeof(WCHAR) );
433         if ((ret = !wine_server_call_err( req )))
434         {
435             if (lpNumCharsWritten) *lpNumCharsWritten = reply->written;
436         }
437     }
438     SERVER_END_REQ;
439     return ret;
440 }
441
442
443 /******************************************************************************
444  * SetConsoleTitleW [KERNEL32.@]  Sets title bar string for console
445  *
446  * PARAMS
447  *    title [I] Address of new title
448  *
449  * RETURNS
450  *    Success: TRUE
451  *    Failure: FALSE
452  */
453 BOOL WINAPI SetConsoleTitleW(LPCWSTR title)
454 {
455     BOOL ret;
456
457     SERVER_START_REQ( set_console_input_info )
458     {
459         req->handle = 0;
460         req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
461         wine_server_add_data( req, title, strlenW(title) * sizeof(WCHAR) );
462         ret = !wine_server_call_err( req );
463     }
464     SERVER_END_REQ;
465     return ret;
466 }
467
468
469 /***********************************************************************
470  *            GetNumberOfConsoleMouseButtons   (KERNEL32.@)
471  */
472 BOOL WINAPI GetNumberOfConsoleMouseButtons(LPDWORD nrofbuttons)
473 {
474     FIXME("(%p): stub\n", nrofbuttons);
475     *nrofbuttons = 2;
476     return TRUE;
477 }
478
479 /******************************************************************************
480  *  SetConsoleInputExeNameW      [KERNEL32.@]
481  * 
482  * BUGS
483  *   Unimplemented
484  */
485 BOOL WINAPI SetConsoleInputExeNameW(LPCWSTR name)
486 {
487     FIXME("(%s): stub!\n", debugstr_w(name));
488
489     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
490     return TRUE;
491 }
492
493 /******************************************************************************
494  *  SetConsoleInputExeNameA      [KERNEL32.@]
495  * 
496  * BUGS
497  *   Unimplemented
498  */
499 BOOL WINAPI SetConsoleInputExeNameA(LPCSTR name)
500 {
501     int         len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
502     LPWSTR      xptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
503     BOOL        ret;
504
505     if (!xptr) return FALSE;
506
507     MultiByteToWideChar(CP_ACP, 0, name, -1, xptr, len);
508     ret = SetConsoleInputExeNameW(xptr);
509     HeapFree(GetProcessHeap(), 0, xptr);
510
511     return ret;
512 }
513
514 static BOOL WINAPI CONSOLE_DefaultHandler(DWORD dwCtrlType)
515 {
516     FIXME("Terminating process %lx on event %lx\n", GetCurrentProcessId(), dwCtrlType);
517     ExitProcess(0);
518     /* should never go here */
519     return TRUE;
520 }
521
522 /******************************************************************************
523  * SetConsoleCtrlHandler [KERNEL32.@]  Adds function to calling process list
524  *
525  * PARAMS
526  *    func [I] Address of handler function
527  *    add  [I] Handler to add or remove
528  *
529  * RETURNS
530  *    Success: TRUE
531  *    Failure: FALSE
532  *
533  * CHANGED
534  * James Sutherland (JamesSutherland@gmx.de)
535  * Added global variables console_ignore_ctrl_c and handlers[]
536  * Does not yet do any error checking, or set LastError if failed.
537  * This doesn't yet matter, since these handlers are not yet called...!
538  */
539
540 static unsigned int console_ignore_ctrl_c = 0; /* FIXME: this should be inherited somehow */
541 static PHANDLER_ROUTINE handlers[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,CONSOLE_DefaultHandler};
542
543 /*****************************************************************************/
544
545 BOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE func, BOOL add)
546 {
547     int alloc_loop = sizeof(handlers)/sizeof(handlers[0]) - 1;
548     
549     FIXME("(%p,%i) - no error checking or testing yet\n", func, add);
550     
551     if (!func)
552     {
553         console_ignore_ctrl_c = add;
554         return TRUE;
555     }
556     if (add)
557     {
558         for (; alloc_loop >= 0 && handlers[alloc_loop]; alloc_loop--);
559         if (alloc_loop <= 0)
560         {
561             FIXME("Out of space on CtrlHandler table\n");
562             return FALSE;
563         }
564         handlers[alloc_loop] = func;
565     }
566     else
567     {
568         for (; alloc_loop >= 0 && handlers[alloc_loop] != func; alloc_loop--);
569         if (alloc_loop <= 0)
570         {
571             WARN("Attempt to remove non-installed CtrlHandler %p\n", func);
572             return FALSE;
573         }
574         /* sanity check */
575         if (alloc_loop == sizeof(handlers)/sizeof(handlers[0]) - 1)
576         {
577             ERR("Who's trying to remove default handler???\n");
578             return FALSE;
579         }
580         if (alloc_loop)
581             memmove(&handlers[1], &handlers[0], alloc_loop * sizeof(handlers[0]));
582         handlers[0] = 0;
583     }
584     return TRUE;
585 }
586
587 static WINE_EXCEPTION_FILTER(CONSOLE_CtrlEventHandler)
588 {
589     TRACE("(%lx)\n", GetExceptionCode());
590     return EXCEPTION_EXECUTE_HANDLER;
591 }
592
593 /******************************************************************************
594  * GenerateConsoleCtrlEvent [KERNEL32.@] Simulate a CTRL-C or CTRL-BREAK
595  *
596  * PARAMS
597  *    dwCtrlEvent        [I] Type of event
598  *    dwProcessGroupID   [I] Process group ID to send event to
599  *
600  * NOTES
601  *    Doesn't yet work...!
602  *
603  * RETURNS
604  *    Success: True
605  *    Failure: False (and *should* [but doesn't] set LastError)
606  */
607 BOOL WINAPI GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,
608                                      DWORD dwProcessGroupID)
609 {
610     if (dwCtrlEvent != CTRL_C_EVENT && dwCtrlEvent != CTRL_BREAK_EVENT)
611     {
612         ERR("invalid event %ld for PGID %ld\n", dwCtrlEvent, dwProcessGroupID);
613         return FALSE;
614     }
615
616     if (dwProcessGroupID == GetCurrentProcessId() || dwProcessGroupID == 0)
617     {
618         int     i;
619         
620         FIXME("Attempt to send event %ld to self groupID, doing locally only\n", dwCtrlEvent);
621         
622         /* this is only meaningfull when done locally, otherwise it will have to be done on
623          * the 'receive' side of the event generation
624          */
625         if (dwCtrlEvent == CTRL_C_EVENT && console_ignore_ctrl_c)
626             return TRUE;
627
628         /* try to pass the exception to the debugger
629          * if it continues, there's nothing more to do
630          * otherwise, we need to send the ctrl-event to the handlers
631          */
632         __TRY
633         {
634             RaiseException( (dwCtrlEvent == CTRL_C_EVENT) ? DBG_CONTROL_C : DBG_CONTROL_BREAK,
635                             0, 0, NULL);
636         }
637         __EXCEPT(CONSOLE_CtrlEventHandler)
638         {
639             /* the debugger didn't continue... so, pass to ctrl handlers */
640             for (i = 0; i < sizeof(handlers)/sizeof(handlers[0]); i++)
641             {
642                 if (handlers[i] && (handlers[i])(dwCtrlEvent)) break;
643             }
644         }
645         __ENDTRY;
646         return TRUE;
647     }
648     FIXME("event %ld to external PGID %ld - not implemented yet\n", dwCtrlEvent, dwProcessGroupID);
649     return FALSE;
650 }
651
652
653 /******************************************************************************
654  * CreateConsoleScreenBuffer [KERNEL32.@]  Creates a console screen buffer
655  *
656  * PARAMS
657  *    dwDesiredAccess    [I] Access flag
658  *    dwShareMode        [I] Buffer share mode
659  *    sa                 [I] Security attributes
660  *    dwFlags            [I] Type of buffer to create
661  *    lpScreenBufferData [I] Reserved
662  *
663  * NOTES
664  *    Should call SetLastError
665  *
666  * RETURNS
667  *    Success: Handle to new console screen buffer
668  *    Failure: INVALID_HANDLE_VALUE
669  */
670 HANDLE WINAPI CreateConsoleScreenBuffer(DWORD dwDesiredAccess, DWORD dwShareMode, 
671                                         LPSECURITY_ATTRIBUTES sa, DWORD dwFlags, 
672                                         LPVOID lpScreenBufferData)
673 {
674     HANDLE      ret = INVALID_HANDLE_VALUE;
675     
676     TRACE("(%ld,%ld,%p,%ld,%p)\n", 
677           dwDesiredAccess, dwShareMode, sa, dwFlags, lpScreenBufferData);
678     
679     if (dwFlags != CONSOLE_TEXTMODE_BUFFER || lpScreenBufferData != NULL)
680     {
681         SetLastError(ERROR_INVALID_PARAMETER);
682         return INVALID_HANDLE_VALUE;
683     }
684     
685     SERVER_START_REQ(create_console_output)
686     {
687         req->handle_in = 0;
688         req->access    = dwDesiredAccess;
689         req->share     = dwShareMode;
690         req->inherit   = (sa && sa->bInheritHandle);
691         if (!wine_server_call_err( req )) ret = reply->handle_out;
692     }
693     SERVER_END_REQ;
694     
695     return ret;
696 }
697
698
699 /***********************************************************************
700  *           GetConsoleScreenBufferInfo   (KERNEL32.@)
701  */
702 BOOL WINAPI GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, LPCONSOLE_SCREEN_BUFFER_INFO csbi)
703 {
704     BOOL        ret;
705
706     SERVER_START_REQ(get_console_output_info)
707     {
708         req->handle = hConsoleOutput;
709         if ((ret = !wine_server_call_err( req )))
710         {
711             csbi->dwSize.X              = reply->width;
712             csbi->dwSize.Y              = reply->height;
713             csbi->dwCursorPosition.X    = reply->cursor_x;
714             csbi->dwCursorPosition.Y    = reply->cursor_y;
715             csbi->wAttributes           = reply->attr;
716             csbi->srWindow.Left         = reply->win_left;
717             csbi->srWindow.Right        = reply->win_right;
718             csbi->srWindow.Top          = reply->win_top;
719             csbi->srWindow.Bottom       = reply->win_bottom;
720             csbi->dwMaximumWindowSize.X = reply->max_width;
721             csbi->dwMaximumWindowSize.Y = reply->max_height;
722         }
723     }
724     SERVER_END_REQ;
725
726     return ret;
727 }
728
729
730 /******************************************************************************
731  * SetConsoleActiveScreenBuffer [KERNEL32.@]  Sets buffer to current console
732  *
733  * RETURNS
734  *    Success: TRUE
735  *    Failure: FALSE
736  */
737 BOOL WINAPI SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput)
738 {
739     BOOL ret;
740
741     TRACE("(%x)\n", hConsoleOutput);
742
743     SERVER_START_REQ( set_console_input_info )
744     {
745         req->handle    = 0;
746         req->mask      = SET_CONSOLE_INPUT_INFO_ACTIVE_SB;
747         req->active_sb = hConsoleOutput;
748         ret = !wine_server_call_err( req );
749     }
750     SERVER_END_REQ;
751     return ret;
752 }
753
754
755 /***********************************************************************
756  *            GetConsoleMode   (KERNEL32.@)
757  */
758 BOOL WINAPI GetConsoleMode(HANDLE hcon, LPDWORD mode)
759 {
760     BOOL ret;
761     
762     SERVER_START_REQ(get_console_mode)
763     {
764         req->handle = hcon;
765         ret = !wine_server_call_err( req );
766         if (ret && mode) *mode = reply->mode;
767     }
768     SERVER_END_REQ;
769     return ret;
770 }
771
772
773 /******************************************************************************
774  * SetConsoleMode [KERNEL32.@]  Sets input mode of console's input buffer
775  *
776  * PARAMS
777  *    hcon [I] Handle to console input or screen buffer
778  *    mode [I] Input or output mode to set
779  *
780  * RETURNS
781  *    Success: TRUE
782  *    Failure: FALSE
783  */
784 BOOL WINAPI SetConsoleMode(HANDLE hcon, DWORD mode)
785 {
786     BOOL ret;
787     
788     TRACE("(%x,%lx)\n", hcon, mode);
789     
790     SERVER_START_REQ(set_console_mode)
791     {
792         req->handle = hcon;
793         req->mode = mode;
794         ret = !wine_server_call_err( req );
795     }
796     SERVER_END_REQ;
797     /* FIXME: when resetting a console input to editline mode, I think we should
798      * empty the S_EditString buffer
799      */
800     return ret;
801 }
802
803
804 /******************************************************************
805  *              write_char
806  *
807  * WriteConsoleOutput helper: hides server call semantics
808  */
809 static int write_char(HANDLE hCon, LPCWSTR lpBuffer, int nc, COORD* pos)
810 {
811     int written = -1;
812
813     if (!nc) return 0;
814
815     SERVER_START_REQ( write_console_output )
816     {
817         req->handle = hCon;
818         req->x      = pos->X;
819         req->y      = pos->Y;
820         req->mode   = CHAR_INFO_MODE_TEXTSTDATTR;
821         req->wrap   = FALSE;
822         wine_server_add_data( req, lpBuffer, nc * sizeof(WCHAR) );
823         if (!wine_server_call_err( req )) written = reply->written;
824     }
825     SERVER_END_REQ;
826
827     if (written > 0) pos->X += written;
828     return written;
829 }
830
831 /******************************************************************
832  *              next_line
833  *
834  * WriteConsoleOutput helper: handles passing to next line (+scrolling if necessary)
835  *
836  */
837 static int      next_line(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi)
838 {
839     SMALL_RECT  src; 
840     CHAR_INFO   ci;
841     COORD       dst;
842
843     csbi->dwCursorPosition.X = 0;
844     csbi->dwCursorPosition.Y++;
845
846     if (csbi->dwCursorPosition.Y < csbi->dwSize.Y) return 1;
847
848     src.Top    = 1; 
849     src.Bottom = csbi->dwSize.Y - 1; 
850     src.Left   = 0; 
851     src.Right  = csbi->dwSize.X - 1; 
852     
853     dst.X      = 0; 
854     dst.Y      = 0;
855         
856     ci.Attributes = csbi->wAttributes;
857     ci.Char.UnicodeChar = ' '; 
858     
859     csbi->dwCursorPosition.Y--;
860     if (!ScrollConsoleScreenBufferW(hCon, &src, NULL, dst, &ci))
861         return 0;
862     return 1;
863 }
864
865 /******************************************************************
866  *              write_block
867  *
868  * WriteConsoleOutput helper: writes a block of non special characters
869  *
870  */
871 static int      write_block(HANDLE hCon, CONSOLE_SCREEN_BUFFER_INFO* csbi,
872                             DWORD mode, LPWSTR ptr, int len)
873 {
874     int blk;    /* number of chars to write on first line */
875
876     if (len <= 0) return 1;
877
878     blk = min(len, csbi->dwSize.X - csbi->dwCursorPosition.X);
879
880     if (write_char(hCon, ptr, blk, &csbi->dwCursorPosition) != blk)
881         return 0;
882
883     if (blk < len) /* special handling for right border */
884     {
885         if (mode & ENABLE_WRAP_AT_EOL_OUTPUT) /* writes remaining on next line */
886         {
887             if (!next_line(hCon, csbi) ||
888                 write_char(hCon, ptr + blk, len - blk, &csbi->dwCursorPosition) != len - blk)
889                 return 0;
890         }
891         else /* all remaining chars should be written on last column, so only write the last one */
892         {
893             csbi->dwCursorPosition.X = csbi->dwSize.X - 1;
894             if (write_char(hCon, ptr + len - 1, 1, &csbi->dwCursorPosition) != 1)
895                 return 0;
896             csbi->dwCursorPosition.X = csbi->dwSize.X - 1;
897         }
898     }
899     return 1;
900 }   
901
902 /***********************************************************************
903  *            WriteConsoleW   (KERNEL32.@)
904  */
905 BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
906                           LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
907 {
908     DWORD                       mode;
909     DWORD                       nw = 0;
910     WCHAR*                      psz = (WCHAR*)lpBuffer;
911     CONSOLE_SCREEN_BUFFER_INFO  csbi;
912     int                         k, first = 0;
913     
914     TRACE("%d %s %ld %p %p\n", 
915           hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
916           nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
917     
918     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
919     
920     if (!GetConsoleMode(hConsoleOutput, &mode) || 
921         !GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
922         return FALSE;
923     
924     if (mode & ENABLE_PROCESSED_OUTPUT)
925     {
926         int     i;
927         
928         for (i = 0; i < nNumberOfCharsToWrite; i++)
929         {
930             switch (psz[i])
931             {
932             case '\b': case '\t': case '\n': case '\a': case '\r':
933                 /* don't handle here the i-th char... done below */
934                 if ((k = i - first) > 0)
935                 {
936                     if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
937                         goto the_end;
938                     nw += k;
939                 }
940                 first = i + 1;
941                 nw++;
942             }
943             switch (psz[i])
944             {
945             case '\b':
946                 if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
947                 break;
948             case '\t':
949                 {
950                     WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};
951                     
952                     if (!write_block(hConsoleOutput, &csbi, mode, tmp, 
953                                      ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
954                         goto the_end;
955                 }
956                 break;
957             case '\n':
958                 next_line(hConsoleOutput, &csbi);
959                 break;
960             case '\a':
961                 Beep(400, 300);
962                 break; 
963             case '\r':
964                 csbi.dwCursorPosition.X = 0;
965                 break;
966             default:
967                 break;
968             }
969         }
970     }
971     
972     /* write the remaining block (if any) if processed output is enabled, or the
973      * entire buffer otherwise
974      */
975     if ((k = nNumberOfCharsToWrite - first) > 0)
976     {
977         if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
978             goto the_end;
979         nw += k;
980     }
981     
982  the_end:
983     SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
984     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
985     return nw != 0;
986 }
987
988
989 /***********************************************************************
990  *            WriteConsoleA   (KERNEL32.@)
991  */
992 BOOL WINAPI WriteConsoleA(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
993                           LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
994 {
995     BOOL        ret;
996     LPWSTR      xstring;
997     DWORD       n;
998     
999     n = MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0);
1000     
1001     if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;
1002     xstring = HeapAlloc(GetProcessHeap(), 0, n * sizeof(WCHAR));
1003     if (!xstring) return 0;
1004     
1005     MultiByteToWideChar(CP_ACP, 0, lpBuffer, nNumberOfCharsToWrite, xstring, n);
1006     
1007     ret = WriteConsoleW(hConsoleOutput, xstring, n, lpNumberOfCharsWritten, 0);
1008     
1009     HeapFree(GetProcessHeap(), 0, xstring);
1010     
1011     return ret;
1012 }
1013
1014 /******************************************************************************
1015  * SetConsoleCursorPosition [KERNEL32.@]
1016  * Sets the cursor position in console
1017  *
1018  * PARAMS
1019  *    hConsoleOutput   [I] Handle of console screen buffer
1020  *    dwCursorPosition [I] New cursor position coordinates
1021  *
1022  * RETURNS STD
1023  */
1024 BOOL WINAPI SetConsoleCursorPosition(HANDLE hcon, COORD pos)
1025 {
1026     BOOL                        ret;
1027     CONSOLE_SCREEN_BUFFER_INFO  csbi;
1028     int                         do_move = 0;
1029     int                         w, h;
1030
1031     TRACE("%x %d %d\n", hcon, pos.X, pos.Y);
1032
1033     SERVER_START_REQ(set_console_output_info)
1034     {
1035         req->handle         = hcon;
1036         req->cursor_x       = pos.X;
1037         req->cursor_y       = pos.Y;
1038         req->mask           = SET_CONSOLE_OUTPUT_INFO_CURSOR_POS;
1039         ret = !wine_server_call_err( req );
1040     }
1041     SERVER_END_REQ;
1042
1043     if (!ret || !GetConsoleScreenBufferInfo(hcon, &csbi))
1044         return FALSE;
1045
1046     /* if cursor is no longer visible, scroll the visible window... */
1047     w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
1048     h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1049     if (pos.X < csbi.srWindow.Left)
1050     {
1051         csbi.srWindow.Left   = min(pos.X, csbi.dwSize.X - w);
1052         do_move++;
1053     } 
1054     else if (pos.X > csbi.srWindow.Right)
1055     {
1056         csbi.srWindow.Left   = max(pos.X, w) - w + 1;
1057         do_move++;
1058     }
1059     csbi.srWindow.Right  = csbi.srWindow.Left + w - 1;
1060
1061     if (pos.Y < csbi.srWindow.Top)
1062     {
1063         csbi.srWindow.Top    = min(pos.Y, csbi.dwSize.Y - h);
1064         do_move++;
1065     }
1066     else if (pos.Y > csbi.srWindow.Bottom)
1067     {
1068         csbi.srWindow.Top   = max(pos.Y, h) - h + 1;
1069         do_move++;
1070     }
1071     csbi.srWindow.Bottom = csbi.srWindow.Top + h - 1;
1072
1073     ret = (do_move) ? SetConsoleWindowInfo(hcon, TRUE, &csbi.srWindow) : TRUE;
1074
1075     return ret;
1076 }
1077
1078 /******************************************************************************
1079  * GetConsoleCursorInfo [KERNEL32.@]  Gets size and visibility of console
1080  *
1081  * PARAMS
1082  *    hcon  [I] Handle to console screen buffer
1083  *    cinfo [O] Address of cursor information
1084  *
1085  * RETURNS
1086  *    Success: TRUE
1087  *    Failure: FALSE
1088  */
1089 BOOL WINAPI GetConsoleCursorInfo(HANDLE hcon, LPCONSOLE_CURSOR_INFO cinfo)
1090 {
1091     BOOL ret;
1092
1093     SERVER_START_REQ(get_console_output_info)
1094     {
1095         req->handle = hcon;
1096         ret = !wine_server_call_err( req );
1097         if (ret && cinfo)
1098         {
1099             cinfo->dwSize = reply->cursor_size;
1100             cinfo->bVisible = reply->cursor_visible;
1101         }
1102     }
1103     SERVER_END_REQ;
1104     return ret;
1105 }
1106
1107
1108 /******************************************************************************
1109  * SetConsoleCursorInfo [KERNEL32.@]  Sets size and visibility of cursor
1110  *
1111  * PARAMS
1112  *      hcon    [I] Handle to console screen buffer
1113  *      cinfo   [I] Address of cursor information
1114  * RETURNS
1115  *    Success: TRUE
1116  *    Failure: FALSE
1117  */
1118 BOOL WINAPI SetConsoleCursorInfo(HANDLE hCon, LPCONSOLE_CURSOR_INFO cinfo)
1119 {
1120     BOOL ret;
1121
1122     SERVER_START_REQ(set_console_output_info)
1123     {
1124         req->handle         = hCon;
1125         req->cursor_size    = cinfo->dwSize;
1126         req->cursor_visible = cinfo->bVisible;
1127         req->mask           = SET_CONSOLE_OUTPUT_INFO_CURSOR_GEOM;
1128         ret = !wine_server_call_err( req );
1129     }
1130     SERVER_END_REQ;
1131     return ret;
1132 }
1133
1134
1135 /******************************************************************************
1136  * SetConsoleWindowInfo [KERNEL32.@]  Sets size and position of console
1137  *
1138  * PARAMS
1139  *      hcon            [I] Handle to console screen buffer
1140  *      bAbsolute       [I] Coordinate type flag
1141  *      window          [I] Address of new window rectangle
1142  * RETURNS
1143  *    Success: TRUE
1144  *    Failure: FALSE
1145  */
1146 BOOL WINAPI SetConsoleWindowInfo(HANDLE hCon, BOOL bAbsolute, LPSMALL_RECT window)
1147 {
1148     SMALL_RECT  p = *window;
1149     BOOL        ret;
1150
1151     if (!bAbsolute)
1152     {
1153         CONSOLE_SCREEN_BUFFER_INFO      csbi;
1154         if (!GetConsoleScreenBufferInfo(hCon, &csbi))
1155             return FALSE;
1156         p.Left   += csbi.srWindow.Left;
1157         p.Top    += csbi.srWindow.Top;
1158         p.Right  += csbi.srWindow.Left;
1159         p.Bottom += csbi.srWindow.Top;
1160     }
1161     SERVER_START_REQ(set_console_output_info)
1162     {
1163         req->handle         = hCon;
1164         req->win_left       = p.Left;
1165         req->win_top        = p.Top;
1166         req->win_right      = p.Right;
1167         req->win_bottom     = p.Bottom;
1168         req->mask           = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
1169         ret = !wine_server_call_err( req );
1170     }
1171     SERVER_END_REQ;
1172
1173     return ret;
1174 }
1175
1176
1177 /******************************************************************************
1178  * SetConsoleTextAttribute [KERNEL32.@]  Sets colors for text
1179  *
1180  * Sets the foreground and background color attributes of characters
1181  * written to the screen buffer.
1182  *
1183  * RETURNS
1184  *    Success: TRUE
1185  *    Failure: FALSE
1186  */
1187 BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttr)
1188 {
1189     BOOL ret;
1190
1191     SERVER_START_REQ(set_console_output_info)
1192     {
1193         req->handle = hConsoleOutput;
1194         req->attr   = wAttr;
1195         req->mask   = SET_CONSOLE_OUTPUT_INFO_ATTR;
1196         ret = !wine_server_call_err( req );
1197     }
1198     SERVER_END_REQ;
1199     return ret;
1200 }
1201
1202
1203 /******************************************************************************
1204  * SetConsoleScreenBufferSize [KERNEL32.@]  Changes size of console 
1205  *
1206  * PARAMS
1207  *    hConsoleOutput [I] Handle to console screen buffer
1208  *    dwSize         [I] New size in character rows and cols
1209  *
1210  * RETURNS
1211  *    Success: TRUE
1212  *    Failure: FALSE
1213  */
1214 BOOL WINAPI SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD dwSize)
1215 {
1216     BOOL ret;
1217
1218     SERVER_START_REQ(set_console_output_info)
1219     {
1220         req->handle = hConsoleOutput;
1221         req->width  = dwSize.X;
1222         req->height = dwSize.Y;
1223         req->mask   = SET_CONSOLE_OUTPUT_INFO_SIZE;
1224         ret = !wine_server_call_err( req );
1225     }
1226     SERVER_END_REQ;
1227     return ret;
1228 }
1229
1230
1231 /******************************************************************************
1232  * ScrollConsoleScreenBufferA [KERNEL32.@]
1233  * 
1234  */
1235 BOOL WINAPI ScrollConsoleScreenBufferA(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect, 
1236                                        LPSMALL_RECT lpClipRect, COORD dwDestOrigin, 
1237                                        LPCHAR_INFO lpFill)
1238 {
1239     CHAR_INFO   ciw;
1240     
1241     ciw.Attributes = lpFill->Attributes;
1242     MultiByteToWideChar(CP_ACP, 0, &lpFill->Char.AsciiChar, 1, &ciw.Char.UnicodeChar, 1);
1243     
1244     return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRect, lpClipRect, 
1245                                       dwDestOrigin, &ciw);
1246 }
1247
1248 /******************************************************************
1249  *              fill_line_uniform
1250  *
1251  * Helper function for ScrollConsoleScreenBufferW
1252  * Fills a part of a line with a constant character info
1253  */
1254 static void fill_line_uniform(HANDLE hConsoleOutput, int i, int j, int len, LPCHAR_INFO lpFill)
1255 {
1256     SERVER_START_REQ( fill_console_output )
1257     {
1258         req->handle    = hConsoleOutput;
1259         req->mode      = CHAR_INFO_MODE_TEXTATTR;
1260         req->x         = i;
1261         req->y         = j;
1262         req->count     = len;
1263         req->wrap      = FALSE;
1264         req->data.ch   = lpFill->Char.UnicodeChar;
1265         req->data.attr = lpFill->Attributes;
1266         wine_server_call_err( req );
1267     }
1268     SERVER_END_REQ;
1269 }
1270
1271 /******************************************************************************
1272  * ScrollConsoleScreenBufferW [KERNEL32.@]
1273  * 
1274  */
1275
1276 BOOL WINAPI ScrollConsoleScreenBufferW(HANDLE hConsoleOutput, LPSMALL_RECT lpScrollRect, 
1277                                        LPSMALL_RECT lpClipRect, COORD dwDestOrigin, 
1278                                        LPCHAR_INFO lpFill)
1279 {
1280     SMALL_RECT                  dst;
1281     DWORD                       ret;
1282     int                         i, j;
1283     int                         start = -1;
1284     SMALL_RECT                  clip;
1285     CONSOLE_SCREEN_BUFFER_INFO  csbi;
1286     BOOL                        inside;
1287         
1288     if (lpClipRect)
1289         TRACE("(%d,(%d,%d-%d,%d),(%d,%d-%d,%d),%d-%d,%p)\n", hConsoleOutput, 
1290               lpScrollRect->Left, lpScrollRect->Top,
1291               lpScrollRect->Right, lpScrollRect->Bottom,
1292               lpClipRect->Left, lpClipRect->Top,
1293               lpClipRect->Right, lpClipRect->Bottom,
1294               dwDestOrigin.X, dwDestOrigin.Y, lpFill);
1295     else
1296         TRACE("(%d,(%d,%d-%d,%d),(nil),%d-%d,%p)\n", hConsoleOutput, 
1297               lpScrollRect->Left, lpScrollRect->Top,
1298               lpScrollRect->Right, lpScrollRect->Bottom,
1299               dwDestOrigin.X, dwDestOrigin.Y, lpFill);
1300     
1301     if (!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
1302         return FALSE;
1303
1304     /* step 1: get dst rect */
1305     dst.Left = dwDestOrigin.X;
1306     dst.Top = dwDestOrigin.Y;
1307     dst.Right = dst.Left + (lpScrollRect->Right - lpScrollRect->Left);
1308     dst.Bottom = dst.Top + (lpScrollRect->Bottom - lpScrollRect->Top);
1309     
1310     /* step 2a: compute the final clip rect (optional passed clip and screen buffer limits */
1311     if (lpClipRect)
1312     {
1313         clip.Left   = max(0, lpClipRect->Left);
1314         clip.Right  = min(csbi.dwSize.X - 1, lpClipRect->Right);
1315         clip.Top    = max(0, lpClipRect->Top);
1316         clip.Bottom = min(csbi.dwSize.Y - 1, lpClipRect->Bottom);
1317     }
1318     else
1319     {
1320         clip.Left   = 0;
1321         clip.Right  = csbi.dwSize.X - 1;
1322         clip.Top    = 0;
1323         clip.Bottom = csbi.dwSize.Y - 1;
1324     }
1325     if (clip.Left > clip.Right || clip.Top > clip.Bottom) return FALSE;
1326
1327     /* step 2b: clip dst rect */
1328     if (dst.Left   < clip.Left  ) dst.Left   = clip.Left;
1329     if (dst.Top    < clip.Top   ) dst.Top    = clip.Top;
1330     if (dst.Right  > clip.Right ) dst.Right  = clip.Right;
1331     if (dst.Bottom > clip.Bottom) dst.Bottom = clip.Bottom;
1332     
1333     /* step 3: transfer the bits */
1334     SERVER_START_REQ(move_console_output)
1335     {
1336         req->handle = hConsoleOutput;
1337         req->x_src = lpScrollRect->Left;
1338         req->y_src = lpScrollRect->Top;
1339         req->x_dst = dst.Left;
1340         req->y_dst = dst.Top;
1341         req->w = dst.Right - dst.Left + 1;
1342         req->h = dst.Bottom - dst.Top + 1;
1343         ret = !wine_server_call_err( req );
1344     }
1345     SERVER_END_REQ;
1346
1347     if (!ret) return FALSE;
1348
1349     /* step 4: clean out the exposed part */
1350
1351     /* have to write celll [i,j] if it is not in dst rect (because it has already
1352      * been written to by the scroll) and is in clip (we shall not write
1353      * outside of clip)
1354      */
1355     for (j = max(lpScrollRect->Top, clip.Top); j <= min(lpScrollRect->Bottom, clip.Bottom); j++)
1356     {
1357         inside = dst.Top <= j && j <= dst.Bottom;
1358         start = -1;
1359         for (i = max(lpScrollRect->Left, clip.Left); i <= min(lpScrollRect->Right, clip.Right); i++)
1360         {
1361             if (inside && dst.Left <= i && i <= dst.Right)
1362             {
1363                 if (start != -1)
1364                 {
1365                     fill_line_uniform(hConsoleOutput, start, j, i - start, lpFill);
1366                     start = -1;
1367                 }
1368             }
1369             else
1370             {
1371                 if (start == -1) start = i;
1372             }
1373         }
1374         if (start != -1)
1375             fill_line_uniform(hConsoleOutput, start, j, i - start, lpFill);
1376     }
1377
1378     return TRUE;
1379 }
1380
1381
1382 /* ====================================================================
1383  *
1384  * Console manipulation functions
1385  *
1386  * ====================================================================*/
1387 /* some missing functions...
1388  * FIXME: those are likely to be defined as undocumented function in kernel32 (or part of them)
1389  * should get the right API and implement them
1390  *      GetConsoleCommandHistory[AW] (dword dword dword)
1391  *      GetConsoleCommandHistoryLength[AW]
1392  *      SetConsoleCommandHistoryMode
1393  *      SetConsoleNumberOfCommands[AW]
1394  */
1395 int CONSOLE_GetHistory(int idx, WCHAR* buf, int buf_len)
1396 {
1397     int len = 0;
1398
1399     SERVER_START_REQ( get_console_input_history )
1400     {
1401         req->handle = 0;
1402         req->index = idx;
1403         if (buf && buf_len > 1)
1404         {
1405             wine_server_set_reply( req, buf, (buf_len - 1) * sizeof(WCHAR) );
1406         }
1407         if (!wine_server_call_err( req ))
1408         {
1409             if (buf) buf[wine_server_reply_size(reply) / sizeof(WCHAR)] = 0;
1410             len = reply->total / sizeof(WCHAR) + 1;
1411         }
1412     }
1413     SERVER_END_REQ;
1414     return len;
1415 }
1416
1417 /******************************************************************
1418  *              CONSOLE_AppendHistory
1419  *
1420  *
1421  */
1422 BOOL    CONSOLE_AppendHistory(const WCHAR* ptr)
1423 {
1424     size_t      len = strlenW(ptr);
1425     BOOL        ret;
1426
1427     while (len && (ptr[len - 1] == '\n' || ptr[len - 1] == '\r')) len--;
1428
1429     SERVER_START_REQ( append_console_input_history )
1430     {
1431         req->handle = 0;
1432         wine_server_add_data( req, ptr, len * sizeof(WCHAR) );
1433         ret = !wine_server_call_err( req );
1434     }
1435     SERVER_END_REQ;
1436     return ret;
1437 }
1438
1439 /******************************************************************
1440  *              CONSOLE_GetNumHistoryEntries
1441  *
1442  *
1443  */
1444 unsigned CONSOLE_GetNumHistoryEntries(void)
1445 {
1446     unsigned ret = 0;
1447     SERVER_START_REQ(get_console_input_info)
1448     {
1449         req->handle = 0;
1450         if (!wine_server_call_err( req )) ret = reply->history_index;
1451     }
1452     SERVER_END_REQ;
1453     return ret;
1454 }
1455