wineconsole: Make some functions static.
[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(void)
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 static 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 = wine_server_obj_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       = wine_server_obj_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 = wine_server_obj_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 = wine_server_obj_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 = wine_server_obj_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 = wine_server_obj_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 = wine_server_obj_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 = wine_server_obj_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 = wine_server_obj_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       = wine_server_obj_handle( 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 : wine_server_ptr_handle(reply->handle);
305             }
306             SERVER_END_REQ;
307             WINE_TRACE(" active(%p)", 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 = wine_server_obj_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 = wine_server_obj_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 = wine_server_ptr_handle( reply->handle_in );
639         data->hSynchro = wine_server_ptr_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(create_console_output)
646     {
647         req->handle_in  = wine_server_obj_handle( data->hConIn );
648         req->access     = GENERIC_WRITE|GENERIC_READ;
649         req->attributes = 0;
650         req->share      = FILE_SHARE_READ|FILE_SHARE_WRITE;
651         ret = !wine_server_call_err( req );
652         data->hConOut   = wine_server_ptr_handle( reply->handle_out );
653     }
654     SERVER_END_REQ;
655     if (!ret) goto error;
656     WINE_TRACE("using hConOut %p\n", data->hConOut);
657
658     /* filling data->curcfg from cfg */
659     switch ((*backend)(data))
660     {
661     case init_not_supported:
662         if (backend == WCCURSES_InitBackend)
663         {
664             if (WCUSER_InitBackend( data ) != init_success) break;
665         }
666         else if (backend == WCUSER_InitBackend)
667         {
668             if (WCCURSES_InitBackend( data ) != init_success) break;
669         }
670         /* fall through */
671     case init_success:
672         WINECON_GetServerConfig(data);
673         data->cells = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
674                                 data->curcfg.sb_width * data->curcfg.sb_height * sizeof(CHAR_INFO));
675         if (!data->cells) WINECON_Fatal("OOM\n");
676         data->fnResizeScreenBuffer(data);
677         data->fnComputePositions(data);
678         WINECON_SetConfig(data, &cfg);
679         data->curcfg.registry = cfg.registry;
680         WINECON_DumpConfig("fint", &data->curcfg);
681         SERVER_START_REQ( set_console_input_info )
682         {
683             req->handle = wine_server_obj_handle( data->hConIn );
684             req->win = wine_server_user_handle( data->hWnd );
685             req->mask = SET_CONSOLE_INPUT_INFO_TITLE |
686                         SET_CONSOLE_INPUT_INFO_WIN;
687             wine_server_add_data( req, appname, lstrlenW(appname) * sizeof(WCHAR) );
688             ret = !wine_server_call_err( req );
689         }
690         SERVER_END_REQ;
691         if (!ret) goto error;
692
693         return data;
694     case init_failed:
695         break;
696     }
697
698  error:
699     WINE_ERR("failed to init.\n");
700
701     WINECON_Delete(data);
702     return NULL;
703 }
704
705 /******************************************************************
706  *              WINECON_Spawn
707  *
708  * Spawn the child process when invoked with wineconsole foo bar
709  */
710 static BOOL WINECON_Spawn(struct inner_data* data, LPWSTR cmdLine)
711 {
712     PROCESS_INFORMATION info;
713     STARTUPINFO         startup;
714     BOOL                done;
715
716     /* we're in the case wineconsole <exe> <options>... spawn the new process */
717     memset(&startup, 0, sizeof(startup));
718     startup.cb          = sizeof(startup);
719     startup.dwFlags     = STARTF_USESTDHANDLES;
720
721     /* the attributes of wineconsole's handles are not adequate for inheritance, so
722      * get them with the correct attributes before process creation
723      */
724     if (!DuplicateHandle(GetCurrentProcess(), data->hConIn,  GetCurrentProcess(),
725                          &startup.hStdInput, GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE, TRUE, 0) ||
726         !DuplicateHandle(GetCurrentProcess(), data->hConOut, GetCurrentProcess(),
727                          &startup.hStdOutput, GENERIC_READ|GENERIC_WRITE, TRUE, 0) ||
728         !DuplicateHandle(GetCurrentProcess(), data->hConOut, GetCurrentProcess(),
729                          &startup.hStdError, GENERIC_READ|GENERIC_WRITE, TRUE, 0))
730     {
731         WINE_ERR("Can't dup handles\n");
732         /* no need to delete handles, we're exiting the program anyway */
733         return FALSE;
734     }
735
736     done = CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, 0L, NULL, NULL, &startup, &info);
737
738     /* we no longer need the handles passed to the child for the console */
739     CloseHandle(startup.hStdInput);
740     CloseHandle(startup.hStdOutput);
741     CloseHandle(startup.hStdError);
742
743     CloseHandle(info.hProcess);
744     CloseHandle(info.hThread);
745
746     return done;
747 }
748
749 struct wc_init {
750     LPCSTR              ptr;
751     enum {from_event, from_process_name} mode;
752     enum init_return    (*backend)(struct inner_data*);
753     HANDLE              event;
754 };
755
756 #define WINECON_CMD_SHOW_USAGE 0x10000
757
758 /******************************************************************
759  *               WINECON_ParseOptions
760  *
761  * RETURNS
762  *   On success: 0
763  *   On error:   error string id optionally with the CMD_SHOW_USAGE flag
764  */
765 static UINT WINECON_ParseOptions(const char* lpCmdLine, struct wc_init* wci)
766 {
767     memset(wci, 0, sizeof(*wci));
768     wci->ptr = lpCmdLine;
769     wci->mode = from_process_name;
770     wci->backend = WCUSER_InitBackend;
771
772     for (;;)
773     {
774         while (*wci->ptr == ' ' || *wci->ptr == '\t') wci->ptr++;
775         if (wci->ptr[0] != '-') break;
776         if (strncmp(wci->ptr, "--use-event=", 12) == 0)
777         {
778             char*           end;
779             wci->event = (HANDLE)strtol(wci->ptr + 12, &end, 10);
780             if (end == wci->ptr + 12) return IDS_CMD_INVALID_EVENT_ID;
781             wci->mode = from_event;
782             wci->ptr = end;
783             wci->backend = WCUSER_InitBackend;
784         }
785         else if (strncmp(wci->ptr, "--backend=", 10) == 0)
786         {
787             if (strncmp(wci->ptr + 10, "user", 4) == 0)
788             {
789                 wci->backend = WCUSER_InitBackend;
790                 wci->ptr += 14;
791             }
792             else if (strncmp(wci->ptr + 10, "curses", 6) == 0)
793             {
794                 wci->backend = WCCURSES_InitBackend;
795                 wci->ptr += 16;
796             }
797             else
798                 return IDS_CMD_INVALID_BACKEND;
799         }
800         else
801             return IDS_CMD_INVALID_OPTION|WINECON_CMD_SHOW_USAGE;
802     }
803
804     if (wci->mode == from_event)
805         return 0;
806
807     while (*wci->ptr == ' ' || *wci->ptr == '\t') wci->ptr++;
808     if (*wci->ptr == 0)
809         return IDS_CMD_ABOUT|WINECON_CMD_SHOW_USAGE;
810
811     return 0;
812 }
813
814 /******************************************************************
815  *              WinMain
816  *
817  * wineconsole can either be started as:
818  *      wineconsole --use-event=<int>   used when a new console is created (AllocConsole)
819  *      wineconsole <pgm> <arguments>   used to start the program <pgm> from the command line in
820  *                                      a freshly created console
821  * --backend=(curses|user) can also be used to select the desired backend
822  */
823 int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, INT nCmdShow)
824 {
825     struct inner_data*  data;
826     int                 ret = 1;
827     struct wc_init      wci;
828
829     if ((ret = WINECON_ParseOptions(lpCmdLine, &wci)) != 0)
830     {
831         printf_res(ret & 0xffff);
832         if (ret & WINECON_CMD_SHOW_USAGE)
833             WINECON_Usage();
834         return 0;
835     }
836
837     switch (wci.mode)
838     {
839     case from_event:
840         /* case of wineconsole <evt>, signal process that created us that we're up and running */
841         if (!(data = WINECON_Init(hInst, 0, NULL, wci.backend, nCmdShow))) return 0;
842         ret = SetEvent(wci.event);
843         if (!ret) WINE_ERR("SetEvent failed.\n");
844         break;
845     case from_process_name:
846         {
847             WCHAR           buffer[256];
848
849             MultiByteToWideChar(CP_ACP, 0, wci.ptr, -1, buffer, sizeof(buffer) / sizeof(buffer[0]));
850
851             if (!(data = WINECON_Init(hInst, GetCurrentProcessId(), buffer, wci.backend, nCmdShow)))
852                 return 0;
853             ret = WINECON_Spawn(data, buffer);
854             if (!ret)
855             {
856                 WINECON_Delete(data);
857                 printf_res(IDS_CMD_LAUNCH_FAILED, wine_dbgstr_a(wci.ptr));
858                 return 0;
859             }
860         }
861         break;
862     default:
863         return 0;
864     }
865
866     if (ret)
867     {
868         WINE_TRACE("calling MainLoop.\n");
869         ret = data->fnMainLoop(data);
870     }
871
872     WINECON_Delete(data);
873
874     return ret;
875 }