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