msvcp60: Fixed vtables in IO classes.
[wine] / programs / wineconsole / user.c
1 /*
2  * a GUI application for displaying a console
3  *      USER32 back end
4  * Copyright 2001 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 <stdio.h>
22 #include <stdlib.h>
23 #include "winecon_user.h"
24 #include "winnls.h"
25
26 #include "wine/debug.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(wineconsole);
29 WINE_DECLARE_DEBUG_CHANNEL(wc_font);
30
31 UINT g_uiDefaultCharset;
32
33 /* mapping console colors to RGB values */
34 const COLORREF WCUSER_ColorMap[16] =
35 {
36     RGB(0x00, 0x00, 0x00), RGB(0x00, 0x00, 0x80), RGB(0x00, 0x80, 0x00), RGB(0x00, 0x80, 0x80),
37     RGB(0x80, 0x00, 0x00), RGB(0x80, 0x00, 0x80), RGB(0x80, 0x80, 0x00), RGB(0xC0, 0xC0, 0xC0),
38     RGB(0x80, 0x80, 0x80), RGB(0x00, 0x00, 0xFF), RGB(0x00, 0xFF, 0x00), RGB(0x00, 0xFF, 0xFF),
39     RGB(0xFF, 0x00, 0x00), RGB(0xFF, 0x00, 0xFF), RGB(0xFF, 0xFF, 0x00), RGB(0xFF, 0xFF, 0xFF),
40 };
41
42 static BOOL WCUSER_SetFont(struct inner_data* data, const LOGFONTW* font);
43
44 /******************************************************************
45  *              WCUSER_FillMemDC
46  *
47  * Fills the Mem DC with current cells values
48  */
49 static void WCUSER_FillMemDC(const struct inner_data* data, int upd_tp, int upd_bm)
50 {
51     unsigned            i, j, k;
52     CHAR_INFO*          cell;
53     HFONT               hOldFont;
54     WORD                attr;
55     WCHAR*              line;
56     RECT                r;
57     HBRUSH              hbr;
58
59     /* no font has been set up yet, don't worry about filling the bitmap,
60      * we'll do it once a font is chosen
61      */
62     if (!PRIVATE(data)->hFont) return;
63
64     /* FIXME: could set up a mechanism to reuse the line between different
65      * calls to this function
66      */
67     if (!(line = HeapAlloc(GetProcessHeap(), 0, data->curcfg.sb_width * sizeof(WCHAR))))
68         WINECON_Fatal("OOM\n");
69
70     hOldFont = SelectObject(PRIVATE(data)->hMemDC, PRIVATE(data)->hFont);
71     for (j = upd_tp; j <= upd_bm; j++)
72     {
73         cell = &data->cells[j * data->curcfg.sb_width];
74         for (i = 0; i < data->curcfg.sb_width; i++)
75         {
76             attr = cell[i].Attributes;
77             SetBkColor(PRIVATE(data)->hMemDC, WCUSER_ColorMap[(attr>>4)&0x0F]);
78             SetTextColor(PRIVATE(data)->hMemDC, WCUSER_ColorMap[attr&0x0F]);
79             for (k = i; k < data->curcfg.sb_width && cell[k].Attributes == attr; k++)
80             {
81                 line[k - i] = cell[k].Char.UnicodeChar;
82             }
83             TextOutW(PRIVATE(data)->hMemDC, i * data->curcfg.cell_width,
84                      j * data->curcfg.cell_height, line, k - i);
85             if (PRIVATE(data)->ext_leading && 
86                 (hbr = CreateSolidBrush(WCUSER_ColorMap[(attr>>4)&0x0F])))
87             {
88                 r.left   = i * data->curcfg.cell_width;
89                 r.top    = (j + 1) * data->curcfg.cell_height - PRIVATE(data)->ext_leading;
90                 r.right  = k * data->curcfg.cell_width;
91                 r.bottom = (j + 1) * data->curcfg.cell_height;
92                 FillRect(PRIVATE(data)->hMemDC, &r, hbr);
93                 DeleteObject(hbr);
94             }
95             i = k - 1;
96         }
97     }
98     SelectObject(PRIVATE(data)->hMemDC, hOldFont);
99     HeapFree(GetProcessHeap(), 0, line);
100 }
101
102 /******************************************************************
103  *              WCUSER_NewBitmap
104  *
105  * Either the font geometry or the sb geometry has changed. we need
106  * to recreate the bitmap geometry.
107  */
108 static void WCUSER_NewBitmap(struct inner_data* data)
109 {
110     HDC         hDC;
111     HBITMAP     hnew, hold;
112
113     if (!data->curcfg.sb_width || !data->curcfg.sb_height ||
114         !PRIVATE(data)->hFont || !(hDC = GetDC(data->hWnd)))
115         return;
116     hnew = CreateCompatibleBitmap(hDC,
117                                   data->curcfg.sb_width  * data->curcfg.cell_width,
118                                   data->curcfg.sb_height * data->curcfg.cell_height);
119     ReleaseDC(data->hWnd, hDC);
120     hold = SelectObject(PRIVATE(data)->hMemDC, hnew);
121
122     if (PRIVATE(data)->hBitmap)
123     {
124         if (hold == PRIVATE(data)->hBitmap)
125             DeleteObject(PRIVATE(data)->hBitmap);
126         else
127             WINE_FIXME("leak\n");
128     }
129     PRIVATE(data)->hBitmap = hnew;
130     WCUSER_FillMemDC(data, 0, data->curcfg.sb_height - 1);
131 }
132
133 /******************************************************************
134  *              WCUSER_ResizeScreenBuffer
135  *
136  *
137  */
138 static void WCUSER_ResizeScreenBuffer(struct inner_data* data)
139 {
140     WCUSER_NewBitmap(data);
141 }
142
143 /******************************************************************
144  *              WCUSER_PosCursor
145  *
146  * Set a new position for the cursor
147  */
148 static void     WCUSER_PosCursor(const struct inner_data* data)
149 {
150     if (data->hWnd != GetFocus() || !data->curcfg.cursor_visible) return;
151
152     SetCaretPos((data->cursor.X - data->curcfg.win_pos.X) * data->curcfg.cell_width,
153                 (data->cursor.Y - data->curcfg.win_pos.Y) * data->curcfg.cell_height);
154     ShowCaret(data->hWnd);
155 }
156
157 /******************************************************************
158  *              WCUSER_ShapeCursor
159  *
160  * Sets a new shape for the cursor
161  */
162 static void     WCUSER_ShapeCursor(struct inner_data* data, int size, int vis, BOOL force)
163 {
164     if (force || size != data->curcfg.cursor_size)
165     {
166         if (data->curcfg.cursor_visible && data->hWnd == GetFocus()) DestroyCaret();
167         if (PRIVATE(data)->cursor_bitmap) DeleteObject(PRIVATE(data)->cursor_bitmap);
168         PRIVATE(data)->cursor_bitmap = NULL;
169         if (size != 100)
170         {
171             int         w16b; /* number of bytes per row, aligned on word size */
172             BYTE*       ptr;
173             int         i, j, nbl;
174
175             w16b = ((data->curcfg.cell_width + 15) & ~15) / 8;
176             ptr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, w16b * data->curcfg.cell_height);
177             if (!ptr) WINECON_Fatal("OOM");
178             nbl = max((data->curcfg.cell_height * size) / 100, 1);
179             for (j = data->curcfg.cell_height - nbl; j < data->curcfg.cell_height; j++)
180             {
181                 for (i = 0; i < data->curcfg.cell_width; i++)
182                 {
183                     ptr[w16b * j + (i / 8)] |= 0x80 >> (i & 7);
184                 }
185             }
186             PRIVATE(data)->cursor_bitmap = CreateBitmap(data->curcfg.cell_width,
187                                                data->curcfg.cell_height, 1, 1, ptr);
188             HeapFree(GetProcessHeap(), 0, ptr);
189         }
190         data->curcfg.cursor_size = size;
191         data->curcfg.cursor_visible = -1;
192     }
193
194     vis = vis != 0;
195     if (force || vis != data->curcfg.cursor_visible)
196     {
197         data->curcfg.cursor_visible = vis;
198         if (data->hWnd == GetFocus())
199         {
200             if (vis)
201             {
202                 CreateCaret(data->hWnd, PRIVATE(data)->cursor_bitmap,
203                             data->curcfg.cell_width, data->curcfg.cell_height);
204                 WCUSER_PosCursor(data);
205             }
206             else
207             {
208                 DestroyCaret();
209             }
210         }
211     }
212     WINECON_DumpConfig("crsr", &data->curcfg);
213 }
214
215 /******************************************************************
216  *              WCUSER_ComputePositions
217  *
218  * Recomputes all the components (mainly scroll bars) positions
219  */
220 static void     WCUSER_ComputePositions(struct inner_data* data)
221 {
222     RECT                r;
223     int                 dx, dy;
224
225     /* compute window size from desired client size */
226     r.left = r.top = 0;
227     r.right = data->curcfg.win_width * data->curcfg.cell_width;
228     r.bottom = data->curcfg.win_height * data->curcfg.cell_height;
229
230     if (IsRectEmpty(&r)) return;
231
232     AdjustWindowRect(&r, GetWindowLongW(data->hWnd, GWL_STYLE), FALSE);
233
234     dx = dy = 0;
235     if (data->curcfg.sb_width > data->curcfg.win_width)
236     {
237         dy = GetSystemMetrics(SM_CYHSCROLL);
238         SetScrollRange(data->hWnd, SB_HORZ, 0,
239                        data->curcfg.sb_width - data->curcfg.win_width, FALSE);
240         SetScrollPos(data->hWnd, SB_HORZ, 0, FALSE); /* FIXME */
241         ShowScrollBar(data->hWnd, SB_HORZ, TRUE);
242     }
243     else
244     {
245         ShowScrollBar(data->hWnd, SB_HORZ, FALSE);
246     }
247
248     if (data->curcfg.sb_height > data->curcfg.win_height)
249     {
250         dx = GetSystemMetrics(SM_CXVSCROLL);
251         SetScrollRange(data->hWnd, SB_VERT, 0,
252                        data->curcfg.sb_height - data->curcfg.win_height, FALSE);
253         SetScrollPos(data->hWnd, SB_VERT, 0, FALSE); /* FIXME */
254         ShowScrollBar(data->hWnd, SB_VERT, TRUE);
255     }
256     else
257     {
258         ShowScrollBar(data->hWnd, SB_VERT, FALSE);
259     }
260
261     SetWindowPos(data->hWnd, 0, 0, 0, r.right - r.left + dx, r.bottom - r.top + dy,
262                  SWP_NOMOVE|SWP_NOZORDER);
263     WCUSER_ShapeCursor(data, data->curcfg.cursor_size, data->curcfg.cursor_visible, TRUE);
264     WCUSER_PosCursor(data);
265 }
266
267 /******************************************************************
268  *              WCUSER_SetTitle
269  *
270  * Sets the title to the wine console
271  */
272 static void     WCUSER_SetTitle(const struct inner_data* data)
273 {
274     WCHAR       buffer[256];
275
276     if (WINECON_GetConsoleTitle(data->hConIn, buffer, sizeof(buffer)))
277         SetWindowTextW(data->hWnd, buffer);
278 }
279
280 void WCUSER_DumpLogFont(const char* pfx, const LOGFONTW* lf, DWORD ft)
281 {
282     WINE_TRACE_(wc_font)("%s %s%s%s%s\n"
283                          "\tlf.lfHeight=%d lf.lfWidth=%d lf.lfEscapement=%d lf.lfOrientation=%d\n"
284                          "\tlf.lfWeight=%d lf.lfItalic=%u lf.lfUnderline=%u lf.lfStrikeOut=%u\n"
285                          "\tlf.lfCharSet=%u lf.lfOutPrecision=%u lf.lfClipPrecision=%u lf.lfQuality=%u\n"
286                          "\tlf->lfPitchAndFamily=%u lf.lfFaceName=%s\n",
287                          pfx,
288                          (ft & RASTER_FONTTYPE) ? "raster" : "",
289                          (ft & TRUETYPE_FONTTYPE) ? "truetype" : "",
290                          ((ft & (RASTER_FONTTYPE|TRUETYPE_FONTTYPE)) == 0) ? "vector" : "",
291                          (ft & DEVICE_FONTTYPE) ? "|device" : "",
292                          lf->lfHeight, lf->lfWidth, lf->lfEscapement, lf->lfOrientation,
293                          lf->lfWeight, lf->lfItalic, lf->lfUnderline, lf->lfStrikeOut, lf->lfCharSet,
294                          lf->lfOutPrecision, lf->lfClipPrecision, lf->lfQuality, lf->lfPitchAndFamily,
295                          wine_dbgstr_w(lf->lfFaceName));
296 }
297
298 void WCUSER_DumpTextMetric(const TEXTMETRICW* tm, DWORD ft)
299 {
300     WINE_TRACE_(wc_font)("%s%s%s%s\n"
301                          "\ttmHeight=%d tmAscent=%d tmDescent=%d tmInternalLeading=%d tmExternalLeading=%d\n"
302                          "\ttmAveCharWidth=%d tmMaxCharWidth=%d tmWeight=%d tmOverhang=%d\n"
303                          "\ttmDigitizedAspectX=%d tmDigitizedAspectY=%d\n"
304                          "\ttmFirstChar=%d tmLastChar=%d tmDefaultChar=%d tmBreakChar=%d\n"
305                          "\ttmItalic=%u tmUnderlined=%u tmStruckOut=%u tmPitchAndFamily=%u tmCharSet=%u\n",
306                          (ft & RASTER_FONTTYPE) ? "raster" : "",
307                          (ft & TRUETYPE_FONTTYPE) ? "truetype" : "",
308                          ((ft & (RASTER_FONTTYPE|TRUETYPE_FONTTYPE)) == 0) ? "vector" : "",
309                          (ft & DEVICE_FONTTYPE) ? "|device" : "",
310                          tm->tmHeight, tm->tmAscent, tm->tmDescent, tm->tmInternalLeading, tm->tmExternalLeading, tm->tmAveCharWidth,
311                          tm->tmMaxCharWidth, tm->tmWeight, tm->tmOverhang, tm->tmDigitizedAspectX, tm->tmDigitizedAspectY,
312                          tm->tmFirstChar, tm->tmLastChar, tm->tmDefaultChar, tm->tmBreakChar, tm->tmItalic, tm->tmUnderlined, tm->tmStruckOut,
313                          tm->tmPitchAndFamily, tm->tmCharSet);
314 }
315
316 /******************************************************************
317  *              WCUSER_AreFontsEqual
318  *
319  *
320  */
321 static BOOL WCUSER_AreFontsEqual(const struct config_data* config, const LOGFONTW* lf)
322 {
323     return lf->lfHeight == config->cell_height &&
324         lf->lfWeight == config->font_weight &&
325         !lf->lfItalic && !lf->lfUnderline && !lf->lfStrikeOut &&
326         !lstrcmpW(lf->lfFaceName, config->face_name);
327 }
328
329 struct font_chooser
330 {
331     struct inner_data*  data;
332     int                 done;
333 };
334
335 /******************************************************************
336  *              WCUSER_ValidateFontMetric
337  *
338  * Returns true if the font described in tm is usable as a font for the renderer
339  */
340 BOOL WCUSER_ValidateFontMetric(const struct inner_data* data, const TEXTMETRICW* tm, DWORD fontType)
341 {
342     BOOL        ret = TRUE;
343
344     if (fontType & RASTER_FONTTYPE)
345         ret = (tm->tmMaxCharWidth * data->curcfg.win_width < GetSystemMetrics(SM_CXSCREEN) &&
346                tm->tmHeight * data->curcfg.win_height < GetSystemMetrics(SM_CYSCREEN));
347     return ret && !tm->tmItalic && !tm->tmUnderlined && !tm->tmStruckOut &&
348         (tm->tmCharSet == DEFAULT_CHARSET || tm->tmCharSet == g_uiDefaultCharset);
349 }
350
351 /******************************************************************
352  *              WCUSER_ValidateFont
353  *
354  * Returns true if the font family described in lf is usable as a font for the renderer
355  */
356 BOOL WCUSER_ValidateFont(const struct inner_data* data, const LOGFONTW* lf)
357 {
358     return (lf->lfPitchAndFamily & 3) == FIXED_PITCH &&
359         /* (lf->lfPitchAndFamily & 0xF0) == FF_MODERN && */
360         (lf->lfCharSet == DEFAULT_CHARSET || lf->lfCharSet == g_uiDefaultCharset);
361 }
362
363 /******************************************************************
364  *              get_first_font_enum_2
365  *              get_first_font_enum
366  *
367  * Helper functions to get a decent font for the renderer
368  */
369 static int CALLBACK get_first_font_enum_2(const LOGFONTW* lf, const TEXTMETRICW* tm,
370                                           DWORD FontType, LPARAM lParam)
371 {
372     struct font_chooser*        fc = (struct font_chooser*)lParam;
373
374     WCUSER_DumpTextMetric(tm, FontType);
375     if (WCUSER_ValidateFontMetric(fc->data, tm, FontType))
376     {
377         LOGFONTW mlf = *lf;
378
379         /* Use the default sizes for the font (this is needed, especially for
380          * TrueType fonts, so that we get a decent size, not the max size)
381          */
382         mlf.lfWidth  = fc->data->curcfg.cell_width;
383         mlf.lfHeight = fc->data->curcfg.cell_height;
384         if (WCUSER_SetFont(fc->data, &mlf))
385         {
386             struct      config_data     defcfg;
387
388             WCUSER_DumpLogFont("InitChoosing: ", &mlf, FontType);
389             fc->done = 1;
390             /* since we've modified the current config with new font information,
391              * set this information as the new default.
392              */
393             WINECON_RegLoad(NULL, &defcfg);
394             defcfg.cell_width = fc->data->curcfg.cell_width;
395             defcfg.cell_height = fc->data->curcfg.cell_height;
396             lstrcpyW(defcfg.face_name, fc->data->curcfg.face_name);
397             /* Force also its writing back to the registry so that we can get it
398              * the next time.
399              */
400             WINECON_RegSave(&defcfg);
401             return 0;
402         }
403     }
404     return 1;
405 }
406
407 static int CALLBACK get_first_font_enum(const LOGFONTW* lf, const TEXTMETRICW* tm,
408                                         DWORD FontType, LPARAM lParam)
409 {
410     struct font_chooser*        fc = (struct font_chooser*)lParam;
411
412     WCUSER_DumpLogFont("InitFamily: ", lf, FontType);
413     if (WCUSER_ValidateFont(fc->data, lf))
414     {
415         EnumFontFamiliesW(PRIVATE(fc->data)->hMemDC, lf->lfFaceName,
416                           get_first_font_enum_2, lParam);
417         return !fc->done; /* we just need the first matching one... */
418     }
419     return 1;
420 }
421
422 /******************************************************************
423  *              WCUSER_CopyFont
424  *
425  * get the relevant information from the font described in lf and store them
426  * in config
427  */
428 HFONT WCUSER_CopyFont(struct config_data* config, HWND hWnd, const LOGFONTW* lf, LONG* el)
429 {
430     TEXTMETRICW tm;
431     HDC         hDC;
432     HFONT       hFont, hOldFont;
433     int         w, i, buf[256];
434
435     if (!(hDC = GetDC(hWnd))) return NULL;
436     if (!(hFont = CreateFontIndirectW(lf))) goto err1;
437
438     hOldFont = SelectObject(hDC, hFont);
439     GetTextMetricsW(hDC, &tm);
440
441     /* FIXME:
442      * the current freetype engine (at least 2.0.x with x <= 8) and its implementation
443      * in Wine don't return adequate values for fixed fonts
444      * In Windows, those fonts are expected to return the same value for
445      *  - the average width
446      *  - the largest width
447      *  - the width of all characters in the font
448      * This isn't true in Wine. As a temporary workaround, we get as the width of the
449      * cell, the width of the first character in the font, after checking that all
450      * characters in the font have the same width (I hear paranoia coming)
451      * when this gets fixed, the code should be using tm.tmAveCharWidth
452      * or tm.tmMaxCharWidth as the cell width.
453      */
454     GetCharWidth32W(hDC, tm.tmFirstChar, tm.tmFirstChar, &w);
455     for (i = tm.tmFirstChar + 1; i <= tm.tmLastChar; i += sizeof(buf) / sizeof(buf[0]))
456     {
457         int j, k;
458
459         k = min(tm.tmLastChar - i, sizeof(buf) / sizeof(buf[0]) - 1);
460         GetCharWidth32W(hDC, i, i + k, buf);
461         for (j = 0; j <= k; j++)
462         {
463             if (buf[j] != w)
464             {
465                 WINE_WARN("Non uniform cell width: [%d]=%d [%d]=%d\n"
466                           "This may be caused by old freetype libraries, >= 2.0.8 is recommended\n",
467                           i + j, buf[j], tm.tmFirstChar, w);
468                 goto err;
469             }
470         }
471     }
472     SelectObject(hDC, hOldFont);
473     ReleaseDC(hWnd, hDC);
474
475     config->cell_width  = w;
476     config->cell_height = tm.tmHeight + tm.tmExternalLeading;
477     config->font_weight = tm.tmWeight;
478     lstrcpyW(config->face_name, lf->lfFaceName);
479     if (el) *el = tm.tmExternalLeading;
480
481     return hFont;
482  err:
483     if (hDC && hOldFont) SelectObject(hDC, hOldFont);
484     if (hFont) DeleteObject(hFont);
485  err1:
486     if (hDC) ReleaseDC(hWnd, hDC);
487
488     return NULL;
489 }
490
491 /******************************************************************
492  *              WCUSER_FillLogFont
493  *
494  *
495  */
496 void WCUSER_FillLogFont(LOGFONTW* lf, const WCHAR* name, UINT height, UINT weight)
497 {
498     lf->lfHeight        = height;
499     lf->lfWidth         = 0;
500     lf->lfEscapement    = 0;
501     lf->lfOrientation   = 0;
502     lf->lfWeight        = weight;
503     lf->lfItalic        = FALSE;
504     lf->lfUnderline     = FALSE;
505     lf->lfStrikeOut     = FALSE;
506     lf->lfCharSet       = DEFAULT_CHARSET;
507     lf->lfOutPrecision  = OUT_DEFAULT_PRECIS;
508     lf->lfClipPrecision = CLIP_DEFAULT_PRECIS;
509     lf->lfQuality       = DEFAULT_QUALITY;
510     lf->lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE;
511     lstrcpyW(lf->lfFaceName, name);
512 }
513
514 /******************************************************************
515  *              WCUSER_SetFont
516  *
517  * sets logfont as the new font for the console
518  */
519 BOOL WCUSER_SetFont(struct inner_data* data, const LOGFONTW* logfont)
520 {
521     HFONT       hFont;
522     LONG        el;
523
524     if (PRIVATE(data)->hFont != 0 && WCUSER_AreFontsEqual(&data->curcfg, logfont))
525         return TRUE;
526
527     hFont = WCUSER_CopyFont(&data->curcfg, data->hWnd, logfont, &el);
528     if (!hFont) {WINE_ERR("wrong font\n"); return FALSE;}
529
530     if (PRIVATE(data)->hFont) DeleteObject(PRIVATE(data)->hFont);
531     PRIVATE(data)->hFont = hFont;
532     PRIVATE(data)->ext_leading = el;
533
534     WCUSER_ComputePositions(data);
535     WCUSER_NewBitmap(data);
536     InvalidateRect(data->hWnd, NULL, FALSE);
537     UpdateWindow(data->hWnd);
538
539     return TRUE;
540 }
541
542 /******************************************************************
543  *              WCUSER_SetFontPmt
544  *
545  * Sets a new font for the console.
546  * In fact a wrapper for WCUSER_SetFont
547  */
548 static void     WCUSER_SetFontPmt(struct inner_data* data, const WCHAR* font,
549                                   unsigned height, unsigned weight)
550 {
551     LOGFONTW            lf;
552     struct font_chooser fc;
553
554     WINE_TRACE_(wc_font)("=> %s h=%u w=%u\n",
555                          wine_dbgstr_wn(font, -1), height, weight);
556
557     if (font[0] != '\0' && height != 0 && weight != 0)
558     {
559         WCUSER_FillLogFont(&lf, font, height, weight);
560         if (WCUSER_SetFont(data, &lf))
561         {
562             WCUSER_DumpLogFont("InitReuses: ", &lf, 0);
563             return;
564         }
565     }
566
567     /* try to find an acceptable font */
568     WINE_WARN("Couldn't match the font from registry... trying to find one\n");
569     fc.data = data;
570     fc.done = 0;
571     EnumFontFamiliesW(PRIVATE(data)->hMemDC, NULL, get_first_font_enum, (LPARAM)&fc);
572     if (!fc.done) WINECON_Fatal("Couldn't find a decent font, aborting\n");
573 }
574
575 /******************************************************************
576  *              WCUSER_GetCell
577  *
578  * Get a cell from a relative coordinate in window (takes into
579  * account the scrolling)
580  */
581 static COORD    WCUSER_GetCell(const struct inner_data* data, LPARAM lParam)
582 {
583     COORD       c;
584
585     c.X = data->curcfg.win_pos.X + (short)LOWORD(lParam) / data->curcfg.cell_width;
586     c.Y = data->curcfg.win_pos.Y + (short)HIWORD(lParam) / data->curcfg.cell_height;
587
588     return c;
589 }
590
591 /******************************************************************
592  *              WCUSER_GetSelectionRect
593  *
594  * Get the selection rectangle
595  */
596 static void     WCUSER_GetSelectionRect(const struct inner_data* data, LPRECT r)
597 {
598     r->left   = (min(PRIVATE(data)->selectPt1.X, PRIVATE(data)->selectPt2.X)     - data->curcfg.win_pos.X) * data->curcfg.cell_width;
599     r->top    = (min(PRIVATE(data)->selectPt1.Y, PRIVATE(data)->selectPt2.Y)     - data->curcfg.win_pos.Y) * data->curcfg.cell_height;
600     r->right  = (max(PRIVATE(data)->selectPt1.X, PRIVATE(data)->selectPt2.X) + 1 - data->curcfg.win_pos.X) * data->curcfg.cell_width;
601     r->bottom = (max(PRIVATE(data)->selectPt1.Y, PRIVATE(data)->selectPt2.Y) + 1 - data->curcfg.win_pos.Y) * data->curcfg.cell_height;
602 }
603
604 /******************************************************************
605  *              WCUSER_SetSelection
606  *
607  *
608  */
609 static void     WCUSER_SetSelection(const struct inner_data* data, HDC hRefDC)
610 {
611     HDC         hDC;
612     RECT        r;
613
614     WCUSER_GetSelectionRect(data, &r);
615     hDC = hRefDC ? hRefDC : GetDC(data->hWnd);
616     if (hDC)
617     {
618         if (data->hWnd == GetFocus() && data->curcfg.cursor_visible)
619             HideCaret(data->hWnd);
620         InvertRect(hDC, &r);
621         if (hDC != hRefDC)
622             ReleaseDC(data->hWnd, hDC);
623         if (data->hWnd == GetFocus() && data->curcfg.cursor_visible)
624             ShowCaret(data->hWnd);
625     }
626 }
627
628 /******************************************************************
629  *              WCUSER_MoveSelection
630  *
631  *
632  */
633 static void     WCUSER_MoveSelection(struct inner_data* data, COORD c1, COORD c2)
634 {
635     RECT        r;
636     HDC         hDC;
637
638     if (c1.X < 0 || c1.X >= data->curcfg.sb_width ||
639         c2.X < 0 || c2.X >= data->curcfg.sb_width ||
640         c1.Y < 0 || c1.Y >= data->curcfg.sb_height ||
641         c2.Y < 0 || c2.Y >= data->curcfg.sb_height)
642         return;
643
644     WCUSER_GetSelectionRect(data, &r);
645     hDC = GetDC(data->hWnd);
646     if (hDC)
647     {
648         if (data->hWnd == GetFocus() && data->curcfg.cursor_visible)
649             HideCaret(data->hWnd);
650         InvertRect(hDC, &r);
651     }
652     PRIVATE(data)->selectPt1 = c1;
653     PRIVATE(data)->selectPt2 = c2;
654     if (hDC)
655     {
656         WCUSER_GetSelectionRect(data, &r);
657         InvertRect(hDC, &r);
658         ReleaseDC(data->hWnd, hDC);
659         if (data->hWnd == GetFocus() && data->curcfg.cursor_visible)
660             ShowCaret(data->hWnd);
661     }
662 }
663
664 /******************************************************************
665  *              WCUSER_CopySelectionToClipboard
666  *
667  * Copies the current selection into the clipboard
668  */
669 static void     WCUSER_CopySelectionToClipboard(const struct inner_data* data)
670 {
671     HANDLE      hMem;
672     LPWSTR      p;
673     unsigned    w, h;
674
675     w = abs(PRIVATE(data)->selectPt1.X - PRIVATE(data)->selectPt2.X) + 2;
676     h = abs(PRIVATE(data)->selectPt1.Y - PRIVATE(data)->selectPt2.Y) + 1;
677
678     if (!OpenClipboard(data->hWnd)) return;
679     EmptyClipboard();
680
681     hMem = GlobalAlloc(GMEM_MOVEABLE, (w * h) * sizeof(WCHAR));
682     if (hMem && (p = GlobalLock(hMem)))
683     {
684         COORD   c;
685         int     y;
686
687         c.X = min(PRIVATE(data)->selectPt1.X, PRIVATE(data)->selectPt2.X);
688         c.Y = min(PRIVATE(data)->selectPt1.Y, PRIVATE(data)->selectPt2.Y);
689
690         for (y = 0; y < h; y++, c.Y++)
691         {
692             LPWSTR end;
693             DWORD count;
694
695             ReadConsoleOutputCharacterW(data->hConOut, p, w - 1, c, &count);
696
697             /* strip spaces from the end of the line */
698             end = p + w - 1;
699             while (end > p && *(end - 1) == ' ')
700                 end--;
701             *end = (y < h - 1) ? '\n' : '\0';
702             p = end + 1;
703         }
704         GlobalUnlock(hMem);
705         SetClipboardData(CF_UNICODETEXT, hMem);
706     }
707     CloseClipboard();
708 }
709
710 /******************************************************************
711  *              WCUSER_PasteFromClipboard
712  *
713  *
714  */
715 static void     WCUSER_PasteFromClipboard(struct inner_data* data)
716 {
717     HANDLE      h;
718     WCHAR*      ptr;
719
720     if (!OpenClipboard(data->hWnd)) return;
721     h = GetClipboardData(CF_UNICODETEXT);
722     if (h && (ptr = GlobalLock(h)))
723     {
724         int             i, len = GlobalSize(h) / sizeof(WCHAR);
725         INPUT_RECORD    ir[2];
726         DWORD           n;
727         SHORT           sh;
728
729         ir[0].EventType = KEY_EVENT;
730         ir[0].Event.KeyEvent.wRepeatCount = 0;
731         ir[0].Event.KeyEvent.dwControlKeyState = 0;
732         ir[0].Event.KeyEvent.bKeyDown = TRUE;
733
734         /* generate the corresponding input records */
735         for (i = 0; i < len; i++)
736         {
737             /* FIXME: the modifying keys are not generated (shift, ctrl...) */
738             sh = VkKeyScanW(ptr[i]);
739             ir[0].Event.KeyEvent.wVirtualKeyCode = LOBYTE(sh);
740             ir[0].Event.KeyEvent.wVirtualScanCode = MapVirtualKeyW(LOBYTE(sh), 0);
741             ir[0].Event.KeyEvent.uChar.UnicodeChar = ptr[i];
742
743             ir[1] = ir[0];
744             ir[1].Event.KeyEvent.bKeyDown = FALSE;
745
746             WriteConsoleInputW(data->hConIn, ir, 2, &n);
747         }
748         GlobalUnlock(h);
749     }
750     CloseClipboard();
751 }
752
753 /******************************************************************
754  *              WCUSER_Refresh
755  *
756  *
757  */
758 static void WCUSER_Refresh(const struct inner_data* data, int tp, int bm)
759 {
760     WCUSER_FillMemDC(data, tp, bm);
761     if (data->curcfg.win_pos.Y <= bm && data->curcfg.win_pos.Y + data->curcfg.win_height >= tp)
762     {
763         RECT    r;
764
765         r.left   = 0;
766         r.right  = data->curcfg.win_width * data->curcfg.cell_width;
767         r.top    = (tp - data->curcfg.win_pos.Y) * data->curcfg.cell_height;
768         r.bottom = (bm - data->curcfg.win_pos.Y + 1) * data->curcfg.cell_height;
769         InvalidateRect(data->hWnd, &r, FALSE);
770         UpdateWindow(data->hWnd);
771     }
772 }
773
774 /******************************************************************
775  *              WCUSER_Paint
776  *
777  *
778  */
779 static void     WCUSER_Paint(const struct inner_data* data)
780 {
781     PAINTSTRUCT         ps;
782
783     if (data->in_set_config) return; /* in order to avoid some flicker */
784     BeginPaint(data->hWnd, &ps);
785     BitBlt(ps.hdc, 0, 0,
786            data->curcfg.win_width * data->curcfg.cell_width,
787            data->curcfg.win_height * data->curcfg.cell_height,
788            PRIVATE(data)->hMemDC,
789            data->curcfg.win_pos.X * data->curcfg.cell_width,
790            data->curcfg.win_pos.Y * data->curcfg.cell_height,
791            SRCCOPY);
792     if (PRIVATE(data)->has_selection)
793         WCUSER_SetSelection(data, ps.hdc);
794     EndPaint(data->hWnd, &ps);
795 }
796
797 /******************************************************************
798  *              WCUSER_Scroll
799  *
800  *
801  */
802 static void WCUSER_Scroll(struct inner_data* data, int pos, BOOL horz)
803 {
804     if (horz)
805     {
806         ScrollWindow(data->hWnd, (data->curcfg.win_pos.X - pos) * data->curcfg.cell_width, 0, NULL, NULL);
807         SetScrollPos(data->hWnd, SB_HORZ, pos, TRUE);
808         data->curcfg.win_pos.X = pos;
809     }
810     else
811     {
812         ScrollWindow(data->hWnd, 0, (data->curcfg.win_pos.Y - pos) * data->curcfg.cell_height, NULL, NULL);
813         SetScrollPos(data->hWnd, SB_VERT, pos, TRUE);
814         data->curcfg.win_pos.Y = pos;
815     }
816     InvalidateRect(data->hWnd, NULL, FALSE);
817 }
818
819 /******************************************************************
820  *              WCUSER_FillMenu
821  *
822  *
823  */
824 static BOOL WCUSER_FillMenu(HMENU hMenu, BOOL sep)
825 {
826     HMENU     hSubMenu;
827     HINSTANCE hInstance = GetModuleHandleW(NULL);
828     WCHAR     buff[256];
829
830     if (!hMenu) return FALSE;
831
832     /* FIXME: error handling & memory cleanup */
833     hSubMenu = CreateMenu();
834     if (!hSubMenu) return FALSE;
835
836     LoadStringW(hInstance, IDS_MARK, buff, sizeof(buff) / sizeof(buff[0]));
837     InsertMenuW(hSubMenu, -1, MF_BYPOSITION|MF_STRING, IDS_MARK, buff);
838     LoadStringW(hInstance, IDS_COPY, buff, sizeof(buff) / sizeof(buff[0]));
839     InsertMenuW(hSubMenu, -1, MF_BYPOSITION|MF_STRING, IDS_COPY, buff);
840     LoadStringW(hInstance, IDS_PASTE, buff, sizeof(buff) / sizeof(buff[0]));
841     InsertMenuW(hSubMenu, -1, MF_BYPOSITION|MF_STRING, IDS_PASTE, buff);
842     LoadStringW(hInstance, IDS_SELECTALL, buff, sizeof(buff) / sizeof(buff[0]));
843     InsertMenuW(hSubMenu, -1, MF_BYPOSITION|MF_STRING, IDS_SELECTALL, buff);
844     LoadStringW(hInstance, IDS_SCROLL, buff, sizeof(buff) / sizeof(buff[0]));
845     InsertMenuW(hSubMenu, -1, MF_BYPOSITION|MF_STRING, IDS_SCROLL, buff);
846     LoadStringW(hInstance, IDS_SEARCH, buff, sizeof(buff) / sizeof(buff[0]));
847     InsertMenuW(hSubMenu, -1, MF_BYPOSITION|MF_STRING, IDS_SEARCH, buff);
848
849     if (sep) InsertMenuW(hMenu, -1, MF_BYPOSITION|MF_SEPARATOR, 0, NULL);
850     LoadStringW(hInstance, IDS_EDIT, buff, sizeof(buff) / sizeof(buff[0]));
851     InsertMenuW(hMenu, -1, MF_BYPOSITION|MF_STRING|MF_POPUP, (UINT_PTR)hSubMenu, buff);
852     LoadStringW(hInstance, IDS_DEFAULT, buff, sizeof(buff) / sizeof(buff[0]));
853     InsertMenuW(hMenu, -1, MF_BYPOSITION|MF_STRING, IDS_DEFAULT, buff);
854     LoadStringW(hInstance, IDS_PROPERTIES, buff, sizeof(buff) / sizeof(buff[0]));
855     InsertMenuW(hMenu, -1, MF_BYPOSITION|MF_STRING, IDS_PROPERTIES, buff);
856
857     return TRUE;
858 }
859
860 /******************************************************************
861  *              WCUSER_SetMenuDetails
862  *
863  * Grays / ungrays the menu items according to their state
864  */
865 static void     WCUSER_SetMenuDetails(const struct inner_data* data, HMENU hMenu)
866 {
867     if (!hMenu) {WINE_ERR("Issue in getting menu bits\n");return;}
868
869     EnableMenuItem(hMenu, IDS_COPY,
870                    MF_BYCOMMAND|(PRIVATE(data)->has_selection ? MF_ENABLED : MF_GRAYED));
871     EnableMenuItem(hMenu, IDS_PASTE,
872                    MF_BYCOMMAND|(IsClipboardFormatAvailable(CF_UNICODETEXT)
873                                  ? MF_ENABLED : MF_GRAYED));
874     EnableMenuItem(hMenu, IDS_SCROLL, MF_BYCOMMAND|MF_GRAYED);
875     EnableMenuItem(hMenu, IDS_SEARCH, MF_BYCOMMAND|MF_GRAYED);
876 }
877
878 /******************************************************************
879  *              WCUSER_Create
880  *
881  * Creates the window for the rendering
882  */
883 static LRESULT WCUSER_Create(HWND hWnd, LPCREATESTRUCTW lpcs)
884 {
885     struct inner_data*  data;
886     HMENU               hSysMenu;
887
888     data = lpcs->lpCreateParams;
889     SetWindowLongPtrW(hWnd, 0, (DWORD_PTR)data);
890     data->hWnd = hWnd;
891
892     hSysMenu = GetSystemMenu(hWnd, FALSE);
893     if (!hSysMenu) return 0;
894     PRIVATE(data)->hPopMenu = CreatePopupMenu();
895     if (!PRIVATE(data)->hPopMenu) return 0;
896
897     WCUSER_FillMenu(hSysMenu, TRUE);
898     WCUSER_FillMenu(PRIVATE(data)->hPopMenu, FALSE);
899
900     PRIVATE(data)->hMemDC = CreateCompatibleDC(0);
901     if (!PRIVATE(data)->hMemDC) {WINE_ERR("no mem dc\n");return 0;}
902
903     data->curcfg.quick_edit = FALSE;
904     return 0;
905 }
906
907 /******************************************************************
908  *              WCUSER_GetCtrlKeyState
909  *
910  * Get the console bit mask equivalent to the VK_ status in keyState
911  */
912 static DWORD    WCUSER_GetCtrlKeyState(BYTE* keyState)
913 {
914     DWORD               ret = 0;
915
916     GetKeyboardState(keyState);
917     if (keyState[VK_SHIFT]    & 0x80)   ret |= SHIFT_PRESSED;
918     if (keyState[VK_LCONTROL] & 0x80)   ret |= LEFT_CTRL_PRESSED;
919     if (keyState[VK_RCONTROL] & 0x80)   ret |= RIGHT_CTRL_PRESSED;
920     if (keyState[VK_LMENU]    & 0x80)   ret |= LEFT_ALT_PRESSED;
921     if (keyState[VK_RMENU]    & 0x80)   ret |= RIGHT_ALT_PRESSED;
922     if (keyState[VK_CAPITAL]  & 0x01)   ret |= CAPSLOCK_ON;
923     if (keyState[VK_NUMLOCK]  & 0x01)   ret |= NUMLOCK_ON;
924     if (keyState[VK_SCROLL]   & 0x01)   ret |= SCROLLLOCK_ON;
925
926     return ret;
927 }
928
929 /******************************************************************
930  *              WCUSER_HandleSelectionKey
931  *
932  * Handles keys while selecting an area
933  */
934 static void WCUSER_HandleSelectionKey(struct inner_data* data, BOOL down,
935                                       WPARAM wParam, LPARAM lParam)
936 {
937     BYTE        keyState[256];
938     DWORD       state = WCUSER_GetCtrlKeyState(keyState) & ~(CAPSLOCK_ON|NUMLOCK_ON|SCROLLLOCK_ON);
939     COORD       c1, c2;
940
941     if (!down) return;
942
943     switch (state)
944     {
945     case 0:
946         switch (wParam)
947         {
948         case VK_RETURN:
949             PRIVATE(data)->has_selection = FALSE;
950             WCUSER_SetSelection(data, 0);
951             WCUSER_CopySelectionToClipboard(data);
952             return;
953         case VK_RIGHT:
954             c1 = PRIVATE(data)->selectPt1;
955             c2 = PRIVATE(data)->selectPt2;
956             c1.X++; c2.X++;
957             WCUSER_MoveSelection(data, c1, c2);
958             return;
959         case VK_LEFT:
960             c1 = PRIVATE(data)->selectPt1;
961             c2 = PRIVATE(data)->selectPt2;
962             c1.X--; c2.X--;
963             WCUSER_MoveSelection(data, c1, c2);
964             return;
965         case VK_UP:
966             c1 = PRIVATE(data)->selectPt1;
967             c2 = PRIVATE(data)->selectPt2;
968             c1.Y--; c2.Y--;
969             WCUSER_MoveSelection(data, c1, c2);
970             return;
971         case VK_DOWN:
972             c1 = PRIVATE(data)->selectPt1;
973             c2 = PRIVATE(data)->selectPt2;
974             c1.Y++; c2.Y++;
975             WCUSER_MoveSelection(data, c1, c2);
976             return;
977         }
978         break;
979     case SHIFT_PRESSED:
980         switch (wParam)
981         {
982         case VK_RIGHT:
983             c1 = PRIVATE(data)->selectPt1;
984             c2 = PRIVATE(data)->selectPt2;
985             c2.X++;
986             WCUSER_MoveSelection(data, c1, c2);
987             return;
988         case VK_LEFT:
989             c1 = PRIVATE(data)->selectPt1;
990             c2 = PRIVATE(data)->selectPt2;
991             c2.X--;
992             WCUSER_MoveSelection(data, c1, c2);
993             return;
994         case VK_UP:
995             c1 = PRIVATE(data)->selectPt1;
996             c2 = PRIVATE(data)->selectPt2;
997             c2.Y--;
998             WCUSER_MoveSelection(data, c1, c2);
999             return;
1000         case VK_DOWN:
1001             c1 = PRIVATE(data)->selectPt1;
1002             c2 = PRIVATE(data)->selectPt2;
1003             c2.Y++;
1004             WCUSER_MoveSelection(data, c1, c2);
1005             return;
1006         }
1007         break;
1008     }
1009
1010     if (wParam < VK_SPACE)  /* Shift, Alt, Ctrl, Num Lock etc. */
1011         return;
1012     
1013     WCUSER_SetSelection(data, 0);    
1014     PRIVATE(data)->has_selection = FALSE;
1015 }
1016
1017 /******************************************************************
1018  *              WCUSER_GenerateKeyInputRecord
1019  *
1020  * generates input_record from windows WM_KEYUP/WM_KEYDOWN messages
1021  */
1022 static void    WCUSER_GenerateKeyInputRecord(struct inner_data* data, BOOL down,
1023                                              WPARAM wParam, LPARAM lParam)
1024 {
1025     INPUT_RECORD        ir;
1026     DWORD               n;
1027     WCHAR               buf[2];
1028     static      WCHAR   last; /* keep last char seen as feed for key up message */
1029     BYTE                keyState[256];
1030
1031     ir.EventType = KEY_EVENT;
1032     ir.Event.KeyEvent.bKeyDown = down;
1033     ir.Event.KeyEvent.wRepeatCount = LOWORD(lParam);
1034     ir.Event.KeyEvent.wVirtualKeyCode = wParam;
1035
1036     ir.Event.KeyEvent.wVirtualScanCode = HIWORD(lParam) & 0xFF;
1037
1038     ir.Event.KeyEvent.uChar.UnicodeChar = 0;
1039     ir.Event.KeyEvent.dwControlKeyState = WCUSER_GetCtrlKeyState(keyState);
1040     if (lParam & (1L << 24))            ir.Event.KeyEvent.dwControlKeyState |= ENHANCED_KEY;
1041
1042     if (down)
1043     {
1044         switch (ToUnicode(wParam, HIWORD(lParam), keyState, buf, 2, 0))
1045         {
1046         case 2:
1047             /* FIXME... should generate two events... */
1048             /* fall through */
1049         case 1:
1050             last = buf[0];
1051             break;
1052         default:
1053             last = 0;
1054             break;
1055         }
1056     }
1057     ir.Event.KeyEvent.uChar.UnicodeChar = last; /* FIXME: HACKY... and buggy because it should be a stack, not a single value */
1058     if (!down) last = 0;
1059
1060     WriteConsoleInputW(data->hConIn, &ir, 1, &n);
1061 }
1062
1063 /******************************************************************
1064  *              WCUSER_GenerateMouseInputRecord
1065  *
1066  *
1067  */
1068 static void    WCUSER_GenerateMouseInputRecord(struct inner_data* data, COORD c,
1069                                                WPARAM wParam, DWORD event)
1070 {
1071     INPUT_RECORD        ir;
1072     BYTE                keyState[256];
1073     DWORD               mode, n;
1074
1075     /* MOUSE_EVENTs shouldn't be sent unless ENABLE_MOUSE_INPUT is active */
1076     if (!GetConsoleMode(data->hConIn, &mode) || !(mode & ENABLE_MOUSE_INPUT))
1077         return;
1078
1079     ir.EventType = MOUSE_EVENT;
1080     ir.Event.MouseEvent.dwMousePosition = c;
1081     ir.Event.MouseEvent.dwButtonState = 0;
1082     if (wParam & MK_LBUTTON) ir.Event.MouseEvent.dwButtonState |= FROM_LEFT_1ST_BUTTON_PRESSED;
1083     if (wParam & MK_MBUTTON) ir.Event.MouseEvent.dwButtonState |= FROM_LEFT_2ND_BUTTON_PRESSED;
1084     if (wParam & MK_RBUTTON) ir.Event.MouseEvent.dwButtonState |= RIGHTMOST_BUTTON_PRESSED;
1085     if (wParam & MK_CONTROL) ir.Event.MouseEvent.dwButtonState |= LEFT_CTRL_PRESSED;
1086     if (wParam & MK_SHIFT)   ir.Event.MouseEvent.dwButtonState |= SHIFT_PRESSED;
1087     if (event == MOUSE_WHEELED) ir.Event.MouseEvent.dwButtonState |= wParam & 0xFFFF0000;
1088     ir.Event.MouseEvent.dwControlKeyState = WCUSER_GetCtrlKeyState(keyState);
1089     ir.Event.MouseEvent.dwEventFlags = event;
1090
1091     WriteConsoleInputW(data->hConIn, &ir, 1, &n);
1092 }
1093
1094 /******************************************************************
1095  *              WCUSER_Proc
1096  *
1097  *
1098  */
1099 static LRESULT CALLBACK WCUSER_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1100 {
1101     struct inner_data* data = (struct inner_data*)GetWindowLongPtrW(hWnd, 0);
1102
1103     switch (uMsg)
1104     {
1105     case WM_CREATE:
1106         return WCUSER_Create(hWnd, (LPCREATESTRUCTW)lParam);
1107     case WM_DESTROY:
1108         data->hWnd = 0;
1109         PostQuitMessage(0);
1110         break;
1111     case WM_PAINT:
1112         WCUSER_Paint(data);
1113         break;
1114     case WM_KEYDOWN:
1115     case WM_KEYUP:
1116         if (PRIVATE(data)->has_selection)
1117             WCUSER_HandleSelectionKey(data, uMsg == WM_KEYDOWN, wParam, lParam);
1118         else
1119             WCUSER_GenerateKeyInputRecord(data, uMsg == WM_KEYDOWN, wParam, lParam);
1120         break;
1121     case WM_SYSKEYDOWN:
1122     case WM_SYSKEYUP:
1123         WCUSER_GenerateKeyInputRecord(data, uMsg == WM_SYSKEYDOWN, wParam, lParam);
1124         break;
1125     case WM_LBUTTONDOWN:
1126         if (data->curcfg.quick_edit || PRIVATE(data)->has_selection)
1127         {
1128             if (PRIVATE(data)->has_selection)
1129                 WCUSER_SetSelection(data, 0);
1130             
1131             if (data->curcfg.quick_edit && PRIVATE(data)->has_selection)
1132             {
1133                 PRIVATE(data)->has_selection = FALSE;
1134             }
1135             else
1136             {
1137                 PRIVATE(data)->selectPt1 = PRIVATE(data)->selectPt2 = WCUSER_GetCell(data, lParam);
1138                 SetCapture(data->hWnd);
1139                 WCUSER_SetSelection(data, 0);
1140                 PRIVATE(data)->has_selection = TRUE;
1141             }
1142         }
1143         else
1144         {
1145             WCUSER_GenerateMouseInputRecord(data, WCUSER_GetCell(data, lParam), wParam, 0);
1146         }
1147         break;
1148     case WM_MOUSEMOVE:
1149         if (data->curcfg.quick_edit || PRIVATE(data)->has_selection)
1150         {
1151             if (GetCapture() == data->hWnd && PRIVATE(data)->has_selection &&
1152                 (wParam & MK_LBUTTON))
1153             {
1154                 WCUSER_MoveSelection(data, PRIVATE(data)->selectPt1, WCUSER_GetCell(data, lParam));
1155             }
1156         }
1157         else
1158         {
1159             WCUSER_GenerateMouseInputRecord(data, WCUSER_GetCell(data, lParam), wParam, MOUSE_MOVED);
1160         }
1161         break;
1162     case WM_LBUTTONUP:
1163         if (data->curcfg.quick_edit || PRIVATE(data)->has_selection)
1164         {
1165             if (GetCapture() == data->hWnd && PRIVATE(data)->has_selection)
1166             {
1167                 WCUSER_MoveSelection(data, PRIVATE(data)->selectPt1, WCUSER_GetCell(data, lParam));
1168                 ReleaseCapture();
1169             }
1170         }
1171         else
1172         {
1173             WCUSER_GenerateMouseInputRecord(data, WCUSER_GetCell(data, lParam), wParam, 0);
1174         }
1175         break;
1176     case WM_RBUTTONDOWN:
1177         if ((wParam & (MK_CONTROL|MK_SHIFT)) == data->curcfg.menu_mask)
1178         {
1179             POINT       pt;
1180
1181             pt.x = (short)LOWORD(lParam);
1182             pt.y = (short)HIWORD(lParam);
1183             ClientToScreen(hWnd, &pt);
1184             WCUSER_SetMenuDetails(data, PRIVATE(data)->hPopMenu);
1185             TrackPopupMenu(PRIVATE(data)->hPopMenu, TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RIGHTBUTTON,
1186                            pt.x, pt.y, 0, hWnd, NULL);
1187         }
1188         else
1189         {
1190             WCUSER_GenerateMouseInputRecord(data, WCUSER_GetCell(data, lParam), wParam, 0);
1191         }
1192         break;
1193     case WM_RBUTTONUP:
1194         /* no need to track for rbutton up when opening the popup... the event will be
1195          * swallowed by TrackPopupMenu */
1196     case WM_MBUTTONDOWN:
1197     case WM_MBUTTONUP:
1198         WCUSER_GenerateMouseInputRecord(data, WCUSER_GetCell(data, lParam), wParam, 0);
1199         break;
1200     case WM_LBUTTONDBLCLK:
1201     case WM_MBUTTONDBLCLK:
1202     case WM_RBUTTONDBLCLK:
1203         WCUSER_GenerateMouseInputRecord(data, WCUSER_GetCell(data, lParam), wParam, DOUBLE_CLICK);
1204         break;
1205     case WM_SETFOCUS:
1206         if (data->curcfg.cursor_visible)
1207         {
1208             CreateCaret(data->hWnd, PRIVATE(data)->cursor_bitmap,
1209                         data->curcfg.cell_width, data->curcfg.cell_height);
1210             WCUSER_PosCursor(data);
1211         }
1212         break;
1213     case WM_KILLFOCUS:
1214         if (data->curcfg.cursor_visible)
1215             DestroyCaret();
1216         break;
1217     case WM_HSCROLL:
1218         {
1219             struct config_data  cfg = data->curcfg;
1220
1221             switch (LOWORD(wParam))
1222             {
1223             case SB_PAGEUP:     cfg.win_pos.X -= 8;             break;
1224             case SB_PAGEDOWN:   cfg.win_pos.X += 8;             break;
1225             case SB_LINEUP:     cfg.win_pos.X--;                break;
1226             case SB_LINEDOWN:   cfg.win_pos.X++;                break;
1227             case SB_THUMBTRACK: cfg.win_pos.X = HIWORD(wParam); break;
1228             default:                                            break;
1229             }
1230             if (cfg.win_pos.X < 0) cfg.win_pos.X = 0;
1231             if (cfg.win_pos.X > data->curcfg.sb_width - data->curcfg.win_width)
1232                 cfg.win_pos.X = data->curcfg.sb_width - data->curcfg.win_width;
1233             if (cfg.win_pos.X != data->curcfg.win_pos.X)
1234             {
1235                 WINECON_SetConfig(data, &cfg);
1236             }
1237         }
1238         break;
1239     case WM_MOUSEWHEEL:
1240         if (data->curcfg.sb_height <= data->curcfg.win_height)
1241         {
1242             WCUSER_GenerateMouseInputRecord(data,  WCUSER_GetCell(data, lParam), wParam, MOUSE_WHEELED);
1243             break;
1244         }
1245         /* else fallthrough */
1246     case WM_VSCROLL:
1247         {
1248             struct config_data  cfg = data->curcfg;
1249
1250             if (uMsg == WM_MOUSEWHEEL)
1251             {
1252                 UINT scrollLines = 3;
1253                 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES, 0, &scrollLines, 0);
1254                 scrollLines *= -GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA;
1255                 cfg.win_pos.Y += scrollLines;
1256             } else {
1257                 switch (LOWORD(wParam))
1258                 {
1259                 case SB_PAGEUP:     cfg.win_pos.Y -= 8;                 break;
1260                 case SB_PAGEDOWN:   cfg.win_pos.Y += 8;                 break;
1261                 case SB_LINEUP:     cfg.win_pos.Y--;                    break;
1262                 case SB_LINEDOWN:   cfg.win_pos.Y++;                    break;
1263                 case SB_THUMBTRACK: cfg.win_pos.Y = HIWORD(wParam);     break;
1264                 default:                                                break;
1265                 }
1266             }
1267
1268             if (cfg.win_pos.Y < 0) cfg.win_pos.Y = 0;
1269             if (cfg.win_pos.Y > data->curcfg.sb_height - data->curcfg.win_height)
1270                 cfg.win_pos.Y = data->curcfg.sb_height - data->curcfg.win_height;
1271             if (cfg.win_pos.Y != data->curcfg.win_pos.Y)
1272             {
1273                 WINECON_SetConfig(data, &cfg);
1274             }
1275         }
1276         break;
1277     case WM_SYSCOMMAND:
1278         switch (wParam)
1279         {
1280         case IDS_DEFAULT:
1281             WCUSER_GetProperties(data, FALSE);
1282             break;
1283         case IDS_PROPERTIES:
1284             WCUSER_GetProperties(data, TRUE);
1285             break;
1286         default:
1287             return DefWindowProcW(hWnd, uMsg, wParam, lParam);
1288         }
1289         break;
1290     case WM_COMMAND:
1291         switch (wParam)
1292         {
1293         case IDS_DEFAULT:
1294             WCUSER_GetProperties(data, FALSE);
1295             break;
1296         case IDS_PROPERTIES:
1297             WCUSER_GetProperties(data, TRUE);
1298             break;
1299         case IDS_MARK:
1300             PRIVATE(data)->selectPt1.X = PRIVATE(data)->selectPt1.Y = 0;
1301             PRIVATE(data)->selectPt2.X = PRIVATE(data)->selectPt2.Y = 0;
1302             WCUSER_SetSelection(data, 0);
1303             PRIVATE(data)->has_selection = TRUE;
1304             break;
1305         case IDS_COPY:
1306             if (PRIVATE(data)->has_selection)
1307             {
1308                 PRIVATE(data)->has_selection = FALSE;
1309                 WCUSER_SetSelection(data, 0);
1310                 WCUSER_CopySelectionToClipboard(data);
1311             }
1312             break;
1313         case IDS_PASTE:
1314             WCUSER_PasteFromClipboard(data);
1315             break;
1316         case IDS_SELECTALL:
1317             PRIVATE(data)->selectPt1.X = PRIVATE(data)->selectPt1.Y = 0;
1318             PRIVATE(data)->selectPt2.X = (data->curcfg.sb_width - 1) * data->curcfg.cell_width;
1319             PRIVATE(data)->selectPt2.Y = (data->curcfg.sb_height - 1) * data->curcfg.cell_height;
1320             WCUSER_SetSelection(data, 0);
1321             PRIVATE(data)->has_selection = TRUE;
1322             break;
1323         case IDS_SCROLL:
1324         case IDS_SEARCH:
1325             WINE_FIXME("Unhandled yet command: %lx\n", wParam);
1326             break;
1327         default:
1328             return DefWindowProcW(hWnd, uMsg, wParam, lParam);
1329         }
1330         break;
1331     case WM_INITMENUPOPUP:
1332         if (!HIWORD(lParam)) return DefWindowProcW(hWnd, uMsg, wParam, lParam);
1333         WCUSER_SetMenuDetails(data, GetSystemMenu(data->hWnd, FALSE));
1334         break;
1335     case WM_SIZE:
1336         WINECON_ResizeWithContainer(data, LOWORD(lParam) / data->curcfg.cell_width,
1337                                     HIWORD(lParam) / data->curcfg.cell_height);
1338         break;
1339     default:
1340         return DefWindowProcW(hWnd, uMsg, wParam, lParam);
1341     }
1342     return 0;
1343 }
1344
1345 /******************************************************************
1346  *              WCUSER_DeleteBackend
1347  *
1348  *
1349  */
1350 static void WCUSER_DeleteBackend(struct inner_data* data)
1351 {
1352     if (!PRIVATE(data)) return;
1353     if (PRIVATE(data)->hMemDC)          DeleteDC(PRIVATE(data)->hMemDC);
1354     if (data->hWnd)                     DestroyWindow(data->hWnd);
1355     if (PRIVATE(data)->hFont)           DeleteObject(PRIVATE(data)->hFont);
1356     if (PRIVATE(data)->cursor_bitmap)   DeleteObject(PRIVATE(data)->cursor_bitmap);
1357     if (PRIVATE(data)->hBitmap)         DeleteObject(PRIVATE(data)->hBitmap);
1358     HeapFree(GetProcessHeap(), 0, PRIVATE(data));
1359 }
1360
1361 /******************************************************************
1362  *              WCUSER_MainLoop
1363  *
1364  *
1365  */
1366 static int WCUSER_MainLoop(struct inner_data* data)
1367 {
1368     MSG         msg;
1369
1370     ShowWindow(data->hWnd, data->nCmdShow);
1371     while (!data->dying || !data->curcfg.exit_on_die)
1372     {
1373         switch (MsgWaitForMultipleObjects(1, &data->hSynchro, FALSE, INFINITE, QS_ALLINPUT))
1374         {
1375         case WAIT_OBJECT_0:
1376             WINECON_GrabChanges(data);
1377             break;
1378         case WAIT_OBJECT_0+1:
1379             /* need to use PeekMessageW loop instead of simple GetMessage:
1380              * multiple messages might have arrived in between,
1381              * so GetMessage would lead to delayed processing */
1382             while (PeekMessageW(&msg, 0, 0, 0, PM_REMOVE))
1383             {
1384                 if (msg.message == WM_QUIT) return 0;
1385                 WINE_TRACE("dispatching msg %04x\n", msg.message);
1386                 DispatchMessageW(&msg);
1387             }
1388             break;
1389         default:
1390             WINE_ERR("got pb\n");
1391             /* err */
1392             break;
1393         }
1394     }
1395     PostQuitMessage(0);
1396     return 0;
1397 }
1398
1399 /******************************************************************
1400  *              WCUSER_InitBackend
1401  *
1402  * Initialisation part II: creation of window.
1403  *
1404  */
1405 enum init_return WCUSER_InitBackend(struct inner_data* data)
1406 {
1407     static const WCHAR wClassName[] = {'W','i','n','e','C','o','n','s','o','l','e','C','l','a','s','s',0};
1408
1409     WNDCLASSW   wndclass;
1410     CHARSETINFO ci;
1411
1412     if (!TranslateCharsetInfo((DWORD *)(INT_PTR)GetACP(), &ci, TCI_SRCCODEPAGE))
1413         return init_failed;
1414     g_uiDefaultCharset = ci.ciCharset;
1415     WINE_TRACE_(wc_font)("Code page %d => Default charset: %d\n", GetACP(), g_uiDefaultCharset);
1416
1417     data->private = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct inner_data_user));
1418     if (!data->private) return init_failed;
1419
1420     data->fnMainLoop = WCUSER_MainLoop;
1421     data->fnPosCursor = WCUSER_PosCursor;
1422     data->fnShapeCursor = WCUSER_ShapeCursor;
1423     data->fnComputePositions = WCUSER_ComputePositions;
1424     data->fnRefresh = WCUSER_Refresh;
1425     data->fnResizeScreenBuffer = WCUSER_ResizeScreenBuffer;
1426     data->fnSetTitle = WCUSER_SetTitle;
1427     data->fnSetFont = WCUSER_SetFontPmt;
1428     data->fnScroll = WCUSER_Scroll;
1429     data->fnDeleteBackend = WCUSER_DeleteBackend;
1430
1431     wndclass.style         = CS_DBLCLKS;
1432     wndclass.lpfnWndProc   = WCUSER_Proc;
1433     wndclass.cbClsExtra    = 0;
1434     wndclass.cbWndExtra    = sizeof(DWORD_PTR);
1435     wndclass.hInstance     = GetModuleHandleW(NULL);
1436     wndclass.hIcon         = LoadIconW(0, (LPCWSTR)IDI_WINLOGO);
1437     wndclass.hCursor       = LoadCursorW(0, (LPCWSTR)IDC_ARROW);
1438     wndclass.hbrBackground = GetStockObject(BLACK_BRUSH);
1439     wndclass.lpszMenuName  = NULL;
1440     wndclass.lpszClassName = wClassName;
1441
1442     RegisterClassW(&wndclass);
1443
1444     data->hWnd = CreateWindowW(wndclass.lpszClassName, NULL,
1445                                WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_THICKFRAME|WS_MINIMIZEBOX|WS_HSCROLL|WS_VSCROLL,
1446                                CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, 0, 0, wndclass.hInstance, data);
1447     if (!data->hWnd) return init_not_supported;
1448
1449     return init_success;
1450 }