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