chiark / gitweb /
Implement selection of game seeds, by reusing the config box
[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
315     fe = snew(frontend);
316     fe->me = midend_new(fe);
317     fe->inst = inst;
318     midend_new_game(fe->me);
319     midend_size(fe->me, &x, &y);
320
321     fe->timer = 0;
322
323     {
324         int i, ncolours;
325         float *colours;
326
327         colours = midend_colours(fe->me, &ncolours);
328
329         fe->colours = snewn(ncolours, COLORREF);
330         fe->brushes = snewn(ncolours, HBRUSH);
331         fe->pens = snewn(ncolours, HPEN);
332
333         for (i = 0; i < ncolours; i++) {
334             fe->colours[i] = RGB(255 * colours[i*3+0],
335                                  255 * colours[i*3+1],
336                                  255 * colours[i*3+2]);
337             fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
338             fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
339         }
340     }
341
342     r.left = r.top = 0;
343     r.right = x;
344     r.bottom = y;
345     AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
346                        (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED),
347                        TRUE, 0);
348
349     fe->hwnd = CreateWindowEx(0, game_name, game_name,
350                               WS_OVERLAPPEDWINDOW &~
351                               (WS_THICKFRAME | WS_MAXIMIZEBOX),
352                               CW_USEDEFAULT, CW_USEDEFAULT,
353                               r.right - r.left, r.bottom - r.top,
354                               NULL, NULL, inst, NULL);
355
356     {
357         HMENU bar = CreateMenu();
358         HMENU menu = CreateMenu();
359
360         AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Game");
361         AppendMenu(menu, MF_ENABLED, IDM_NEW, "New");
362         AppendMenu(menu, MF_ENABLED, IDM_RESTART, "Restart");
363         AppendMenu(menu, MF_ENABLED, IDM_SEED, "Specific...");
364
365         if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
366             game_can_configure) {
367             HMENU sub = CreateMenu();
368             int i;
369
370             AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "Type");
371
372             fe->presets = snewn(fe->npresets, game_params *);
373
374             for (i = 0; i < fe->npresets; i++) {
375                 char *name;
376
377                 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
378
379                 /*
380                  * FIXME: we ought to go through and do something
381                  * with ampersands here.
382                  */
383
384                 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
385             }
386
387             if (game_can_configure) {
388                 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, "Custom...");
389             }
390         }
391
392         AppendMenu(menu, MF_SEPARATOR, 0, 0);
393         AppendMenu(menu, MF_ENABLED, IDM_UNDO, "Undo");
394         AppendMenu(menu, MF_ENABLED, IDM_REDO, "Redo");
395         AppendMenu(menu, MF_SEPARATOR, 0, 0);
396         AppendMenu(menu, MF_ENABLED, IDM_QUIT, "Exit");
397         SetMenu(fe->hwnd, bar);
398     }
399
400     if (midend_wants_statusbar(fe->me)) {
401         fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
402                                        WS_CHILD | WS_VISIBLE,
403                                        0, 0, 0, 0, /* status bar does these */
404                                        fe->hwnd, NULL, inst, NULL);
405         GetWindowRect(fe->statusbar, &sr);
406         SetWindowPos(fe->hwnd, NULL, 0, 0,
407                      r.right - r.left, r.bottom - r.top + sr.bottom - sr.top,
408                      SWP_NOMOVE | SWP_NOZORDER);
409         SetWindowPos(fe->statusbar, NULL, 0, y, x, sr.bottom - sr.top,
410                      SWP_NOZORDER);
411     } else {
412         fe->statusbar = NULL;
413     }
414
415     hdc = GetDC(fe->hwnd);
416     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
417     ReleaseDC(fe->hwnd, hdc);
418
419     SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
420
421     ShowWindow(fe->hwnd, SW_NORMAL);
422     SetForegroundWindow(fe->hwnd);
423
424     midend_redraw(fe->me);
425
426     return fe;
427 }
428
429 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
430                                   WPARAM wParam, LPARAM lParam)
431 {
432     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
433     config_item *i;
434     struct cfg_aux *j;
435
436     switch (msg) {
437       case WM_INITDIALOG:
438         return 0;
439
440       case WM_COMMAND:
441         /*
442          * OK and Cancel are special cases.
443          */
444         if ((HIWORD(wParam) == BN_CLICKED ||
445              HIWORD(wParam) == BN_DOUBLECLICKED) &&
446             (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
447             if (LOWORD(wParam) == IDOK) {
448                 char *err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
449
450                 if (err) {
451                     MessageBox(hwnd, err, "Validation error",
452                                MB_ICONERROR | MB_OK);
453                 } else {
454                     fe->cfg_done = 2;
455                 }
456             } else {
457                 fe->cfg_done = 1;
458             }
459             return 0;
460         }
461
462         /*
463          * First find the control whose id this is.
464          */
465         for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
466             if (j->ctlid == LOWORD(wParam))
467                 break;
468         }
469         if (i->type == C_END)
470             return 0;                  /* not our problem */
471
472         if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
473             char buffer[4096];
474             GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
475             buffer[lenof(buffer)-1] = '\0';
476             sfree(i->sval);
477             i->sval = dupstr(buffer);
478         } else if (i->type == C_BOOLEAN && 
479                    (HIWORD(wParam) == BN_CLICKED ||
480                     HIWORD(wParam) == BN_DOUBLECLICKED)) {
481             i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
482         } else if (i->type == C_CHOICES &&
483                    HIWORD(wParam) == CBN_SELCHANGE) {
484             i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
485                                          CB_GETCURSEL, 0, 0);
486         }
487
488         return 0;
489
490       case WM_CLOSE:
491         fe->cfg_done = 1;
492         return 0;
493     }
494
495     return 0;
496 }
497
498 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
499             char *wclass, int wstyle,
500             int exstyle, char *wtext, int wid)
501 {
502     HWND ret;
503     ret = CreateWindowEx(exstyle, wclass, wtext,
504                          wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
505                          fe->cfgbox, (HMENU) wid, fe->inst, NULL);
506     SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
507     return ret;
508 }
509
510 static int get_config(frontend *fe, int which)
511 {
512     config_item *i;
513     struct cfg_aux *j;
514     char *title;
515     WNDCLASS wc;
516     MSG msg;
517     TEXTMETRIC tm;
518     HDC hdc;
519     HFONT oldfont;
520     SIZE size;
521     HWND ctl;
522     int gm, id, nctrls;
523     int winwidth, winheight, col1l, col1r, col2l, col2r, y;
524     int height, width, maxlabel, maxcheckbox;
525
526     wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
527     wc.lpfnWndProc = DefDlgProc;
528     wc.cbClsExtra = 0;
529     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
530     wc.hInstance = fe->inst;
531     wc.hIcon = NULL;
532     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
533     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
534     wc.lpszMenuName = NULL;
535     wc.lpszClassName = "GameConfigBox";
536     RegisterClass(&wc);
537
538     hdc = GetDC(fe->hwnd);
539     SetMapMode(hdc, MM_TEXT);
540
541     fe->cfg_done = FALSE;
542
543     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
544                              0, 0, 0, 0,
545                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
546                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
547                              DEFAULT_QUALITY,
548                              FF_SWISS,
549                              "MS Shell Dlg");
550
551     oldfont = SelectObject(hdc, fe->cfgfont);
552     if (GetTextMetrics(hdc, &tm)) {
553         height = tm.tmAscent + tm.tmDescent;
554         width = tm.tmAveCharWidth;
555     } else {
556         height = width = 30;
557     }
558
559     fe->cfg = midend_get_config(fe->me, which, &title);
560     fe->cfg_which = which;
561
562     /*
563      * Figure out the layout of the config box by measuring the
564      * length of each piece of text.
565      */
566     maxlabel = maxcheckbox = 0;
567     winheight = height/2;
568
569     for (i = fe->cfg; i->type != C_END; i++) {
570         switch (i->type) {
571           case C_STRING:
572           case C_CHOICES:
573             /*
574              * Both these control types have a label filling only
575              * the left-hand column of the box.
576              */
577             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
578                 maxlabel < size.cx)
579                 maxlabel = size.cx;
580             winheight += height * 3 / 2 + (height / 2);
581             break;
582
583           case C_BOOLEAN:
584             /*
585              * Checkboxes take up the whole of the box width.
586              */
587             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
588                 maxcheckbox < size.cx)
589                 maxcheckbox = size.cx;
590             winheight += height + (height / 2);
591             break;
592         }
593     }
594
595     winheight += height + height * 7 / 4;      /* OK / Cancel buttons */
596
597     col1l = 2*width;
598     col1r = col1l + maxlabel;
599     col2l = col1r + 2*width;
600     col2r = col2l + 30*width;
601     if (col2r < col1l+2*height+maxcheckbox)
602         col2r = col1l+2*height+maxcheckbox;
603     winwidth = col2r + 2*width;
604
605     ReleaseDC(fe->hwnd, hdc);
606
607     /*
608      * Create the dialog, now that we know its size.
609      */
610     {
611         RECT r, r2;
612
613         r.left = r.top = 0;
614         r.right = winwidth;
615         r.bottom = winheight;
616
617         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
618                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
619                                 WS_CAPTION | WS_SYSMENU*/) &~
620                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
621                            FALSE, 0);
622
623         /*
624          * Centre the dialog on its parent window.
625          */
626         r.right -= r.left;
627         r.bottom -= r.top;
628         GetWindowRect(fe->hwnd, &r2);
629         r.left = (r2.left + r2.right - r.right) / 2;
630         r.top = (r2.top + r2.bottom - r.bottom) / 2;
631         r.right += r.left;
632         r.bottom += r.top;
633
634         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
635                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
636                                     WS_CAPTION | WS_SYSMENU,
637                                     r.left, r.top,
638                                     r.right-r.left, r.bottom-r.top,
639                                     fe->hwnd, NULL, fe->inst, NULL);
640         sfree(title);
641     }
642
643     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
644
645     SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
646     SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
647
648     /*
649      * Count the controls so we can allocate cfgaux.
650      */
651     for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
652         nctrls++;
653     fe->cfgaux = snewn(nctrls, struct cfg_aux);
654
655     id = 1000;
656     y = height/2;
657     for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
658         switch (i->type) {
659           case C_STRING:
660             /*
661              * Edit box with a label beside it.
662              */
663             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
664                    "Static", 0, 0, i->name, id++);
665             ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
666                          "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
667                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
668             SetWindowText(ctl, i->sval);
669             y += height*3/2;
670             break;
671
672           case C_BOOLEAN:
673             /*
674              * Simple checkbox.
675              */
676             mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
677                    BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
678                    0, i->name, (j->ctlid = id++));
679             y += height;
680             break;
681
682           case C_CHOICES:
683             /*
684              * Drop-down list with a label beside it.
685              */
686             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
687                    "STATIC", 0, 0, i->name, id++);
688             ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
689                          "COMBOBOX", WS_TABSTOP |
690                          CBS_DROPDOWNLIST | CBS_HASSTRINGS,
691                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
692             {
693                 char c, *p, *q, *str;
694
695                 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
696                 p = i->sval;
697                 c = *p++;
698                 while (*p) {
699                     q = p;
700                     while (*q && *q != c) q++;
701                     str = snewn(q-p+1, char);
702                     strncpy(str, p, q-p);
703                     str[q-p] = '\0';
704                     SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
705                     sfree(str);
706                     if (*q) q++;
707                     p = q;
708                 }
709             }
710
711             SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
712
713             y += height*3/2;
714             break;
715         }
716
717         assert(y < winheight);
718         y += height/2;
719     }
720
721     y += height/2;                     /* extra space before OK and Cancel */
722     mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
723            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
724            "OK", IDOK);
725     mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
726            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP, 0, "Cancel", IDCANCEL);
727
728     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
729
730     EnableWindow(fe->hwnd, FALSE);
731     ShowWindow(fe->cfgbox, SW_NORMAL);
732     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
733         if (!IsDialogMessage(fe->cfgbox, &msg))
734             DispatchMessage(&msg);
735         if (fe->cfg_done)
736             break;
737     }
738     EnableWindow(fe->hwnd, TRUE);
739     SetForegroundWindow(fe->hwnd);
740     DestroyWindow(fe->cfgbox);
741     DeleteObject(fe->cfgfont);
742
743     free_cfg(fe->cfg);
744     sfree(fe->cfgaux);
745
746     return (fe->cfg_done == 2);
747 }
748
749 static void new_game_type(frontend *fe)
750 {
751     RECT r, sr;
752     HDC hdc;
753     int x, y;
754
755     midend_new_game(fe->me);
756     midend_size(fe->me, &x, &y);
757
758     r.left = r.top = 0;
759     r.right = x;
760     r.bottom = y;
761     AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
762                        (WS_THICKFRAME | WS_MAXIMIZEBOX |
763                         WS_OVERLAPPED),
764                        TRUE, 0);
765
766     if (fe->statusbar != NULL) {
767         GetWindowRect(fe->statusbar, &sr);
768     } else {
769         sr.left = sr.right = sr.top = sr.bottom = 0;
770     }
771     SetWindowPos(fe->hwnd, NULL, 0, 0,
772                  r.right - r.left,
773                  r.bottom - r.top + sr.bottom - sr.top,
774                  SWP_NOMOVE | SWP_NOZORDER);
775     if (fe->statusbar != NULL)
776         SetWindowPos(fe->statusbar, NULL, 0, y, x,
777                      sr.bottom - sr.top, SWP_NOZORDER);
778
779     DeleteObject(fe->bitmap);
780
781     hdc = GetDC(fe->hwnd);
782     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
783     ReleaseDC(fe->hwnd, hdc);
784
785     midend_redraw(fe->me);
786 }
787
788 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
789                                 WPARAM wParam, LPARAM lParam)
790 {
791     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
792
793     switch (message) {
794       case WM_CLOSE:
795         DestroyWindow(hwnd);
796         return 0;
797       case WM_COMMAND:
798         switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
799           case IDM_NEW:
800             if (!midend_process_key(fe->me, 0, 0, 'n'))
801                 PostQuitMessage(0);
802             break;
803           case IDM_RESTART:
804             if (!midend_process_key(fe->me, 0, 0, 'r'))
805                 PostQuitMessage(0);
806             break;
807           case IDM_UNDO:
808             if (!midend_process_key(fe->me, 0, 0, 'u'))
809                 PostQuitMessage(0);
810             break;
811           case IDM_REDO:
812             if (!midend_process_key(fe->me, 0, 0, '\x12'))
813                 PostQuitMessage(0);
814             break;
815           case IDM_QUIT:
816             if (!midend_process_key(fe->me, 0, 0, 'q'))
817                 PostQuitMessage(0);
818             break;
819           case IDM_CONFIG:
820             if (get_config(fe, CFG_SETTINGS))
821                 new_game_type(fe);
822             break;
823           case IDM_SEED:
824             if (get_config(fe, CFG_SEED))
825                 new_game_type(fe);
826             break;
827           default:
828             {
829                 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
830
831                 if (p >= 0 && p < fe->npresets) {
832                     midend_set_params(fe->me, fe->presets[p]);
833                     new_game_type(fe);
834                 }
835             }
836             break;
837         }
838         break;
839       case WM_DESTROY:
840         PostQuitMessage(0);
841         return 0;
842       case WM_PAINT:
843         {
844             PAINTSTRUCT p;
845             HDC hdc, hdc2;
846             HBITMAP prevbm;
847
848             hdc = BeginPaint(hwnd, &p);
849             hdc2 = CreateCompatibleDC(hdc);
850             prevbm = SelectObject(hdc2, fe->bitmap);
851             BitBlt(hdc,
852                    p.rcPaint.left, p.rcPaint.top,
853                    p.rcPaint.right - p.rcPaint.left,
854                    p.rcPaint.bottom - p.rcPaint.top,
855                    hdc2,
856                    p.rcPaint.left, p.rcPaint.top,
857                    SRCCOPY);
858             SelectObject(hdc2, prevbm);
859             DeleteDC(hdc2);
860             EndPaint(hwnd, &p);
861         }
862         return 0;
863       case WM_KEYDOWN:
864         {
865             int key = -1;
866
867             switch (wParam) {
868               case VK_LEFT: key = CURSOR_LEFT; break;
869               case VK_RIGHT: key = CURSOR_RIGHT; break;
870               case VK_UP: key = CURSOR_UP; break;
871               case VK_DOWN: key = CURSOR_DOWN; break;
872                 /*
873                  * Diagonal keys on the numeric keypad.
874                  */
875               case VK_PRIOR:
876                 if (!(lParam & 0x01000000)) key = CURSOR_UP_RIGHT;
877                 break;
878               case VK_NEXT:
879                 if (!(lParam & 0x01000000)) key = CURSOR_DOWN_RIGHT;
880                 break;
881               case VK_HOME:
882                 if (!(lParam & 0x01000000)) key = CURSOR_UP_LEFT;
883                 break;
884               case VK_END:
885                 if (!(lParam & 0x01000000)) key = CURSOR_DOWN_LEFT;
886                 break;
887                 /*
888                  * Numeric keypad keys with Num Lock on.
889                  */
890               case VK_NUMPAD4: key = CURSOR_LEFT; break;
891               case VK_NUMPAD6: key = CURSOR_RIGHT; break;
892               case VK_NUMPAD8: key = CURSOR_UP; break;
893               case VK_NUMPAD2: key = CURSOR_DOWN; break;
894               case VK_NUMPAD9: key = CURSOR_UP_RIGHT; break;
895               case VK_NUMPAD3: key = CURSOR_DOWN_RIGHT; break;
896               case VK_NUMPAD7: key = CURSOR_UP_LEFT; break;
897               case VK_NUMPAD1: key = CURSOR_DOWN_LEFT; break;
898             }
899
900             if (key != -1) {
901                 if (!midend_process_key(fe->me, 0, 0, key))
902                     PostQuitMessage(0);
903             } else {
904                 MSG m;
905                 m.hwnd = hwnd;
906                 m.message = WM_KEYDOWN;
907                 m.wParam = wParam;
908                 m.lParam = lParam & 0xdfff;
909                 TranslateMessage(&m);
910             }
911         }
912         break;
913       case WM_LBUTTONDOWN:
914       case WM_RBUTTONDOWN:
915       case WM_MBUTTONDOWN:
916         {
917             int button;
918
919             /*
920              * Shift-clicks count as middle-clicks, since otherwise
921              * two-button Windows users won't have any kind of
922              * middle click to use.
923              */
924             if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
925                 button = MIDDLE_BUTTON;
926             else if (message == WM_LBUTTONDOWN)
927                 button = LEFT_BUTTON;
928             else
929                 button = RIGHT_BUTTON;
930                 
931             if (!midend_process_key(fe->me, LOWORD(lParam),
932                                     HIWORD(lParam), button))
933                 PostQuitMessage(0);
934         }
935         break;
936       case WM_CHAR:
937         if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
938             PostQuitMessage(0);
939         return 0;
940       case WM_TIMER:
941         if (fe->timer)
942             midend_timer(fe->me, (float)0.02);
943         return 0;
944     }
945
946     return DefWindowProc(hwnd, message, wParam, lParam);
947 }
948
949 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
950 {
951     MSG msg;
952
953     srand(time(NULL));
954
955     InitCommonControls();
956
957     if (!prev) {
958         WNDCLASS wndclass;
959
960         wndclass.style = 0;
961         wndclass.lpfnWndProc = WndProc;
962         wndclass.cbClsExtra = 0;
963         wndclass.cbWndExtra = 0;
964         wndclass.hInstance = inst;
965         wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
966         wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
967         wndclass.hbrBackground = NULL;
968         wndclass.lpszMenuName = NULL;
969         wndclass.lpszClassName = game_name;
970
971         RegisterClass(&wndclass);
972     }
973
974     new_window(inst);
975
976     while (GetMessage(&msg, NULL, 0, 0)) {
977         DispatchMessage(&msg);
978     }
979
980     return msg.wParam;
981 }