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