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