chiark / gitweb /
The Windows RNG turns out to only give about 16 bits at a time. This
[sgt-puzzles.git] / windows.c
1 /*
2  * windows.c: Windows front end for my puzzle collection.
3  */
4
5 #include <windows.h>
6 #include <commctrl.h>
7
8 #include <stdio.h>
9 #include <assert.h>
10 #include <stdarg.h>
11 #include <stdlib.h>
12 #include <time.h>
13
14 #include "puzzles.h"
15
16 #define IDM_NEW       0x0010
17 #define IDM_RESTART   0x0020
18 #define IDM_UNDO      0x0030
19 #define IDM_REDO      0x0040
20 #define IDM_QUIT      0x0050
21 #define IDM_CONFIG    0x0060
22 #define IDM_SEED      0x0070
23 #define IDM_PRESETS   0x0100
24
25 #ifdef DEBUG
26 static FILE *debug_fp = NULL;
27 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
28 static int debug_got_console = 0;
29
30 void dputs(char *buf)
31 {
32     DWORD dw;
33
34     if (!debug_got_console) {
35         if (AllocConsole()) {
36             debug_got_console = 1;
37             debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
38         }
39     }
40     if (!debug_fp) {
41         debug_fp = fopen("debug.log", "w");
42     }
43
44     if (debug_hdl != INVALID_HANDLE_VALUE) {
45         WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
46     }
47     fputs(buf, debug_fp);
48     fflush(debug_fp);
49 }
50
51 void debug_printf(char *fmt, ...)
52 {
53     char buf[4096];
54     va_list ap;
55
56     va_start(ap, fmt);
57     vsprintf(buf, fmt, ap);
58     dputs(buf);
59     va_end(ap);
60 }
61
62 #define debug(x) (debug_printf x)
63
64 #else
65
66 #define debug(x)
67
68 #endif
69
70 struct font {
71     HFONT font;
72     int type;
73     int size;
74 };
75
76 struct cfg_aux {
77     int ctlid;
78 };
79
80 struct frontend {
81     midend_data *me;
82     HWND hwnd, statusbar, cfgbox;
83     HINSTANCE inst;
84     HBITMAP bitmap, prevbm;
85     HDC hdc_bm;
86     COLORREF *colours;
87     HBRUSH *brushes;
88     HPEN *pens;
89     HRGN clip;
90     UINT timer;
91     int npresets;
92     game_params **presets;
93     struct font *fonts;
94     int nfonts, fontsize;
95     config_item *cfg;
96     struct cfg_aux *cfgaux;
97     int cfg_which, cfg_done;
98     HFONT cfgfont;
99 };
100
101 void fatal(char *fmt, ...)
102 {
103     char buf[2048];
104     va_list ap;
105
106     va_start(ap, fmt);
107     vsprintf(buf, fmt, ap);
108     va_end(ap);
109
110     MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
111
112     exit(1);
113 }
114
115 void status_bar(frontend *fe, char *text)
116 {
117     SetWindowText(fe->statusbar, text);
118 }
119
120 void frontend_default_colour(frontend *fe, float *output)
121 {
122     DWORD c = GetSysColor(COLOR_MENU); /* ick */
123
124     output[0] = (float)(GetRValue(c) / 255.0);
125     output[1] = (float)(GetGValue(c) / 255.0);
126     output[2] = (float)(GetBValue(c) / 255.0);
127 }
128
129 void clip(frontend *fe, int x, int y, int w, int h)
130 {
131     if (!fe->clip) {
132         fe->clip = CreateRectRgn(0, 0, 1, 1);
133         GetClipRgn(fe->hdc_bm, fe->clip);
134     }
135
136     IntersectClipRect(fe->hdc_bm, x, y, x+w, y+h);
137 }
138
139 void unclip(frontend *fe)
140 {
141     assert(fe->clip);
142     SelectClipRgn(fe->hdc_bm, fe->clip);
143 }
144
145 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
146                int align, int colour, char *text)
147 {
148     int i;
149
150     /*
151      * Find or create the font.
152      */
153     for (i = 0; i < fe->nfonts; i++)
154         if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
155             break;
156
157     if (i == fe->nfonts) {
158         if (fe->fontsize <= fe->nfonts) {
159             fe->fontsize = fe->nfonts + 10;
160             fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
161         }
162
163         fe->nfonts++;
164
165         fe->fonts[i].type = fonttype;
166         fe->fonts[i].size = fontsize;
167
168         /*
169          * FIXME: Really I should make at least _some_ effort to
170          * pick the correct font.
171          */
172         fe->fonts[i].font = CreateFont(-fontsize, 0, 0, 0, 0,
173                                        FALSE, FALSE, FALSE, DEFAULT_CHARSET,
174                                        OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
175                                        DEFAULT_QUALITY,
176                                        (fonttype == FONT_FIXED ?
177                                         FIXED_PITCH | FF_DONTCARE :
178                                         VARIABLE_PITCH | FF_SWISS),
179                                        NULL);
180     }
181
182     /*
183      * Position and draw the text.
184      */
185     {
186         HFONT oldfont;
187         TEXTMETRIC tm;
188         SIZE size;
189
190         oldfont = SelectObject(fe->hdc_bm, fe->fonts[i].font);
191         if (GetTextMetrics(fe->hdc_bm, &tm)) {
192             if (align & ALIGN_VCENTRE)
193                 y -= (tm.tmAscent+tm.tmDescent)/2;
194             else
195                 y -= tm.tmAscent;
196         }
197         if (GetTextExtentPoint32(fe->hdc_bm, text, strlen(text), &size)) {
198             if (align & ALIGN_HCENTRE)
199                 x -= size.cx / 2;
200             else if (align & ALIGN_HRIGHT)
201                 x -= size.cx;
202         }
203         SetBkMode(fe->hdc_bm, TRANSPARENT);
204         TextOut(fe->hdc_bm, x, y, text, strlen(text));
205         SelectObject(fe->hdc_bm, oldfont);
206     }
207 }
208
209 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour)
210 {
211     if (w == 1 && h == 1) {
212         /*
213          * Rectangle() appears to get uppity if asked to draw a 1x1
214          * rectangle, presumably on the grounds that that's beneath
215          * its dignity and you ought to be using SetPixel instead.
216          * So I will.
217          */
218         SetPixel(fe->hdc_bm, x, y, fe->colours[colour]);
219     } else {
220         HBRUSH oldbrush = SelectObject(fe->hdc_bm, fe->brushes[colour]);
221         HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[colour]);
222         Rectangle(fe->hdc_bm, x, y, x+w, y+h);
223         SelectObject(fe->hdc_bm, oldbrush);
224         SelectObject(fe->hdc_bm, oldpen);
225     }
226 }
227
228 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour)
229 {
230     HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[colour]);
231     MoveToEx(fe->hdc_bm, x1, y1, NULL);
232     LineTo(fe->hdc_bm, x2, y2);
233     SetPixel(fe->hdc_bm, x2, y2, fe->colours[colour]);
234     SelectObject(fe->hdc_bm, oldpen);
235 }
236
237 void draw_polygon(frontend *fe, int *coords, int npoints,
238                   int fill, int colour)
239 {
240     POINT *pts = snewn(npoints+1, POINT);
241     int i;
242
243     for (i = 0; i <= npoints; i++) {
244         int j = (i < npoints ? i : 0);
245         pts[i].x = coords[j*2];
246         pts[i].y = coords[j*2+1];
247     }
248
249     if (fill) {
250         HBRUSH oldbrush = SelectObject(fe->hdc_bm, fe->brushes[colour]);
251         HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[colour]);
252         Polygon(fe->hdc_bm, pts, npoints);
253         SelectObject(fe->hdc_bm, oldbrush);
254         SelectObject(fe->hdc_bm, oldpen);
255     } else {
256         HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[colour]);
257         Polyline(fe->hdc_bm, pts, npoints+1);
258         SelectObject(fe->hdc_bm, oldpen);
259     }
260
261     sfree(pts);
262 }
263
264 void start_draw(frontend *fe)
265 {
266     HDC hdc_win;
267     hdc_win = GetDC(fe->hwnd);
268     fe->hdc_bm = CreateCompatibleDC(hdc_win);
269     fe->prevbm = SelectObject(fe->hdc_bm, fe->bitmap);
270     ReleaseDC(fe->hwnd, hdc_win);
271     fe->clip = NULL;
272     SetMapMode(fe->hdc_bm, MM_TEXT);
273 }
274
275 void draw_update(frontend *fe, int x, int y, int w, int h)
276 {
277     RECT r;
278
279     r.left = x;
280     r.top = y;
281     r.right = x + w;
282     r.bottom = y + h;
283
284     InvalidateRect(fe->hwnd, &r, FALSE);
285 }
286
287 void end_draw(frontend *fe)
288 {
289     SelectObject(fe->hdc_bm, fe->prevbm);
290     DeleteDC(fe->hdc_bm);
291     if (fe->clip) {
292         DeleteObject(fe->clip);
293         fe->clip = NULL;
294     }
295 }
296
297 void deactivate_timer(frontend *fe)
298 {
299     KillTimer(fe->hwnd, fe->timer);
300     fe->timer = 0;
301 }
302
303 void activate_timer(frontend *fe)
304 {
305     fe->timer = SetTimer(fe->hwnd, fe->timer, 20, NULL);
306 }
307
308 static frontend *new_window(HINSTANCE inst)
309 {
310     frontend *fe;
311     int x, y;
312     RECT r, sr;
313     HDC hdc;
314     time_t t;
315
316     fe = snew(frontend);
317
318     time(&t);
319     fe->me = midend_new(fe, &t, sizeof(t));
320
321     fe->inst = inst;
322     midend_new_game(fe->me);
323     midend_size(fe->me, &x, &y);
324
325     fe->timer = 0;
326
327     {
328         int i, ncolours;
329         float *colours;
330
331         colours = midend_colours(fe->me, &ncolours);
332
333         fe->colours = snewn(ncolours, COLORREF);
334         fe->brushes = snewn(ncolours, HBRUSH);
335         fe->pens = snewn(ncolours, HPEN);
336
337         for (i = 0; i < ncolours; i++) {
338             fe->colours[i] = RGB(255 * colours[i*3+0],
339                                  255 * colours[i*3+1],
340                                  255 * colours[i*3+2]);
341             fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
342             fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
343         }
344     }
345
346     r.left = r.top = 0;
347     r.right = x;
348     r.bottom = y;
349     AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
350                        (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED),
351                        TRUE, 0);
352
353     fe->hwnd = CreateWindowEx(0, game_name, game_name,
354                               WS_OVERLAPPEDWINDOW &~
355                               (WS_THICKFRAME | WS_MAXIMIZEBOX),
356                               CW_USEDEFAULT, CW_USEDEFAULT,
357                               r.right - r.left, r.bottom - r.top,
358                               NULL, NULL, inst, NULL);
359
360     {
361         HMENU bar = CreateMenu();
362         HMENU menu = CreateMenu();
363
364         AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Game");
365         AppendMenu(menu, MF_ENABLED, IDM_NEW, "New");
366         AppendMenu(menu, MF_ENABLED, IDM_RESTART, "Restart");
367         AppendMenu(menu, MF_ENABLED, IDM_SEED, "Specific...");
368
369         if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
370             game_can_configure) {
371             HMENU sub = CreateMenu();
372             int i;
373
374             AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "Type");
375
376             fe->presets = snewn(fe->npresets, game_params *);
377
378             for (i = 0; i < fe->npresets; i++) {
379                 char *name;
380
381                 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
382
383                 /*
384                  * FIXME: we ought to go through and do something
385                  * with ampersands here.
386                  */
387
388                 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
389             }
390
391             if (game_can_configure) {
392                 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, "Custom...");
393             }
394         }
395
396         AppendMenu(menu, MF_SEPARATOR, 0, 0);
397         AppendMenu(menu, MF_ENABLED, IDM_UNDO, "Undo");
398         AppendMenu(menu, MF_ENABLED, IDM_REDO, "Redo");
399         AppendMenu(menu, MF_SEPARATOR, 0, 0);
400         AppendMenu(menu, MF_ENABLED, IDM_QUIT, "Exit");
401         SetMenu(fe->hwnd, bar);
402     }
403
404     if (midend_wants_statusbar(fe->me)) {
405         fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
406                                        WS_CHILD | WS_VISIBLE,
407                                        0, 0, 0, 0, /* status bar does these */
408                                        fe->hwnd, NULL, inst, NULL);
409         GetWindowRect(fe->statusbar, &sr);
410         SetWindowPos(fe->hwnd, NULL, 0, 0,
411                      r.right - r.left, r.bottom - r.top + sr.bottom - sr.top,
412                      SWP_NOMOVE | SWP_NOZORDER);
413         SetWindowPos(fe->statusbar, NULL, 0, y, x, sr.bottom - sr.top,
414                      SWP_NOZORDER);
415     } else {
416         fe->statusbar = NULL;
417     }
418
419     hdc = GetDC(fe->hwnd);
420     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
421     ReleaseDC(fe->hwnd, hdc);
422
423     SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
424
425     ShowWindow(fe->hwnd, SW_NORMAL);
426     SetForegroundWindow(fe->hwnd);
427
428     midend_redraw(fe->me);
429
430     return fe;
431 }
432
433 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
434                                   WPARAM wParam, LPARAM lParam)
435 {
436     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
437     config_item *i;
438     struct cfg_aux *j;
439
440     switch (msg) {
441       case WM_INITDIALOG:
442         return 0;
443
444       case WM_COMMAND:
445         /*
446          * OK and Cancel are special cases.
447          */
448         if ((HIWORD(wParam) == BN_CLICKED ||
449              HIWORD(wParam) == BN_DOUBLECLICKED) &&
450             (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
451             if (LOWORD(wParam) == IDOK) {
452                 char *err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
453
454                 if (err) {
455                     MessageBox(hwnd, err, "Validation error",
456                                MB_ICONERROR | MB_OK);
457                 } else {
458                     fe->cfg_done = 2;
459                 }
460             } else {
461                 fe->cfg_done = 1;
462             }
463             return 0;
464         }
465
466         /*
467          * First find the control whose id this is.
468          */
469         for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
470             if (j->ctlid == LOWORD(wParam))
471                 break;
472         }
473         if (i->type == C_END)
474             return 0;                  /* not our problem */
475
476         if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
477             char buffer[4096];
478             GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
479             buffer[lenof(buffer)-1] = '\0';
480             sfree(i->sval);
481             i->sval = dupstr(buffer);
482         } else if (i->type == C_BOOLEAN && 
483                    (HIWORD(wParam) == BN_CLICKED ||
484                     HIWORD(wParam) == BN_DOUBLECLICKED)) {
485             i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
486         } else if (i->type == C_CHOICES &&
487                    HIWORD(wParam) == CBN_SELCHANGE) {
488             i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
489                                          CB_GETCURSEL, 0, 0);
490         }
491
492         return 0;
493
494       case WM_CLOSE:
495         fe->cfg_done = 1;
496         return 0;
497     }
498
499     return 0;
500 }
501
502 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
503             char *wclass, int wstyle,
504             int exstyle, char *wtext, int wid)
505 {
506     HWND ret;
507     ret = CreateWindowEx(exstyle, wclass, wtext,
508                          wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
509                          fe->cfgbox, (HMENU) wid, fe->inst, NULL);
510     SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
511     return ret;
512 }
513
514 static int get_config(frontend *fe, int which)
515 {
516     config_item *i;
517     struct cfg_aux *j;
518     char *title;
519     WNDCLASS wc;
520     MSG msg;
521     TEXTMETRIC tm;
522     HDC hdc;
523     HFONT oldfont;
524     SIZE size;
525     HWND ctl;
526     int gm, id, nctrls;
527     int winwidth, winheight, col1l, col1r, col2l, col2r, y;
528     int height, width, maxlabel, maxcheckbox;
529
530     wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
531     wc.lpfnWndProc = DefDlgProc;
532     wc.cbClsExtra = 0;
533     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
534     wc.hInstance = fe->inst;
535     wc.hIcon = NULL;
536     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
537     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
538     wc.lpszMenuName = NULL;
539     wc.lpszClassName = "GameConfigBox";
540     RegisterClass(&wc);
541
542     hdc = GetDC(fe->hwnd);
543     SetMapMode(hdc, MM_TEXT);
544
545     fe->cfg_done = FALSE;
546
547     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
548                              0, 0, 0, 0,
549                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
550                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
551                              DEFAULT_QUALITY,
552                              FF_SWISS,
553                              "MS Shell Dlg");
554
555     oldfont = SelectObject(hdc, fe->cfgfont);
556     if (GetTextMetrics(hdc, &tm)) {
557         height = tm.tmAscent + tm.tmDescent;
558         width = tm.tmAveCharWidth;
559     } else {
560         height = width = 30;
561     }
562
563     fe->cfg = midend_get_config(fe->me, which, &title);
564     fe->cfg_which = which;
565
566     /*
567      * Figure out the layout of the config box by measuring the
568      * length of each piece of text.
569      */
570     maxlabel = maxcheckbox = 0;
571     winheight = height/2;
572
573     for (i = fe->cfg; i->type != C_END; i++) {
574         switch (i->type) {
575           case C_STRING:
576           case C_CHOICES:
577             /*
578              * Both these control types have a label filling only
579              * the left-hand column of the box.
580              */
581             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
582                 maxlabel < size.cx)
583                 maxlabel = size.cx;
584             winheight += height * 3 / 2 + (height / 2);
585             break;
586
587           case C_BOOLEAN:
588             /*
589              * Checkboxes take up the whole of the box width.
590              */
591             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
592                 maxcheckbox < size.cx)
593                 maxcheckbox = size.cx;
594             winheight += height + (height / 2);
595             break;
596         }
597     }
598
599     winheight += height + height * 7 / 4;      /* OK / Cancel buttons */
600
601     col1l = 2*width;
602     col1r = col1l + maxlabel;
603     col2l = col1r + 2*width;
604     col2r = col2l + 30*width;
605     if (col2r < col1l+2*height+maxcheckbox)
606         col2r = col1l+2*height+maxcheckbox;
607     winwidth = col2r + 2*width;
608
609     ReleaseDC(fe->hwnd, hdc);
610
611     /*
612      * Create the dialog, now that we know its size.
613      */
614     {
615         RECT r, r2;
616
617         r.left = r.top = 0;
618         r.right = winwidth;
619         r.bottom = winheight;
620
621         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
622                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
623                                 WS_CAPTION | WS_SYSMENU*/) &~
624                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
625                            FALSE, 0);
626
627         /*
628          * Centre the dialog on its parent window.
629          */
630         r.right -= r.left;
631         r.bottom -= r.top;
632         GetWindowRect(fe->hwnd, &r2);
633         r.left = (r2.left + r2.right - r.right) / 2;
634         r.top = (r2.top + r2.bottom - r.bottom) / 2;
635         r.right += r.left;
636         r.bottom += r.top;
637
638         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
639                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
640                                     WS_CAPTION | WS_SYSMENU,
641                                     r.left, r.top,
642                                     r.right-r.left, r.bottom-r.top,
643                                     fe->hwnd, NULL, fe->inst, NULL);
644         sfree(title);
645     }
646
647     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
648
649     SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
650     SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
651
652     /*
653      * Count the controls so we can allocate cfgaux.
654      */
655     for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
656         nctrls++;
657     fe->cfgaux = snewn(nctrls, struct cfg_aux);
658
659     id = 1000;
660     y = height/2;
661     for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
662         switch (i->type) {
663           case C_STRING:
664             /*
665              * Edit box with a label beside it.
666              */
667             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
668                    "Static", 0, 0, i->name, id++);
669             ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
670                          "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
671                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
672             SetWindowText(ctl, i->sval);
673             y += height*3/2;
674             break;
675
676           case C_BOOLEAN:
677             /*
678              * Simple checkbox.
679              */
680             mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
681                    BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
682                    0, i->name, (j->ctlid = id++));
683             y += height;
684             break;
685
686           case C_CHOICES:
687             /*
688              * Drop-down list with a label beside it.
689              */
690             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
691                    "STATIC", 0, 0, i->name, id++);
692             ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
693                          "COMBOBOX", WS_TABSTOP |
694                          CBS_DROPDOWNLIST | CBS_HASSTRINGS,
695                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
696             {
697                 char c, *p, *q, *str;
698
699                 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
700                 p = i->sval;
701                 c = *p++;
702                 while (*p) {
703                     q = p;
704                     while (*q && *q != c) q++;
705                     str = snewn(q-p+1, char);
706                     strncpy(str, p, q-p);
707                     str[q-p] = '\0';
708                     SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
709                     sfree(str);
710                     if (*q) q++;
711                     p = q;
712                 }
713             }
714
715             SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
716
717             y += height*3/2;
718             break;
719         }
720
721         assert(y < winheight);
722         y += height/2;
723     }
724
725     y += height/2;                     /* extra space before OK and Cancel */
726     mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
727            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
728            "OK", IDOK);
729     mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
730            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP, 0, "Cancel", IDCANCEL);
731
732     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
733
734     EnableWindow(fe->hwnd, FALSE);
735     ShowWindow(fe->cfgbox, SW_NORMAL);
736     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
737         if (!IsDialogMessage(fe->cfgbox, &msg))
738             DispatchMessage(&msg);
739         if (fe->cfg_done)
740             break;
741     }
742     EnableWindow(fe->hwnd, TRUE);
743     SetForegroundWindow(fe->hwnd);
744     DestroyWindow(fe->cfgbox);
745     DeleteObject(fe->cfgfont);
746
747     free_cfg(fe->cfg);
748     sfree(fe->cfgaux);
749
750     return (fe->cfg_done == 2);
751 }
752
753 static void new_game_type(frontend *fe)
754 {
755     RECT r, sr;
756     HDC hdc;
757     int x, y;
758
759     midend_new_game(fe->me);
760     midend_size(fe->me, &x, &y);
761
762     r.left = r.top = 0;
763     r.right = x;
764     r.bottom = y;
765     AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
766                        (WS_THICKFRAME | WS_MAXIMIZEBOX |
767                         WS_OVERLAPPED),
768                        TRUE, 0);
769
770     if (fe->statusbar != NULL) {
771         GetWindowRect(fe->statusbar, &sr);
772     } else {
773         sr.left = sr.right = sr.top = sr.bottom = 0;
774     }
775     SetWindowPos(fe->hwnd, NULL, 0, 0,
776                  r.right - r.left,
777                  r.bottom - r.top + sr.bottom - sr.top,
778                  SWP_NOMOVE | SWP_NOZORDER);
779     if (fe->statusbar != NULL)
780         SetWindowPos(fe->statusbar, NULL, 0, y, x,
781                      sr.bottom - sr.top, SWP_NOZORDER);
782
783     DeleteObject(fe->bitmap);
784
785     hdc = GetDC(fe->hwnd);
786     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
787     ReleaseDC(fe->hwnd, hdc);
788
789     midend_redraw(fe->me);
790 }
791
792 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
793                                 WPARAM wParam, LPARAM lParam)
794 {
795     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
796
797     switch (message) {
798       case WM_CLOSE:
799         DestroyWindow(hwnd);
800         return 0;
801       case WM_COMMAND:
802         switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
803           case IDM_NEW:
804             if (!midend_process_key(fe->me, 0, 0, 'n'))
805                 PostQuitMessage(0);
806             break;
807           case IDM_RESTART:
808             if (!midend_process_key(fe->me, 0, 0, 'r'))
809                 PostQuitMessage(0);
810             break;
811           case IDM_UNDO:
812             if (!midend_process_key(fe->me, 0, 0, 'u'))
813                 PostQuitMessage(0);
814             break;
815           case IDM_REDO:
816             if (!midend_process_key(fe->me, 0, 0, '\x12'))
817                 PostQuitMessage(0);
818             break;
819           case IDM_QUIT:
820             if (!midend_process_key(fe->me, 0, 0, 'q'))
821                 PostQuitMessage(0);
822             break;
823           case IDM_CONFIG:
824             if (get_config(fe, CFG_SETTINGS))
825                 new_game_type(fe);
826             break;
827           case IDM_SEED:
828             if (get_config(fe, CFG_SEED))
829                 new_game_type(fe);
830             break;
831           default:
832             {
833                 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
834
835                 if (p >= 0 && p < fe->npresets) {
836                     midend_set_params(fe->me, fe->presets[p]);
837                     new_game_type(fe);
838                 }
839             }
840             break;
841         }
842         break;
843       case WM_DESTROY:
844         PostQuitMessage(0);
845         return 0;
846       case WM_PAINT:
847         {
848             PAINTSTRUCT p;
849             HDC hdc, hdc2;
850             HBITMAP prevbm;
851
852             hdc = BeginPaint(hwnd, &p);
853             hdc2 = CreateCompatibleDC(hdc);
854             prevbm = SelectObject(hdc2, fe->bitmap);
855             BitBlt(hdc,
856                    p.rcPaint.left, p.rcPaint.top,
857                    p.rcPaint.right - p.rcPaint.left,
858                    p.rcPaint.bottom - p.rcPaint.top,
859                    hdc2,
860                    p.rcPaint.left, p.rcPaint.top,
861                    SRCCOPY);
862             SelectObject(hdc2, prevbm);
863             DeleteDC(hdc2);
864             EndPaint(hwnd, &p);
865         }
866         return 0;
867       case WM_KEYDOWN:
868         {
869             int key = -1;
870
871             switch (wParam) {
872               case VK_LEFT: key = CURSOR_LEFT; break;
873               case VK_RIGHT: key = CURSOR_RIGHT; break;
874               case VK_UP: key = CURSOR_UP; break;
875               case VK_DOWN: key = CURSOR_DOWN; break;
876                 /*
877                  * Diagonal keys on the numeric keypad.
878                  */
879               case VK_PRIOR:
880                 if (!(lParam & 0x01000000)) key = CURSOR_UP_RIGHT;
881                 break;
882               case VK_NEXT:
883                 if (!(lParam & 0x01000000)) key = CURSOR_DOWN_RIGHT;
884                 break;
885               case VK_HOME:
886                 if (!(lParam & 0x01000000)) key = CURSOR_UP_LEFT;
887                 break;
888               case VK_END:
889                 if (!(lParam & 0x01000000)) key = CURSOR_DOWN_LEFT;
890                 break;
891                 /*
892                  * Numeric keypad keys with Num Lock on.
893                  */
894               case VK_NUMPAD4: key = CURSOR_LEFT; break;
895               case VK_NUMPAD6: key = CURSOR_RIGHT; break;
896               case VK_NUMPAD8: key = CURSOR_UP; break;
897               case VK_NUMPAD2: key = CURSOR_DOWN; break;
898               case VK_NUMPAD9: key = CURSOR_UP_RIGHT; break;
899               case VK_NUMPAD3: key = CURSOR_DOWN_RIGHT; break;
900               case VK_NUMPAD7: key = CURSOR_UP_LEFT; break;
901               case VK_NUMPAD1: key = CURSOR_DOWN_LEFT; break;
902             }
903
904             if (key != -1) {
905                 if (!midend_process_key(fe->me, 0, 0, key))
906                     PostQuitMessage(0);
907             } else {
908                 MSG m;
909                 m.hwnd = hwnd;
910                 m.message = WM_KEYDOWN;
911                 m.wParam = wParam;
912                 m.lParam = lParam & 0xdfff;
913                 TranslateMessage(&m);
914             }
915         }
916         break;
917       case WM_LBUTTONDOWN:
918       case WM_RBUTTONDOWN:
919       case WM_MBUTTONDOWN:
920         {
921             int button;
922
923             /*
924              * Shift-clicks count as middle-clicks, since otherwise
925              * two-button Windows users won't have any kind of
926              * middle click to use.
927              */
928             if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
929                 button = MIDDLE_BUTTON;
930             else if (message == WM_LBUTTONDOWN)
931                 button = LEFT_BUTTON;
932             else
933                 button = RIGHT_BUTTON;
934                 
935             if (!midend_process_key(fe->me, LOWORD(lParam),
936                                     HIWORD(lParam), button))
937                 PostQuitMessage(0);
938         }
939         break;
940       case WM_CHAR:
941         if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
942             PostQuitMessage(0);
943         return 0;
944       case WM_TIMER:
945         if (fe->timer)
946             midend_timer(fe->me, (float)0.02);
947         return 0;
948     }
949
950     return DefWindowProc(hwnd, message, wParam, lParam);
951 }
952
953 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
954 {
955     MSG msg;
956
957     InitCommonControls();
958
959     if (!prev) {
960         WNDCLASS wndclass;
961
962         wndclass.style = 0;
963         wndclass.lpfnWndProc = WndProc;
964         wndclass.cbClsExtra = 0;
965         wndclass.cbWndExtra = 0;
966         wndclass.hInstance = inst;
967         wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
968         wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
969         wndclass.hbrBackground = NULL;
970         wndclass.lpszMenuName = NULL;
971         wndclass.lpszClassName = game_name;
972
973         RegisterClass(&wndclass);
974     }
975
976     new_window(inst);
977
978     while (GetMessage(&msg, NULL, 0, 0)) {
979         DispatchMessage(&msg);
980     }
981
982     return msg.wParam;
983 }