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