Use CONSOLE_RENDERER_NONE_EVENT to compress an event instead of
[wine] / programs / wineconsole / wineconsole.c
1 /*
2  * an application for displaying Win32 console
3  *
4  * Copyright 2001, 2002 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 "config.h"
22 #include "wine/port.h"
23
24 #include <stdio.h>
25 #include "wine/server.h"
26 #include "winecon_private.h"
27 #include "winnls.h"
28
29 #include "wine/debug.h"
30
31 WINE_DEFAULT_DEBUG_CHANNEL(wineconsole);
32
33 void WINECON_Fatal(const char* msg)
34 {
35     WINE_ERR("%s\n", msg);
36     ExitProcess(0);
37 }
38
39 /******************************************************************
40  *              WINECON_FetchCells
41  *
42  * updates the local copy of cells (band to update)
43  */
44 void WINECON_FetchCells(struct inner_data* data, int upd_tp, int upd_bm)
45 {
46     SERVER_START_REQ( read_console_output )
47     {
48         req->handle = (obj_handle_t)data->hConOut;
49         req->x      = 0;
50         req->y      = upd_tp;
51         req->mode   = CHAR_INFO_MODE_TEXTATTR;
52         req->wrap   = TRUE;
53         wine_server_set_reply( req, &data->cells[upd_tp * data->curcfg.sb_width],
54                                (upd_bm-upd_tp+1) * data->curcfg.sb_width * sizeof(CHAR_INFO) );
55         wine_server_call( req );
56     }
57     SERVER_END_REQ;
58     data->fnRefresh(data, upd_tp, upd_bm);
59 }
60
61 /******************************************************************
62  *              WINECON_NotifyWindowChange
63  *
64  * Inform server that visible window on sb has changed
65  */
66 void WINECON_NotifyWindowChange(struct inner_data* data)
67 {
68     SERVER_START_REQ( set_console_output_info )
69     {
70         req->handle       = (obj_handle_t)data->hConOut;
71         req->win_left     = data->curcfg.win_pos.X;
72         req->win_top      = data->curcfg.win_pos.Y;
73         req->win_right    = data->curcfg.win_pos.X + data->curcfg.win_width - 1;
74         req->win_bottom   = data->curcfg.win_pos.Y + data->curcfg.win_height - 1;
75         req->mask         = SET_CONSOLE_OUTPUT_INFO_DISPLAY_WINDOW;
76         wine_server_call( req );
77     }
78     SERVER_END_REQ;
79 }
80
81 /******************************************************************
82  *              WINECON_GetHistorySize
83  *
84  *
85  */
86 int     WINECON_GetHistorySize(HANDLE hConIn)
87 {
88     int ret = 0;
89
90     SERVER_START_REQ(get_console_input_info)
91     {
92         req->handle = (obj_handle_t)hConIn;
93         if (!wine_server_call_err( req )) ret = reply->history_size;
94     }
95     SERVER_END_REQ;
96     return ret;
97 }
98
99 /******************************************************************
100  *              WINECON_SetHistorySize
101  *
102  *
103  */
104 BOOL    WINECON_SetHistorySize(HANDLE hConIn, int size)
105 {
106     BOOL        ret;
107
108     SERVER_START_REQ(set_console_input_info)
109     {
110         req->handle = (obj_handle_t)hConIn;
111         req->mask = SET_CONSOLE_INPUT_INFO_HISTORY_SIZE;
112         req->history_size = size;
113         ret = !wine_server_call_err( req );
114     }
115     SERVER_END_REQ;
116     return ret;
117 }
118
119
120 /******************************************************************
121  *              WINECON_GetHistoryMode
122  *
123  *
124  */
125 int     WINECON_GetHistoryMode(HANDLE hConIn)
126 {
127     int ret = 0;
128
129     SERVER_START_REQ(get_console_input_info)
130     {
131         req->handle = (obj_handle_t)hConIn;
132         if (!wine_server_call_err( req )) ret = reply->history_mode;
133     }
134     SERVER_END_REQ;
135     return ret;
136 }
137
138 /******************************************************************
139  *              WINECON_SetHistoryMode
140  *
141  *
142  */
143 BOOL    WINECON_SetHistoryMode(HANDLE hConIn, int mode)
144 {
145     BOOL        ret;
146
147     SERVER_START_REQ(set_console_input_info)
148     {
149         req->handle = (obj_handle_t)hConIn;
150         req->mask = SET_CONSOLE_INPUT_INFO_HISTORY_MODE;
151         req->history_mode = mode;
152         ret = !wine_server_call_err( req );
153     }
154     SERVER_END_REQ;
155     return ret;
156 }
157
158 /******************************************************************
159  *              WINECON_GetConsoleTitle
160  *
161  *
162  */
163 BOOL WINECON_GetConsoleTitle(HANDLE hConIn, WCHAR* buffer, size_t len)
164 {
165     BOOL ret;
166
167     if (len < sizeof(WCHAR)) return FALSE;
168
169     SERVER_START_REQ( get_console_input_info )
170     {
171         req->handle = (obj_handle_t)hConIn;
172         wine_server_set_reply( req, buffer, len - sizeof(WCHAR) );
173         if ((ret = !wine_server_call_err( req )))
174         {
175             len = wine_server_reply_size( reply );
176             buffer[len / sizeof(WCHAR)] = 0;
177         }
178     }
179     SERVER_END_REQ;
180     return ret;
181 }
182
183 /******************************************************************
184  *              WINECON_SetEditionMode
185  *
186  *
187  */
188 static BOOL WINECON_SetEditionMode(HANDLE hConIn, int edition_mode)
189 {
190     BOOL ret;
191
192     SERVER_START_REQ( set_console_input_info )
193     {
194         req->handle = (obj_handle_t)hConIn;
195         req->mask = SET_CONSOLE_INPUT_INFO_EDITION_MODE;
196         req->edition_mode = edition_mode;
197         ret = !wine_server_call_err( req );
198     }
199     SERVER_END_REQ;
200     return ret;
201 }
202
203 /******************************************************************
204  *              WINECON_GrabChanges
205  *
206  * A change occurs, try to figure out which
207  */
208 int     WINECON_GrabChanges(struct inner_data* data)
209 {
210     struct console_renderer_event       evts[256];
211     int i, num, ev_found;
212     HANDLE h;
213
214     SERVER_START_REQ( get_console_renderer_events )
215     {
216         wine_server_set_reply( req, evts, sizeof(evts) );
217         req->handle = (obj_handle_t)data->hSynchro;
218         if (!wine_server_call_err( req )) num = wine_server_reply_size(reply) / sizeof(evts[0]);
219         else num = 0;
220     }
221     SERVER_END_REQ;
222     if (!num) {WINE_WARN("hmm renderer signaled but no events available\n"); return 1;}
223
224     /* FIXME: should do some event compression here (cursor pos, update) */
225     /* step 1: keep only last cursor pos event */
226     ev_found = -1;
227     for (i = num - 1; i >= 0; i--)
228     {
229         if (evts[i].event == CONSOLE_RENDERER_CURSOR_POS_EVENT)
230         {
231             if (ev_found != -1) evts[ev_found].event = CONSOLE_RENDERER_NONE_EVENT;
232             ev_found = i;
233         }
234     }
235     /* step 2: manage update events */
236     ev_found = -1;
237     for (i = 0; i < num - 1; i++)
238     {
239         if (evts[i].event == CONSOLE_RENDERER_NONE_EVENT) continue;
240         if (evts[i].event != CONSOLE_RENDERER_UPDATE_EVENT)
241         {
242             ev_found = -1;
243             continue;
244             }
245
246         if (ev_found != -1 &&
247             !(evts[i       ].u.update.bottom + 1 < evts[ev_found].u.update.top ||
248               evts[ev_found].u.update.bottom + 1 < evts[i       ].u.update.top))
249         {
250             evts[i].u.update.top    = min(evts[i       ].u.update.top,
251                                           evts[ev_found].u.update.top);
252             evts[i].u.update.bottom = max(evts[i       ].u.update.bottom,
253                                           evts[ev_found].u.update.bottom);
254             evts[ev_found].event = CONSOLE_RENDERER_NONE_EVENT;
255         }
256         ev_found = i;
257     }
258
259     WINE_TRACE("Events:");
260     for (i = 0; i < num; i++)
261     {
262         switch (evts[i].event)
263         {
264         case CONSOLE_RENDERER_NONE_EVENT:
265             break;
266         case CONSOLE_RENDERER_TITLE_EVENT:
267             data->fnSetTitle(data);
268             break;
269         case CONSOLE_RENDERER_ACTIVE_SB_EVENT:
270             SERVER_START_REQ( open_console )
271             {
272                 req->from    = (int)data->hConIn;
273                 req->access  = GENERIC_READ | GENERIC_WRITE;
274                 req->share   = FILE_SHARE_READ | FILE_SHARE_WRITE;
275                 req->inherit = FALSE;
276                 h = wine_server_call_err( req ) ? 0 : (HANDLE)reply->handle;
277             }
278             SERVER_END_REQ;
279             WINE_TRACE(" active(%d)", (int)h);
280             if (h)
281             {
282                 CloseHandle(data->hConOut);
283                 data->hConOut = h;
284             }
285             break;
286         case CONSOLE_RENDERER_SB_RESIZE_EVENT:
287             if (data->curcfg.sb_width != evts[i].u.resize.width ||
288                 data->curcfg.sb_height != evts[i].u.resize.height || !data->cells)
289             {
290                 WINE_TRACE(" resize(%d,%d)", evts[i].u.resize.width, evts[i].u.resize.height);
291                 data->curcfg.sb_width  = evts[i].u.resize.width;
292                 data->curcfg.sb_height = evts[i].u.resize.height;
293
294                 data->cells = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, data->cells,
295                                           data->curcfg.sb_width * data->curcfg.sb_height * sizeof(CHAR_INFO));
296                 if (!data->cells) WINECON_Fatal("OOM\n");
297                 data->fnResizeScreenBuffer(data);
298                 data->fnComputePositions(data);
299             }
300             break;
301         case CONSOLE_RENDERER_UPDATE_EVENT:
302             WINE_TRACE(" update(%d,%d)", evts[i].u.update.top, evts[i].u.update.bottom);
303             WINECON_FetchCells(data, evts[i].u.update.top, evts[i].u.update.bottom);
304             break;
305         case CONSOLE_RENDERER_CURSOR_POS_EVENT:
306             if (evts[i].u.cursor_pos.x != data->cursor.X || evts[i].u.cursor_pos.y != data->cursor.Y)
307             {
308                 WINE_TRACE(" curs-pos(%d,%d)",evts[i].u.cursor_pos.x, evts[i].u.cursor_pos.y);
309                 data->cursor.X = evts[i].u.cursor_pos.x;
310                 data->cursor.Y = evts[i].u.cursor_pos.y;
311                 data->fnPosCursor(data);
312             }
313             break;
314         case CONSOLE_RENDERER_CURSOR_GEOM_EVENT:
315             if (evts[i].u.cursor_geom.size != data->curcfg.cursor_size ||
316                 evts[i].u.cursor_geom.visible != data->curcfg.cursor_visible)
317             {
318                 WINE_TRACE(" curs-geom(%d,%d)",
319                            evts[i].u.cursor_geom.size, evts[i].u.cursor_geom.visible);
320                 data->fnShapeCursor(data, evts[i].u.cursor_geom.size,
321                                     evts[i].u.cursor_geom.visible, FALSE);
322             }
323             break;
324         case CONSOLE_RENDERER_DISPLAY_EVENT:
325             if (evts[i].u.display.left != data->curcfg.win_pos.X)
326             {
327                 WINE_TRACE(" h-scroll(%d)", evts[i].u.display.left);
328                 data->fnScroll(data, evts[i].u.display.left, TRUE);
329                 data->fnPosCursor(data);
330             }
331             if (evts[i].u.display.top != data->curcfg.win_pos.Y)
332             {
333                 WINE_TRACE(" v-scroll(%d)", evts[i].u.display.top);
334                 data->fnScroll(data, evts[i].u.display.top, FALSE);
335                 data->fnPosCursor(data);
336             }
337             if (evts[i].u.display.width != data->curcfg.win_width ||
338                 evts[i].u.display.height != data->curcfg.win_height)
339             {
340                 WINE_TRACE(" win-size(%d,%d)", evts[i].u.display.width, evts[i].u.display.height);
341                 data->curcfg.win_width = evts[i].u.display.width;
342                 data->curcfg.win_height = evts[i].u.display.height;
343                 data->fnComputePositions(data);
344             }
345             break;
346         case CONSOLE_RENDERER_EXIT_EVENT:
347             WINE_TRACE(". Exit!!\n");
348             return 0;
349         default:
350             WINE_FIXME("Unknown event type (%d)\n", evts[i].event);
351         }
352     }
353
354     WINE_TRACE(".\n");
355     return 1;
356 }
357
358 /******************************************************************
359  *              WINECON_SetConfig
360  *
361  * Apply to data all the configuration elements from cfg. This includes modification
362  * of server side equivalent and visual parts.
363  * If force is FALSE, only the changed items are modified.
364  */
365 void     WINECON_SetConfig(struct inner_data* data,
366                            const struct config_data* cfg, BOOL force)
367 {
368     if (force || data->curcfg.cursor_size != cfg->cursor_size ||
369         data->curcfg.cursor_visible != cfg->cursor_visible)
370     {
371         CONSOLE_CURSOR_INFO cinfo;
372         cinfo.dwSize = cfg->cursor_size;
373         /* <FIXME>: this hack is needed to pass thru the invariant test operation on server side
374          * (no notification is sent when invariant operation is requested
375          */
376         cinfo.bVisible = !cfg->cursor_visible;
377         SetConsoleCursorInfo(data->hConOut, &cinfo);
378         /* </FIXME> */
379         cinfo.bVisible = cfg->cursor_visible;
380         /* this shall update (through notif) curcfg */
381         SetConsoleCursorInfo(data->hConOut, &cinfo);
382     }
383     if (force || data->curcfg.history_size != cfg->history_size)
384     {
385         data->curcfg.history_size = cfg->history_size;
386         WINECON_SetHistorySize(data->hConIn, cfg->history_size);
387     }
388     if (force || data->curcfg.history_nodup != cfg->history_nodup)
389     {
390         data->curcfg.history_nodup = cfg->history_nodup;
391         WINECON_SetHistoryMode(data->hConIn, cfg->history_nodup);
392     }
393     data->curcfg.menu_mask = cfg->menu_mask;
394     data->curcfg.quick_edit = cfg->quick_edit;
395     if (force || 1 /* FIXME: font info has changed */)
396     {
397         data->fnSetFont(data, cfg->face_name, cfg->cell_height, cfg->font_weight);
398     }
399     if (force || data->curcfg.def_attr != cfg->def_attr)
400     {
401         data->curcfg.def_attr = cfg->def_attr;
402         SetConsoleTextAttribute(data->hConOut, cfg->def_attr);
403     }
404     /* now let's look at the window / sb size changes...
405      * since the server checks that sb is always bigger than window, 
406      * we have to take care of doing the operations in the right order
407      */
408     /* a set of macros to make things easier to read 
409      * The Test<A><B> macros test if the <A> (width/height) needs to be changed 
410      * for <B> (window / ScreenBuffer) 
411      * The Change<A><B> actually modify the <B> dimension of <A>.
412      */
413 #define TstSBfWidth()   (force || data->curcfg.sb_width != cfg->sb_width)
414 #define TstWinWidth()   (force || data->curcfg.win_width != cfg->win_width)
415
416 #define ChgSBfWidth()   do {c.X = cfg->sb_width; \
417                             c.Y = data->curcfg.sb_height;\
418                             SetConsoleScreenBufferSize(data->hConOut, c);\
419                         } while (0)
420 #define ChgWinWidth()   do {pos.Left = pos.Top = 0; \
421                             pos.Right = cfg->win_width - 1; \
422                             pos.Bottom = data->curcfg.win_height - 1; \
423                             SetConsoleWindowInfo(data->hConOut, FALSE, &pos);\
424                         } while (0)
425 #define TstSBfHeight()  (force || data->curcfg.sb_height != cfg->sb_height)
426 #define TstWinHeight()  (force || data->curcfg.win_height != cfg->win_height)
427
428 /* since we're going to apply height after width is done, we use width as defined 
429  * in cfg, and not in data->curcfg because if won't be updated yet */
430 #define ChgSBfHeight()  do {c.X = cfg->sb_width; c.Y = cfg->sb_height; \
431                             SetConsoleScreenBufferSize(data->hConOut, c); \
432                         } while (0)
433 #define ChgWinHeight()  do {pos.Left = pos.Top = 0; \
434                             pos.Right = cfg->win_width - 1; \
435                             pos.Bottom = cfg->win_height - 1; \
436                             SetConsoleWindowInfo(data->hConOut, FALSE, &pos);\
437                         } while (0)
438
439     do
440     {
441         COORD       c;
442         SMALL_RECT  pos;
443
444         if (TstSBfWidth())            
445         {
446             if (TstWinWidth())
447             {
448                 /* we're changing both at the same time, do it in the right order */
449                 if (cfg->sb_width >= data->curcfg.win_width)
450                 {
451                     ChgSBfWidth(); ChgWinWidth();
452                 }
453                 else
454                 {
455                     ChgWinWidth(); ChgSBfWidth();
456                 }
457             }
458             else ChgSBfWidth();
459         }
460         else if (TstWinWidth()) ChgWinWidth();
461         if (TstSBfHeight())
462         {
463             if (TstWinHeight())
464             {
465                 if (cfg->sb_height >= data->curcfg.win_height)
466                 {
467                     ChgSBfHeight(); ChgWinHeight();
468                 }
469                 else
470                 {
471                     ChgWinHeight(); ChgSBfHeight();
472                 }
473             }
474             else ChgSBfHeight();
475         }
476         else if (TstWinHeight()) ChgWinHeight();
477     } while (0);
478 #undef TstSBfWidth
479 #undef TstWinWidth
480 #undef ChgSBfWidth
481 #undef ChgWinWidth
482 #undef TstSBfHeight
483 #undef TstWinHeight
484 #undef ChgSBfHeight
485 #undef ChgWinHeight
486
487     data->curcfg.exit_on_die = cfg->exit_on_die;
488     if (force || data->curcfg.edition_mode != cfg->edition_mode)
489     {
490         data->curcfg.edition_mode = cfg->edition_mode;
491         WINECON_SetEditionMode(data->hConIn, cfg->edition_mode);
492     }
493     /* we now need to gather all events we got from the operations above,
494      * in order to get data correctly updated
495      */
496     WINECON_GrabChanges(data);
497 }
498
499 /******************************************************************
500  *              WINECON_Delete
501  *
502  * Destroy wineconsole internal data
503  */
504 static void WINECON_Delete(struct inner_data* data)
505 {
506     if (!data) return;
507
508     if (data->fnDeleteBackend)  data->fnDeleteBackend(data);
509     if (data->hConIn)           CloseHandle(data->hConIn);
510     if (data->hConOut)          CloseHandle(data->hConOut);
511     if (data->hSynchro)         CloseHandle(data->hSynchro);
512     if (data->cells)            HeapFree(GetProcessHeap(), 0, data->cells);
513     HeapFree(GetProcessHeap(), 0, data);
514 }
515
516 /******************************************************************
517  *              WINECON_Init
518  *
519  * Initialisation part I. Creation of server object (console input and
520  * active screen buffer)
521  */
522 static struct inner_data* WINECON_Init(HINSTANCE hInst, DWORD pid, LPCWSTR appname,
523                                        enum init_return (*backend)(struct inner_data*))
524 {
525     struct inner_data*  data = NULL;
526     DWORD               ret;
527     struct config_data  cfg;
528     STARTUPINFOW        si;
529
530     data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data));
531     if (!data) return 0;
532
533     GetStartupInfo(&si);
534
535     if (pid == 0)
536     {
537         if (!si.lpTitle) WINECON_Fatal("Should have a title set");
538         appname = si.lpTitle;
539     }
540
541     /* load settings */
542     WINECON_RegLoad(appname, &cfg);
543
544     /* some overrides */
545     if (pid == 0)
546     {
547         if (si.dwFlags & STARTF_USECOUNTCHARS)
548         {
549             cfg.sb_width  = si.dwXCountChars;
550             cfg.sb_height = si.dwYCountChars;
551         }
552         if (si.dwFlags & STARTF_USEFILLATTRIBUTE)
553             cfg.def_attr = si.dwFillAttribute;
554         /* should always be defined */
555     }
556
557     /* the handles here are created without the whistles and bells required by console
558      * (mainly because wineconsole doesn't need it)
559      * - they are not inheritable
560      * - hConIn is not synchronizable
561      */
562     SERVER_START_REQ(alloc_console)
563     {
564         req->access     = GENERIC_READ | GENERIC_WRITE;
565         req->inherit    = FALSE;
566         req->pid        = pid;
567
568         ret = !wine_server_call_err( req );
569         data->hConIn = (HANDLE)reply->handle_in;
570         data->hSynchro = (HANDLE)reply->event;
571     }
572     SERVER_END_REQ;
573     if (!ret) goto error;
574     WINE_TRACE("using hConIn %p, hSynchro event %p\n", data->hConIn, data->hSynchro);
575
576     SERVER_START_REQ( set_console_input_info )
577     {
578         req->handle = (obj_handle_t)data->hConIn;
579         req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
580         wine_server_add_data( req, appname, lstrlenW(appname) * sizeof(WCHAR) );
581         ret = !wine_server_call_err( req );
582     }
583     SERVER_END_REQ;
584     if (!ret) goto error;
585
586     SERVER_START_REQ(create_console_output)
587     {
588         req->handle_in = (obj_handle_t)data->hConIn;
589         req->access    = GENERIC_WRITE|GENERIC_READ;
590         req->share     = FILE_SHARE_READ|FILE_SHARE_WRITE;
591         req->inherit   = FALSE;
592         ret = !wine_server_call_err( req );
593         data->hConOut  = (HANDLE)reply->handle_out;
594     }
595     SERVER_END_REQ;
596     if (!ret) goto error;
597     WINE_TRACE("using hConOut %p\n", data->hConOut);
598
599     /* filling data->curcfg from cfg */
600  retry:
601     switch ((*backend)(data))
602     {
603     case init_success:
604         WINECON_SetConfig(data, &cfg, TRUE);
605         data->curcfg.registry = cfg.registry;
606         WINECON_DumpConfig("fint", &data->curcfg);
607         return data;
608     case init_failed:
609         break;
610     case init_not_supported:
611         if (backend == WCCURSES_InitBackend)
612         {
613             WINE_ERR("(n)curses was not found at configuration time.\n"
614                      "If you want (n)curses support, please install relevant packages.\n"
615                      "Now forcing user backend instead of (n)curses.\n");
616             backend = WCUSER_InitBackend;
617             goto retry;
618         }
619         break;
620     }
621
622  error:
623     WINE_ERR("failed to init.\n");
624
625     WINECON_Delete(data);
626     return NULL;
627 }
628
629 /******************************************************************
630  *              WINECON_Spawn
631  *
632  * Spawn the child process when invoked with wineconsole foo bar
633  */
634 static BOOL WINECON_Spawn(struct inner_data* data, LPWSTR cmdLine)
635 {
636     PROCESS_INFORMATION info;
637     STARTUPINFO         startup;
638     BOOL                done;
639
640     /* we're in the case wineconsole <exe> <options>... spawn the new process */
641     memset(&startup, 0, sizeof(startup));
642     startup.cb          = sizeof(startup);
643     startup.dwFlags     = STARTF_USESTDHANDLES;
644
645     /* the attributes of wineconsole's handles are not adequate for inheritance, so
646      * get them with the correct attributes before process creation
647      */
648     if (!DuplicateHandle(GetCurrentProcess(), data->hConIn,  GetCurrentProcess(),
649                          &startup.hStdInput, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE, TRUE, 0) ||
650         !DuplicateHandle(GetCurrentProcess(), data->hConOut, GetCurrentProcess(),
651                          &startup.hStdOutput, GENERIC_READ|GENERIC_WRITE, TRUE, 0) ||
652         !DuplicateHandle(GetCurrentProcess(), data->hConOut, GetCurrentProcess(),
653                          &startup.hStdError, GENERIC_READ|GENERIC_WRITE, TRUE, 0))
654     {
655         WINE_ERR("Can't dup handles\n");
656         /* no need to delete handles, we're exiting the programm anyway */
657         return FALSE;
658     }
659
660     done = CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, 0L, NULL, NULL, &startup, &info);
661
662     /* we no longer need the handles passed to the child for the console */
663     CloseHandle(startup.hStdInput);
664     CloseHandle(startup.hStdOutput);
665     CloseHandle(startup.hStdError);
666
667     CloseHandle(info.hProcess);
668     CloseHandle(info.hThread);
669
670     return done;
671 }
672
673 struct wc_init {
674     LPCSTR              ptr;
675     enum {from_event, from_process_name} mode;
676     enum init_return    (*backend)(struct inner_data*);
677     HANDLE              event;
678 };
679
680 /******************************************************************
681  *               WINECON_ParseOptions
682  *
683  *
684  */
685 static BOOL WINECON_ParseOptions(const char* lpCmdLine, struct wc_init* wci)
686 {
687     memset(wci, 0, sizeof(*wci));
688     wci->ptr = lpCmdLine;
689     wci->mode = from_process_name;
690     wci->backend = WCCURSES_InitBackend;
691
692     for (;;)
693     {
694         while (*wci->ptr == ' ' || *wci->ptr == '\t') wci->ptr++;
695         if (wci->ptr[0] != '-') break;
696         if (strncmp(wci->ptr, "--use-event=", 12) == 0)
697         {
698             char*           end;
699             wci->event = (HANDLE)strtol(wci->ptr + 12, &end, 10);
700             if (end == wci->ptr + 12) return FALSE;
701             wci->mode = from_event;
702             wci->ptr = end;
703             wci->backend = WCUSER_InitBackend;
704         }
705         else if (strncmp(wci->ptr, "--backend=", 10) == 0)
706         {
707             if (strncmp(wci->ptr + 10, "user", 4) == 0)
708             {
709                 wci->backend = WCUSER_InitBackend;
710                 wci->ptr += 14;
711             }
712             else if (strncmp(wci->ptr + 10, "curses", 6) == 0)
713             {
714                 wci->ptr += 16;
715             }
716             else
717                 return FALSE;
718         }
719         else
720             return FALSE;
721     }
722
723     return TRUE;
724 }
725
726 /******************************************************************
727  *              WinMain
728  *
729  * wineconsole can either be started as:
730  *      wineconsole --use-event=<int>   used when a new console is created (AllocConsole)
731  *      wineconsole <pgm> <arguments>   used to start the program <pgm> from the command line in
732  *                                      a freshly created console
733  * --backend=(curses|user) can also be used to select the desired backend
734  */
735 int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, INT nCmdShow)
736 {
737     struct inner_data*  data;
738     int                 ret = 1;
739     struct wc_init      wci;
740
741     if (!WINECON_ParseOptions(lpCmdLine, &wci))
742     {
743         WINE_ERR("Wrong command line options\n");
744         return 0;
745     }
746
747     switch (wci.mode)
748     {
749     case from_event:
750         /* case of wineconsole <evt>, signal process that created us that we're up and running */
751         if (!(data = WINECON_Init(hInst, 0, NULL, wci.backend))) return 0;
752         ret = SetEvent(wci.event);
753         if (!ret) WINE_ERR("SetEvent failed.\n");
754         break;
755     case from_process_name:
756         {
757             WCHAR           buffer[256];
758
759             MultiByteToWideChar(CP_ACP, 0, wci.ptr, -1, buffer, sizeof(buffer) / sizeof(buffer[0]));
760
761             if (!(data = WINECON_Init(hInst, GetCurrentProcessId(), buffer, wci.backend)))
762                 return 0;
763             ret = WINECON_Spawn(data, buffer);
764             if (!ret)
765                 WINE_MESSAGE("wineconsole: spawning client program failed (%s), invalid/missing command line arguments ?\n", wine_dbgstr_w(buffer));
766         }
767         break;
768     default:
769         return 0;
770     }
771
772     if (ret)
773     {
774         WINE_TRACE("calling MainLoop.\n");
775         ret = data->fnMainLoop(data);
776     }
777
778     WINECON_Delete(data);
779
780     return ret;
781 }