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