Changed the GDI driver interface to pass an opaque PHYSDEV pointer
[wine] / programs / wineconsole / wineconsole.c
1 /*
2  * an application for displaying Win32 console
3  *
4  * Copyright 2001 Eric Pouech
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include <stdio.h>
22 #include "wine/server.h"
23 #include "wine/unicode.h"
24 #include "winecon_private.h"
25
26 static int trace_level = 1;
27 void      XTracer(int level, const char* format, ...)
28 {
29     char        buf[1024];
30     va_list     valist;
31     int         len;
32
33     if (level > trace_level) return;
34
35     va_start(valist, format);
36     len = vsnprintf(buf, sizeof(buf), format, valist);
37     va_end(valist);
38  
39     if ((len <= -1) || (len >= sizeof(buf)))
40     {
41         len = sizeof(buf) - 1;
42         buf[len] = 0;
43         buf[len - 1] = buf[len - 2] = buf[len - 3] = '.';
44     }
45     fprintf(stderr, buf);
46 }
47
48 /******************************************************************
49  *              WINECON_FetchCells
50  *
51  * updates the local copy of cells (band to update)
52  */
53 void WINECON_FetchCells(struct inner_data* data, int upd_tp, int upd_bm)
54 {
55     SERVER_START_REQ( read_console_output )
56     {
57         req->handle = (handle_t)data->hConOut;
58         req->x      = 0;
59         req->y      = upd_tp;
60         req->mode   = CHAR_INFO_MODE_TEXTATTR;
61         req->wrap   = TRUE;
62         wine_server_set_reply( req, &data->cells[upd_tp * data->curcfg.sb_width],
63                                (upd_bm-upd_tp+1) * data->curcfg.sb_width * sizeof(CHAR_INFO) );
64         wine_server_call( req );
65     }
66     SERVER_END_REQ;
67     data->fnRefresh(data, upd_tp, upd_bm);
68 }
69
70 /******************************************************************
71  *              WINECON_NotifyWindowChange
72  *
73  * Inform server that visible window on sb has changed
74  */
75 void WINECON_NotifyWindowChange(struct inner_data* data)
76 {
77     SERVER_START_REQ( set_console_output_info )
78     {
79         req->handle       = (handle_t)data->hConOut;
80         req->win_left     = data->curcfg.win_pos.X;
81         req->win_top      = data->curcfg.win_pos.Y;
82         req->win_right    = data->curcfg.win_pos.X + data->curcfg.win_width - 1;
83         req->win_bottom   = data->curcfg.win_pos.Y + data->curcfg.win_height - 1;
84         req->mask         = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
85         wine_server_call( req );
86     }
87     SERVER_END_REQ;
88 }
89
90 /******************************************************************
91  *              WINECON_GetHistorySize
92  *
93  *
94  */
95 int     WINECON_GetHistorySize(HANDLE hConIn)
96 {
97     int ret = 0;
98
99     SERVER_START_REQ(get_console_input_info)
100     {
101         req->handle = (handle_t)hConIn;
102         if (!wine_server_call_err( req )) ret = reply->history_size;
103     }
104     SERVER_END_REQ;
105     return ret;
106 }
107
108 /******************************************************************
109  *              WINECON_SetHistorySize
110  *
111  *
112  */
113 BOOL    WINECON_SetHistorySize(HANDLE hConIn, int size)
114 {
115     BOOL        ret;
116
117     SERVER_START_REQ(set_console_input_info)
118     {
119         req->handle = (handle_t)hConIn;
120         req->mask = SET_CONSOLE_INPUT_INFO_HISTORY_SIZE;
121         req->history_size = size;
122         ret = !wine_server_call_err( req );
123     }
124     SERVER_END_REQ;
125     return ret;
126 }
127
128
129 /******************************************************************
130  *              WINECON_GetHistoryMode
131  *
132  *
133  */
134 int     WINECON_GetHistoryMode(HANDLE hConIn)
135 {
136     int ret = 0;
137
138     SERVER_START_REQ(get_console_input_info)
139     {
140         req->handle = (handle_t)hConIn;
141         if (!wine_server_call_err( req )) ret = reply->history_mode;
142     }
143     SERVER_END_REQ;
144     return ret;
145 }
146
147 /******************************************************************
148  *              WINECON_SetHistoryMode
149  *
150  *
151  */
152 BOOL    WINECON_SetHistoryMode(HANDLE hConIn, int mode)
153 {
154     BOOL        ret;
155
156     SERVER_START_REQ(set_console_input_info)
157     {
158         req->handle = (handle_t)hConIn;
159         req->mask = SET_CONSOLE_INPUT_INFO_HISTORY_MODE;
160         req->history_mode = mode;
161         ret = !wine_server_call_err( req );
162     }
163     SERVER_END_REQ;
164     return ret;
165 }
166
167 /******************************************************************
168  *              WINECON_GetConsoleTitle
169  *
170  *
171  */
172 BOOL WINECON_GetConsoleTitle(HANDLE hConIn, WCHAR* buffer, size_t len)
173 {
174     BOOL ret;
175
176     if (len < sizeof(WCHAR)) return FALSE;
177
178     SERVER_START_REQ( get_console_input_info )
179     {
180         req->handle = (handle_t)hConIn;
181         wine_server_set_reply( req, buffer, len - sizeof(WCHAR) );
182         if ((ret = !wine_server_call_err( req )))
183         {
184             len = wine_server_reply_size( reply );
185             buffer[len / sizeof(WCHAR)] = 0;
186         }
187     }
188     SERVER_END_REQ;
189     return ret;
190 }
191
192 /******************************************************************
193  *              WINECON_GrabChanges
194  *
195  * A change occurs, try to figure out which
196  */
197 int     WINECON_GrabChanges(struct inner_data* data)
198 {
199     struct console_renderer_event       evts[256];
200     int i, num, curs = -1;
201     HANDLE h;
202
203     SERVER_START_REQ( get_console_renderer_events )
204     {
205         wine_server_set_reply( req, evts, sizeof(evts) );
206         req->handle = (handle_t)data->hSynchro;
207         if (!wine_server_call_err( req )) num = wine_server_reply_size(reply) / sizeof(evts[0]);
208         else num = 0;
209     }
210     SERVER_END_REQ;
211     if (!num) {Trace(0, "hmm renderer signaled but no events available\n"); return 1;}
212     
213     /* FIXME: should do some event compression here (cursor pos, update) */
214     /* step 1: keep only last cursor pos event */
215     for (i = num - 1; i >= 0; i--)
216     {
217         if (evts[i].event == CONSOLE_RENDERER_CURSOR_POS_EVENT)
218         {
219             if (curs == -1)
220                 curs = i;
221             else
222             {
223                 memmove(&evts[i], &evts[i+1], (num - i - 1) * sizeof(evts[0]));
224                 num--;
225             }
226         }
227     }
228     /* step 2: manage update events */
229     for (i = 0; i < num - 1; i++)
230     {
231         if (evts[i].event == CONSOLE_RENDERER_UPDATE_EVENT &&
232             evts[i+1].event == CONSOLE_RENDERER_UPDATE_EVENT)
233         {
234             /* contiguous */
235             if (evts[i].u.update.bottom + 1 == evts[i+1].u.update.top)
236             {
237                 evts[i].u.update.bottom = evts[i+1].u.update.bottom;
238                 memmove(&evts[i+1], &evts[i+2], (num - i - 2) * sizeof(evts[0]));
239                 num--; i--;
240             }
241             /* already handled cases */
242             else if (evts[i].u.update.top <= evts[i+1].u.update.top &&
243                      evts[i].u.update.bottom >= evts[i+1].u.update.bottom)
244             {
245                 memmove(&evts[i+1], &evts[i+2], (num - i - 2) * sizeof(evts[0]));
246                 num--; i--;
247             }
248         }
249     }
250    
251     Trace(1, "Change notification:");
252     for (i = 0; i < num; i++)
253     {
254         switch (evts[i].event)
255         {
256         case CONSOLE_RENDERER_TITLE_EVENT:
257             data->fnSetTitle(data);
258             break;
259         case CONSOLE_RENDERER_ACTIVE_SB_EVENT:
260             SERVER_START_REQ( open_console )
261             {
262                 req->from    = (int)data->hConIn;
263                 req->access  = GENERIC_READ | GENERIC_WRITE;
264                 req->share   = FILE_SHARE_READ | FILE_SHARE_WRITE;
265                 req->inherit = FALSE;
266                 h = wine_server_call_err( req ) ? 0 : (HANDLE)reply->handle;
267             }
268             SERVER_END_REQ;
269             Trace(1, " active(%d)", (int)h);
270             if (h)
271             {
272                 CloseHandle(data->hConOut);
273                 data->hConOut = h;
274             }
275             break;
276         case CONSOLE_RENDERER_SB_RESIZE_EVENT:
277             if (data->curcfg.sb_width != evts[i].u.resize.width || 
278                 data->curcfg.sb_height != evts[i].u.resize.height)
279             {
280                 Trace(1, " resize(%d,%d)", evts[i].u.resize.width, evts[i].u.resize.height);
281                 data->curcfg.sb_width  = evts[i].u.resize.width;
282                 data->curcfg.sb_height = evts[i].u.resize.height;
283                 
284                 data->cells = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, data->cells,
285                                           data->curcfg.sb_width * data->curcfg.sb_height * sizeof(CHAR_INFO));
286                 if (!data->cells) {Trace(0, "OOM\n"); exit(0);}
287                 data->fnResizeScreenBuffer(data);
288                 data->fnComputePositions(data);
289             }
290             break;
291         case CONSOLE_RENDERER_UPDATE_EVENT:
292             Trace(1, " update(%d,%d)", evts[i].u.update.top, evts[i].u.update.bottom);
293             WINECON_FetchCells(data, evts[i].u.update.top, evts[i].u.update.bottom);
294             break;
295         case CONSOLE_RENDERER_CURSOR_POS_EVENT:
296             if (evts[i].u.cursor_pos.x != data->cursor.X || evts[i].u.cursor_pos.y != data->cursor.Y)
297             {   
298                 data->cursor.X = evts[i].u.cursor_pos.x;
299                 data->cursor.Y = evts[i].u.cursor_pos.y;
300                 data->fnPosCursor(data);
301                 Trace(1, " curs-pos(%d,%d)",evts[i].u.cursor_pos.x, evts[i].u.cursor_pos.y);
302             }
303             break;
304         case CONSOLE_RENDERER_CURSOR_GEOM_EVENT:
305             if (evts[i].u.cursor_geom.size != data->curcfg.cursor_size || 
306                 evts[i].u.cursor_geom.visible != data->curcfg.cursor_visible)
307             {
308                 data->fnShapeCursor(data, evts[i].u.cursor_geom.size, 
309                                     evts[i].u.cursor_geom.visible, FALSE);
310                 Trace(1, " curs-geom(%d,%d)", 
311                       evts[i].u.cursor_geom.size, evts[i].u.cursor_geom.visible);
312             }
313             break;
314         case CONSOLE_RENDERER_DISPLAY_EVENT:
315             if (evts[i].u.display.left != data->curcfg.win_pos.X)
316             {
317                 data->fnScroll(data, evts[i].u.display.left, TRUE);
318                 data->fnPosCursor(data);
319                 Trace(1, " h-scroll(%d)", evts[i].u.display.left);
320             }
321             if (evts[i].u.display.top != data->curcfg.win_pos.Y)
322             {
323                 data->fnScroll(data, evts[i].u.display.top, FALSE);
324                 data->fnPosCursor(data);
325                 Trace(1, " v-scroll(%d)", evts[i].u.display.top);
326             }
327             if (evts[i].u.display.width != data->curcfg.win_width || 
328                 evts[i].u.display.height != data->curcfg.win_height)
329             {
330                 Trace(1, " win-size(%d,%d)", evts[i].u.display.width, evts[i].u.display.height);
331                 data->curcfg.win_width = evts[i].u.display.width;
332                 data->curcfg.win_height = evts[i].u.display.height;
333                 data->fnComputePositions(data);
334             }
335             break;
336         case CONSOLE_RENDERER_EXIT_EVENT:
337             Trace(1, ". Exit!!\n");
338             return 0;
339         default:
340             Trace(0, "Unknown event type (%d)\n", evts[i].event);
341         }
342     }
343
344     Trace(1, ". Done\n");
345     return 1;
346 }
347
348 /******************************************************************
349  *              WINECON_Delete
350  *
351  * Destroy wineconsole internal data
352  */
353 static void WINECON_Delete(struct inner_data* data)
354 {
355     if (!data) return;
356
357     if (data->hConIn)           CloseHandle(data->hConIn);
358     if (data->hConOut)          CloseHandle(data->hConOut);
359     if (data->hSynchro)         CloseHandle(data->hSynchro);
360     if (data->cells)            HeapFree(GetProcessHeap(), 0, data->cells);
361     if (data->fnDeleteBackend)  data->fnDeleteBackend(data);
362     HeapFree(GetProcessHeap(), 0, data);
363 }
364
365 /******************************************************************
366  *              WINECON_Init
367  *
368  * Initialisation part I. Creation of server object (console input and
369  * active screen buffer)
370  */
371 static struct inner_data* WINECON_Init(HINSTANCE hInst, void* pid)
372 {
373     struct inner_data*  data = NULL;
374     DWORD               ret;
375     WCHAR               szTitle[] = {'W','i','n','e',' ','c','o','n','s','o','l','e',0};
376
377     data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data));
378     if (!data) return 0;
379
380     /* load default registry settings, and copy them into our current configuration */
381     WINECON_RegLoad(&data->defcfg);
382     data->curcfg = data->defcfg;
383
384     /* the handles here are created without the whistles and bells required by console
385      * (mainly because wineconsole doesn't need it)
386      * - there are not inheritable
387      * - hConIn is not synchronizable
388      */
389     SERVER_START_REQ(alloc_console)
390     {
391         req->access  = GENERIC_READ | GENERIC_WRITE;
392         req->inherit = FALSE;
393         req->pid     = pid;
394         ret = !wine_server_call_err( req );
395         data->hConIn = (HANDLE)reply->handle_in;
396         data->hSynchro = (HANDLE)reply->event;
397     }
398     SERVER_END_REQ;
399     if (!ret) goto error;
400
401     SERVER_START_REQ( set_console_input_info )
402     {
403         req->handle = (handle_t)data->hConIn;
404         req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
405         wine_server_add_data( req, szTitle, strlenW(szTitle) * sizeof(WCHAR) );
406         ret = !wine_server_call_err( req );
407     }
408     SERVER_END_REQ;
409     if (!ret) goto error;
410
411     SERVER_START_REQ(create_console_output)
412     {
413         req->handle_in = (handle_t)data->hConIn;
414         req->access    = GENERIC_WRITE|GENERIC_READ;
415         req->share     = FILE_SHARE_READ|FILE_SHARE_WRITE;
416         req->inherit   = FALSE;
417         data->hConOut  = (HANDLE)(wine_server_call_err( req ) ? 0 : reply->handle_out);
418     }
419     SERVER_END_REQ;
420     if (data->hConOut) return data;
421
422  error:
423     WINECON_Delete(data);
424     return NULL;
425 }
426
427 /******************************************************************
428  *              WINECON_Spawn
429  *
430  * Spawn the child processus when invoked with wineconsole foo bar
431  */
432 static BOOL WINECON_Spawn(struct inner_data* data, LPCSTR lpCmdLine)
433 {
434     PROCESS_INFORMATION info;
435     STARTUPINFO         startup;
436     LPWSTR              ptr = GetCommandLine(); /* we're unicode... */
437     BOOL                done;
438
439     /* we're in the case wineconsole <exe> <options>... spawn the new process */
440     memset(&startup, 0, sizeof(startup));
441     startup.cb          = sizeof(startup);
442     startup.dwFlags     = STARTF_USESTDHANDLES;
443
444     /* the attributes of wineconsole's handles are not adequate for inheritance, so
445      * get them with the correct attributes before process creation
446      */
447     if (!DuplicateHandle(GetCurrentProcess(), data->hConIn,  GetCurrentProcess(),
448                          &startup.hStdInput, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE, TRUE, 0) ||
449         !DuplicateHandle(GetCurrentProcess(), data->hConOut, GetCurrentProcess(), 
450                          &startup.hStdOutput, GENERIC_READ|GENERIC_WRITE, TRUE, 0) ||
451         !DuplicateHandle(GetCurrentProcess(), data->hConOut, GetCurrentProcess(), 
452                              &startup.hStdError, GENERIC_READ|GENERIC_WRITE, TRUE, 0))
453     {
454         Trace(0, "can't dup handles\n");
455         /* no need to delete handles, we're exiting the programm anyway */
456         return FALSE;
457     }
458
459     /* we could have several ' ' in process command line... so try first space...
460      * FIXME:
461      * the correct way would be to check the existence of the left part of ptr
462      * (to be a file)
463      */
464     while (*ptr && *ptr++ != ' ');
465
466     done = *ptr && CreateProcess(NULL, ptr, NULL, NULL, TRUE, 0L, NULL, NULL, &startup, &info);
467     
468     /* we no longer need the handles passed to the child for the console */
469     CloseHandle(startup.hStdInput);
470     CloseHandle(startup.hStdOutput);
471     CloseHandle(startup.hStdError);
472
473     return done;
474 }
475
476 /******************************************************************
477  *               WINECON_HasEvent
478  *
479  *
480  */
481 static BOOL WINECON_HasEvent(LPCSTR ptr, unsigned *evt)
482 {
483     while (*ptr == ' ' || *ptr == '\t') ptr++;
484     if (strncmp(ptr, "--use-event=", 12)) return FALSE;
485     return sscanf(ptr + 12, "%d", evt) == 1;
486 }
487
488 /******************************************************************
489  *              WINECON_WinMain
490  *
491  * wineconsole can either be started as:
492  *      wineconsole --use-event=<int>   used when a new console is created (AllocConsole)
493  *      wineconsole <pgm> <arguments>   used to start the program <pgm> from the command line in
494  *                                      a freshly created console
495  */
496 int PASCAL WINECON_WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPCSTR lpCmdLine, UINT nCmdShow)
497 {
498     struct inner_data*  data;
499     int                 ret = 1;
500     unsigned            evt;
501
502     /* case of wineconsole <evt>, signal process that created us that we're up and running */
503     if (WINECON_HasEvent(lpCmdLine, &evt))
504     {
505         if (!(data = WINECON_Init(hInst, 0))) return 0;
506         ret = SetEvent((HANDLE)evt);
507     }
508     else
509     {
510         if (!(data = WINECON_Init(hInst, (void*)GetCurrentProcessId()))) return 0;
511         ret = WINECON_Spawn(data, lpCmdLine);
512     }
513
514     if (ret && WCUSER_InitBackend(data))
515     {
516         ret = data->fnMainLoop(data);
517     }
518     WINECON_Delete(data);
519
520     return ret;
521 }