Made RTF reader and writer handle codepages mostly similar to the
[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)
232                 evts[i].event = CONSOLE_RENDERER_NONE_EVENT;
233             ev_found = i;
234         }
235     }
236     /* step 2: manage update events */
237     ev_found = -1;
238     for (i = 0; i < num; i++)
239     {
240         if (evts[i].event == CONSOLE_RENDERER_NONE_EVENT ||
241             evts[i].event == CONSOLE_RENDERER_CURSOR_POS_EVENT ||
242             evts[i].event == CONSOLE_RENDERER_CURSOR_GEOM_EVENT) continue;
243         if (evts[i].event != CONSOLE_RENDERER_UPDATE_EVENT)
244         {
245             ev_found = -1;
246             continue;
247         }
248
249         if (ev_found != -1 &&  /* Only 2 cases where they can NOT merge */
250             !(evts[i       ].u.update.bottom + 1 < evts[ev_found].u.update.top ||
251               evts[ev_found].u.update.bottom + 1 < evts[i       ].u.update.top))
252         {
253             evts[i].u.update.top    = min(evts[i       ].u.update.top,
254                                           evts[ev_found].u.update.top);
255             evts[i].u.update.bottom = max(evts[i       ].u.update.bottom,
256                                           evts[ev_found].u.update.bottom);
257             evts[ev_found].event = CONSOLE_RENDERER_NONE_EVENT;
258         }
259         ev_found = i;
260     }
261
262     WINE_TRACE("Events:");
263     for (i = 0; i < num; i++)
264     {
265         switch (evts[i].event)
266         {
267         case CONSOLE_RENDERER_NONE_EVENT:
268             WINE_TRACE(" NOP");
269             break;
270         case CONSOLE_RENDERER_TITLE_EVENT:
271             WINE_TRACE(" title()");
272             data->fnSetTitle(data);
273             break;
274         case CONSOLE_RENDERER_ACTIVE_SB_EVENT:
275             SERVER_START_REQ( open_console )
276             {
277                 req->from    = (int)data->hConIn;
278                 req->access  = GENERIC_READ | GENERIC_WRITE;
279                 req->share   = FILE_SHARE_READ | FILE_SHARE_WRITE;
280                 req->inherit = FALSE;
281                 h = wine_server_call_err( req ) ? 0 : (HANDLE)reply->handle;
282             }
283             SERVER_END_REQ;
284             WINE_TRACE(" active(%d)", (int)h);
285             if (h)
286             {
287                 CloseHandle(data->hConOut);
288                 data->hConOut = h;
289             }
290             break;
291         case CONSOLE_RENDERER_SB_RESIZE_EVENT:
292             if (data->curcfg.sb_width != evts[i].u.resize.width ||
293                 data->curcfg.sb_height != evts[i].u.resize.height || !data->cells)
294             {
295                 WINE_TRACE(" resize(%d,%d)", evts[i].u.resize.width, evts[i].u.resize.height);
296                 data->curcfg.sb_width  = evts[i].u.resize.width;
297                 data->curcfg.sb_height = evts[i].u.resize.height;
298
299                 if (data->cells) 
300                     data->cells = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, data->cells,
301                                           data->curcfg.sb_width * data->curcfg.sb_height * sizeof(CHAR_INFO));
302                 else 
303                     data->cells = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
304                                           data->curcfg.sb_width * data->curcfg.sb_height * sizeof(CHAR_INFO));
305
306                 if (!data->cells) WINECON_Fatal("OOM\n");
307                 data->fnResizeScreenBuffer(data);
308                 data->fnComputePositions(data);
309             }
310             break;
311         case CONSOLE_RENDERER_UPDATE_EVENT:
312             WINE_TRACE(" update(%d,%d)", evts[i].u.update.top, evts[i].u.update.bottom);
313             WINECON_FetchCells(data, evts[i].u.update.top, evts[i].u.update.bottom);
314             break;
315         case CONSOLE_RENDERER_CURSOR_POS_EVENT:
316             if (evts[i].u.cursor_pos.x != data->cursor.X || evts[i].u.cursor_pos.y != data->cursor.Y)
317             {
318                 WINE_TRACE(" curs-pos(%d,%d)",evts[i].u.cursor_pos.x, evts[i].u.cursor_pos.y);
319                 data->cursor.X = evts[i].u.cursor_pos.x;
320                 data->cursor.Y = evts[i].u.cursor_pos.y;
321                 data->fnPosCursor(data);
322             }
323             break;
324         case CONSOLE_RENDERER_CURSOR_GEOM_EVENT:
325             if (evts[i].u.cursor_geom.size != data->curcfg.cursor_size ||
326                 evts[i].u.cursor_geom.visible != data->curcfg.cursor_visible)
327             {
328                 WINE_TRACE(" curs-geom(%d,%d)",
329                            evts[i].u.cursor_geom.size, evts[i].u.cursor_geom.visible);
330                 data->fnShapeCursor(data, evts[i].u.cursor_geom.size,
331                                     evts[i].u.cursor_geom.visible, FALSE);
332             }
333             break;
334         case CONSOLE_RENDERER_DISPLAY_EVENT:
335             if (evts[i].u.display.left != data->curcfg.win_pos.X)
336             {
337                 WINE_TRACE(" h-scroll(%d)", evts[i].u.display.left);
338                 data->fnScroll(data, evts[i].u.display.left, TRUE);
339                 data->fnPosCursor(data);
340             }
341             if (evts[i].u.display.top != data->curcfg.win_pos.Y)
342             {
343                 WINE_TRACE(" v-scroll(%d)", evts[i].u.display.top);
344                 data->fnScroll(data, evts[i].u.display.top, FALSE);
345                 data->fnPosCursor(data);
346             }
347             if (evts[i].u.display.width != data->curcfg.win_width ||
348                 evts[i].u.display.height != data->curcfg.win_height)
349             {
350                 WINE_TRACE(" win-size(%d,%d)", evts[i].u.display.width, evts[i].u.display.height);
351                 data->curcfg.win_width = evts[i].u.display.width;
352                 data->curcfg.win_height = evts[i].u.display.height;
353                 data->fnComputePositions(data);
354             }
355             break;
356         case CONSOLE_RENDERER_EXIT_EVENT:
357             WINE_TRACE(". Exit!!\n");
358             return 0;
359         default:
360             WINE_FIXME("Unknown event type (%d)\n", evts[i].event);
361         }
362     }
363
364     WINE_TRACE(".\n");
365     return 1;
366 }
367
368 /******************************************************************
369  *              WINECON_SetConfig
370  *
371  * Apply to data all the configuration elements from cfg. This includes modification
372  * of server side equivalent and visual parts.
373  * If force is FALSE, only the changed items are modified.
374  */
375 void     WINECON_SetConfig(struct inner_data* data,
376                            const struct config_data* cfg, BOOL force)
377 {
378     if (force || data->curcfg.cursor_size != cfg->cursor_size ||
379         data->curcfg.cursor_visible != cfg->cursor_visible)
380     {
381         CONSOLE_CURSOR_INFO cinfo;
382         cinfo.dwSize = cfg->cursor_size;
383         /* <FIXME>: this hack is needed to pass thru the invariant test operation on server side
384          * (no notification is sent when invariant operation is requested
385          */
386         cinfo.bVisible = !cfg->cursor_visible;
387         SetConsoleCursorInfo(data->hConOut, &cinfo);
388         /* </FIXME> */
389         cinfo.bVisible = cfg->cursor_visible;
390         /* this shall update (through notif) curcfg */
391         SetConsoleCursorInfo(data->hConOut, &cinfo);
392     }
393     if (force || data->curcfg.history_size != cfg->history_size)
394     {
395         data->curcfg.history_size = cfg->history_size;
396         WINECON_SetHistorySize(data->hConIn, cfg->history_size);
397     }
398     if (force || data->curcfg.history_nodup != cfg->history_nodup)
399     {
400         data->curcfg.history_nodup = cfg->history_nodup;
401         WINECON_SetHistoryMode(data->hConIn, cfg->history_nodup);
402     }
403     data->curcfg.menu_mask = cfg->menu_mask;
404     data->curcfg.quick_edit = cfg->quick_edit;
405     if (force || 1 /* FIXME: font info has changed */)
406     {
407         data->fnSetFont(data, cfg->face_name, cfg->cell_height, cfg->font_weight);
408     }
409     if (force || data->curcfg.def_attr != cfg->def_attr)
410     {
411         data->curcfg.def_attr = cfg->def_attr;
412         SetConsoleTextAttribute(data->hConOut, cfg->def_attr);
413     }
414     /* now let's look at the window / sb size changes...
415      * since the server checks that sb is always bigger than window, 
416      * we have to take care of doing the operations in the right order
417      */
418     /* a set of macros to make things easier to read 
419      * The Test<A><B> macros test if the <A> (width/height) needs to be changed 
420      * for <B> (window / ScreenBuffer) 
421      * The Change<A><B> actually modify the <B> dimension of <A>.
422      */
423 #define TstSBfWidth()   (force || data->curcfg.sb_width != cfg->sb_width)
424 #define TstWinWidth()   (force || data->curcfg.win_width != cfg->win_width)
425
426 #define ChgSBfWidth()   do {c.X = cfg->sb_width; \
427                             c.Y = data->curcfg.sb_height;\
428                             SetConsoleScreenBufferSize(data->hConOut, c);\
429                         } while (0)
430 #define ChgWinWidth()   do {pos.Left = pos.Top = 0; \
431                             pos.Right = cfg->win_width - 1; \
432                             pos.Bottom = data->curcfg.win_height - 1; \
433                             SetConsoleWindowInfo(data->hConOut, FALSE, &pos);\
434                         } while (0)
435 #define TstSBfHeight()  (force || data->curcfg.sb_height != cfg->sb_height)
436 #define TstWinHeight()  (force || data->curcfg.win_height != cfg->win_height)
437
438 /* since we're going to apply height after width is done, we use width as defined 
439  * in cfg, and not in data->curcfg because if won't be updated yet */
440 #define ChgSBfHeight()  do {c.X = cfg->sb_width; c.Y = cfg->sb_height; \
441                             SetConsoleScreenBufferSize(data->hConOut, c); \
442                         } while (0)
443 #define ChgWinHeight()  do {pos.Left = pos.Top = 0; \
444                             pos.Right = cfg->win_width - 1; \
445                             pos.Bottom = cfg->win_height - 1; \
446                             SetConsoleWindowInfo(data->hConOut, FALSE, &pos);\
447                         } while (0)
448
449     do
450     {
451         COORD       c;
452         SMALL_RECT  pos;
453
454         if (TstSBfWidth())            
455         {
456             if (TstWinWidth())
457             {
458                 /* we're changing both at the same time, do it in the right order */
459                 if (cfg->sb_width >= data->curcfg.win_width)
460                 {
461                     ChgSBfWidth(); ChgWinWidth();
462                 }
463                 else
464                 {
465                     ChgWinWidth(); ChgSBfWidth();
466                 }
467             }
468             else ChgSBfWidth();
469         }
470         else if (TstWinWidth()) ChgWinWidth();
471         if (TstSBfHeight())
472         {
473             if (TstWinHeight())
474             {
475                 if (cfg->sb_height >= data->curcfg.win_height)
476                 {
477                     ChgSBfHeight(); ChgWinHeight();
478                 }
479                 else
480                 {
481                     ChgWinHeight(); ChgSBfHeight();
482                 }
483             }
484             else ChgSBfHeight();
485         }
486         else if (TstWinHeight()) ChgWinHeight();
487     } while (0);
488 #undef TstSBfWidth
489 #undef TstWinWidth
490 #undef ChgSBfWidth
491 #undef ChgWinWidth
492 #undef TstSBfHeight
493 #undef TstWinHeight
494 #undef ChgSBfHeight
495 #undef ChgWinHeight
496
497     data->curcfg.exit_on_die = cfg->exit_on_die;
498     if (force || data->curcfg.edition_mode != cfg->edition_mode)
499     {
500         data->curcfg.edition_mode = cfg->edition_mode;
501         WINECON_SetEditionMode(data->hConIn, cfg->edition_mode);
502     }
503     /* we now need to gather all events we got from the operations above,
504      * in order to get data correctly updated
505      */
506     WINECON_GrabChanges(data);
507 }
508
509 /******************************************************************
510  *              WINECON_Delete
511  *
512  * Destroy wineconsole internal data
513  */
514 static void WINECON_Delete(struct inner_data* data)
515 {
516     if (!data) return;
517
518     if (data->fnDeleteBackend)  data->fnDeleteBackend(data);
519     if (data->hConIn)           CloseHandle(data->hConIn);
520     if (data->hConOut)          CloseHandle(data->hConOut);
521     if (data->hSynchro)         CloseHandle(data->hSynchro);
522     HeapFree(GetProcessHeap(), 0, data->cells);
523     HeapFree(GetProcessHeap(), 0, data);
524 }
525
526 /******************************************************************
527  *              WINECON_Init
528  *
529  * Initialisation part I. Creation of server object (console input and
530  * active screen buffer)
531  */
532 static struct inner_data* WINECON_Init(HINSTANCE hInst, DWORD pid, LPCWSTR appname,
533                                        enum init_return (*backend)(struct inner_data*))
534 {
535     struct inner_data*  data = NULL;
536     DWORD               ret;
537     struct config_data  cfg;
538     STARTUPINFOW        si;
539
540     data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data));
541     if (!data) return 0;
542
543     GetStartupInfo(&si);
544
545     if (pid == 0)
546     {
547         if (!si.lpTitle) WINECON_Fatal("Should have a title set");
548         appname = si.lpTitle;
549     }
550
551     /* load settings */
552     WINECON_RegLoad(appname, &cfg);
553
554     /* some overrides */
555     if (pid == 0)
556     {
557         if (si.dwFlags & STARTF_USECOUNTCHARS)
558         {
559             cfg.sb_width  = si.dwXCountChars;
560             cfg.sb_height = si.dwYCountChars;
561         }
562         if (si.dwFlags & STARTF_USEFILLATTRIBUTE)
563             cfg.def_attr = si.dwFillAttribute;
564         /* should always be defined */
565     }
566
567     /* the handles here are created without the whistles and bells required by console
568      * (mainly because wineconsole doesn't need it)
569      * - they are not inheritable
570      * - hConIn is not synchronizable
571      */
572     SERVER_START_REQ(alloc_console)
573     {
574         req->access     = GENERIC_READ | GENERIC_WRITE;
575         req->inherit    = FALSE;
576         req->pid        = pid;
577
578         ret = !wine_server_call_err( req );
579         data->hConIn = (HANDLE)reply->handle_in;
580         data->hSynchro = (HANDLE)reply->event;
581     }
582     SERVER_END_REQ;
583     if (!ret) goto error;
584     WINE_TRACE("using hConIn %p, hSynchro event %p\n", data->hConIn, data->hSynchro);
585
586     SERVER_START_REQ( set_console_input_info )
587     {
588         req->handle = (obj_handle_t)data->hConIn;
589         req->mask = SET_CONSOLE_INPUT_INFO_TITLE;
590         wine_server_add_data( req, appname, lstrlenW(appname) * sizeof(WCHAR) );
591         ret = !wine_server_call_err( req );
592     }
593     SERVER_END_REQ;
594     if (!ret) goto error;
595
596     SERVER_START_REQ(create_console_output)
597     {
598         req->handle_in = (obj_handle_t)data->hConIn;
599         req->access    = GENERIC_WRITE|GENERIC_READ;
600         req->share     = FILE_SHARE_READ|FILE_SHARE_WRITE;
601         req->inherit   = FALSE;
602         ret = !wine_server_call_err( req );
603         data->hConOut  = (HANDLE)reply->handle_out;
604     }
605     SERVER_END_REQ;
606     if (!ret) goto error;
607     WINE_TRACE("using hConOut %p\n", data->hConOut);
608
609     /* filling data->curcfg from cfg */
610  retry:
611     switch ((*backend)(data))
612     {
613     case init_success:
614         WINECON_SetConfig(data, &cfg, TRUE);
615         data->curcfg.registry = cfg.registry;
616         WINECON_DumpConfig("fint", &data->curcfg);
617         return data;
618     case init_failed:
619         break;
620     case init_not_supported:
621         if (backend == WCCURSES_InitBackend)
622         {
623             WINE_ERR("(n)curses was not found at configuration time.\n"
624                      "If you want (n)curses support, please install relevant packages.\n"
625                      "Now forcing user backend instead of (n)curses.\n");
626             backend = WCUSER_InitBackend;
627             goto retry;
628         }
629         break;
630     }
631
632  error:
633     WINE_ERR("failed to init.\n");
634
635     WINECON_Delete(data);
636     return NULL;
637 }
638
639 /******************************************************************
640  *              WINECON_Spawn
641  *
642  * Spawn the child process when invoked with wineconsole foo bar
643  */
644 static BOOL WINECON_Spawn(struct inner_data* data, LPWSTR cmdLine)
645 {
646     PROCESS_INFORMATION info;
647     STARTUPINFO         startup;
648     BOOL                done;
649
650     /* we're in the case wineconsole <exe> <options>... spawn the new process */
651     memset(&startup, 0, sizeof(startup));
652     startup.cb          = sizeof(startup);
653     startup.dwFlags     = STARTF_USESTDHANDLES;
654
655     /* the attributes of wineconsole's handles are not adequate for inheritance, so
656      * get them with the correct attributes before process creation
657      */
658     if (!DuplicateHandle(GetCurrentProcess(), data->hConIn,  GetCurrentProcess(),
659                          &startup.hStdInput, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE, TRUE, 0) ||
660         !DuplicateHandle(GetCurrentProcess(), data->hConOut, GetCurrentProcess(),
661                          &startup.hStdOutput, GENERIC_READ|GENERIC_WRITE, TRUE, 0) ||
662         !DuplicateHandle(GetCurrentProcess(), data->hConOut, GetCurrentProcess(),
663                          &startup.hStdError, GENERIC_READ|GENERIC_WRITE, TRUE, 0))
664     {
665         WINE_ERR("Can't dup handles\n");
666         /* no need to delete handles, we're exiting the programm anyway */
667         return FALSE;
668     }
669
670     done = CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, 0L, NULL, NULL, &startup, &info);
671
672     /* we no longer need the handles passed to the child for the console */
673     CloseHandle(startup.hStdInput);
674     CloseHandle(startup.hStdOutput);
675     CloseHandle(startup.hStdError);
676
677     CloseHandle(info.hProcess);
678     CloseHandle(info.hThread);
679
680     return done;
681 }
682
683 struct wc_init {
684     LPCSTR              ptr;
685     enum {from_event, from_process_name} mode;
686     enum init_return    (*backend)(struct inner_data*);
687     HANDLE              event;
688 };
689
690 /******************************************************************
691  *               WINECON_ParseOptions
692  *
693  *
694  */
695 static BOOL WINECON_ParseOptions(const char* lpCmdLine, struct wc_init* wci)
696 {
697     memset(wci, 0, sizeof(*wci));
698     wci->ptr = lpCmdLine;
699     wci->mode = from_process_name;
700     wci->backend = WCCURSES_InitBackend;
701
702     for (;;)
703     {
704         while (*wci->ptr == ' ' || *wci->ptr == '\t') wci->ptr++;
705         if (wci->ptr[0] != '-') break;
706         if (strncmp(wci->ptr, "--use-event=", 12) == 0)
707         {
708             char*           end;
709             wci->event = (HANDLE)strtol(wci->ptr + 12, &end, 10);
710             if (end == wci->ptr + 12) return FALSE;
711             wci->mode = from_event;
712             wci->ptr = end;
713             wci->backend = WCUSER_InitBackend;
714         }
715         else if (strncmp(wci->ptr, "--backend=", 10) == 0)
716         {
717             if (strncmp(wci->ptr + 10, "user", 4) == 0)
718             {
719                 wci->backend = WCUSER_InitBackend;
720                 wci->ptr += 14;
721             }
722             else if (strncmp(wci->ptr + 10, "curses", 6) == 0)
723             {
724                 wci->ptr += 16;
725             }
726             else
727                 return FALSE;
728         }
729         else
730             return FALSE;
731     }
732
733     return TRUE;
734 }
735
736 /******************************************************************
737  *              WinMain
738  *
739  * wineconsole can either be started as:
740  *      wineconsole --use-event=<int>   used when a new console is created (AllocConsole)
741  *      wineconsole <pgm> <arguments>   used to start the program <pgm> from the command line in
742  *                                      a freshly created console
743  * --backend=(curses|user) can also be used to select the desired backend
744  */
745 int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, INT nCmdShow)
746 {
747     struct inner_data*  data;
748     int                 ret = 1;
749     struct wc_init      wci;
750
751     if (!WINECON_ParseOptions(lpCmdLine, &wci))
752     {
753         WINE_ERR("Wrong command line options\n");
754         return 0;
755     }
756
757     switch (wci.mode)
758     {
759     case from_event:
760         /* case of wineconsole <evt>, signal process that created us that we're up and running */
761         if (!(data = WINECON_Init(hInst, 0, NULL, wci.backend))) return 0;
762         ret = SetEvent(wci.event);
763         if (!ret) WINE_ERR("SetEvent failed.\n");
764         break;
765     case from_process_name:
766         {
767             WCHAR           buffer[256];
768
769             MultiByteToWideChar(CP_ACP, 0, wci.ptr, -1, buffer, sizeof(buffer) / sizeof(buffer[0]));
770
771             if (!(data = WINECON_Init(hInst, GetCurrentProcessId(), buffer, wci.backend)))
772                 return 0;
773             ret = WINECON_Spawn(data, buffer);
774             if (!ret)
775                 WINE_MESSAGE("wineconsole: spawning client program failed (%s), invalid/missing command line arguments ?\n", wine_dbgstr_w(buffer));
776         }
777         break;
778     default:
779         return 0;
780     }
781
782     if (ret)
783     {
784         WINE_TRACE("calling MainLoop.\n");
785         ret = data->fnMainLoop(data);
786     }
787
788     WINECON_Delete(data);
789
790     return ret;
791 }