chiark / gitweb /
I've had two complaints that Solo ought to recognise the numeric
[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, i, j;
334     char *data2;
335     void *lock;
336
337     /*
338      * Windows expects CRLF in the clipboard, so we must convert
339      * any \n that has come out of the puzzle backend.
340      */
341     len = 0;
342     for (i = 0; data[i]; i++) {
343         if (data[i] == '\n')
344             len++;
345         len++;
346     }
347     data2 = snewn(len+1, char);
348     j = 0;
349     for (i = 0; data[i]; i++) {
350         if (data[i] == '\n')
351             data2[j++] = '\r';
352         data2[j++] = data[i];
353     }
354     assert(j == len);
355     data2[j] = '\0';
356
357     clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
358     if (!clipdata)
359         return;
360     lock = GlobalLock(clipdata);
361     if (!lock)
362         return;
363     memcpy(lock, data2, len);
364     ((unsigned char *) lock)[len] = 0;
365     GlobalUnlock(clipdata);
366
367     if (OpenClipboard(hwnd)) {
368         EmptyClipboard();
369         SetClipboardData(CF_TEXT, clipdata);
370         CloseClipboard();
371     } else
372         GlobalFree(clipdata);
373
374     sfree(data2);
375 }
376
377 /*
378  * See if we can find a help file.
379  */
380 static void find_help_file(frontend *fe)
381 {
382     char b[2048], *p, *q, *r;
383     FILE *fp;
384     if (!fe->help_path) {
385         GetModuleFileName(NULL, b, sizeof(b) - 1);
386         r = b;
387         p = strrchr(b, '\\');
388         if (p && p >= r) r = p+1;
389         q = strrchr(b, ':');
390         if (q && q >= r) r = q+1;
391         strcpy(r, HELP_FILE_NAME);
392         if ( (fp = fopen(b, "r")) != NULL) {
393             fe->help_path = dupstr(b);
394             fclose(fp);
395         } else
396             fe->help_path = NULL;
397         strcpy(r, HELP_CNT_NAME);
398         if ( (fp = fopen(b, "r")) != NULL) {
399             fe->help_has_contents = TRUE;
400             fclose(fp);
401         } else
402             fe->help_has_contents = FALSE;
403     }
404 }
405
406 static frontend *new_window(HINSTANCE inst, char *game_id, char **error)
407 {
408     frontend *fe;
409     int x, y;
410     RECT r, sr;
411     HDC hdc;
412
413     fe = snew(frontend);
414
415     fe->me = midend_new(fe, &thegame);
416
417     if (game_id) {
418         *error = midend_game_id(fe->me, game_id, FALSE);
419         if (*error) {
420             midend_free(fe->me);
421             sfree(fe);
422             return NULL;
423         }
424     }
425
426     fe->help_path = NULL;
427     find_help_file(fe);
428
429     fe->inst = inst;
430     midend_new_game(fe->me);
431     midend_size(fe->me, &x, &y);
432
433     fe->timer = 0;
434
435     fe->fonts = NULL;
436     fe->nfonts = fe->fontsize = 0;
437
438     {
439         int i, ncolours;
440         float *colours;
441
442         colours = midend_colours(fe->me, &ncolours);
443
444         fe->colours = snewn(ncolours, COLORREF);
445         fe->brushes = snewn(ncolours, HBRUSH);
446         fe->pens = snewn(ncolours, HPEN);
447
448         for (i = 0; i < ncolours; i++) {
449             fe->colours[i] = RGB(255 * colours[i*3+0],
450                                  255 * colours[i*3+1],
451                                  255 * colours[i*3+2]);
452             fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
453             fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
454         }
455     }
456
457     r.left = r.top = 0;
458     r.right = x;
459     r.bottom = y;
460     AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
461                        (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED),
462                        TRUE, 0);
463
464     fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
465                               WS_OVERLAPPEDWINDOW &~
466                               (WS_THICKFRAME | WS_MAXIMIZEBOX),
467                               CW_USEDEFAULT, CW_USEDEFAULT,
468                               r.right - r.left, r.bottom - r.top,
469                               NULL, NULL, inst, NULL);
470
471     {
472         HMENU bar = CreateMenu();
473         HMENU menu = CreateMenu();
474
475         AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Game");
476         AppendMenu(menu, MF_ENABLED, IDM_NEW, "New");
477         AppendMenu(menu, MF_ENABLED, IDM_RESTART, "Restart");
478         AppendMenu(menu, MF_ENABLED, IDM_SEED, "Specific...");
479
480         if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
481             thegame.can_configure) {
482             HMENU sub = CreateMenu();
483             int i;
484
485             AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "Type");
486
487             fe->presets = snewn(fe->npresets, game_params *);
488
489             for (i = 0; i < fe->npresets; i++) {
490                 char *name;
491
492                 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
493
494                 /*
495                  * FIXME: we ought to go through and do something
496                  * with ampersands here.
497                  */
498
499                 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
500             }
501
502             if (thegame.can_configure) {
503                 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, "Custom...");
504             }
505         }
506
507         AppendMenu(menu, MF_SEPARATOR, 0, 0);
508         AppendMenu(menu, MF_ENABLED, IDM_UNDO, "Undo");
509         AppendMenu(menu, MF_ENABLED, IDM_REDO, "Redo");
510         if (thegame.can_format_as_text) {
511             AppendMenu(menu, MF_SEPARATOR, 0, 0);
512             AppendMenu(menu, MF_ENABLED, IDM_COPY, "Copy");
513         }
514         if (thegame.can_solve) {
515             AppendMenu(menu, MF_SEPARATOR, 0, 0);
516             AppendMenu(menu, MF_ENABLED, IDM_SOLVE, "Solve");
517         }
518         AppendMenu(menu, MF_SEPARATOR, 0, 0);
519         AppendMenu(menu, MF_ENABLED, IDM_QUIT, "Exit");
520         if (fe->help_path) {
521             HMENU hmenu = CreateMenu();
522             AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)hmenu, "Help");
523             AppendMenu(hmenu, MF_ENABLED, IDM_HELPC, "Contents");
524             if (thegame.winhelp_topic) {
525                 char *item;
526                 assert(thegame.name);
527                 item = snewn(9+strlen(thegame.name), char); /*ick*/
528                 sprintf(item, "Help on %s", thegame.name);
529                 AppendMenu(hmenu, MF_ENABLED, IDM_GAMEHELP, item);
530                 sfree(item);
531             }
532         }
533         SetMenu(fe->hwnd, bar);
534     }
535
536     if (midend_wants_statusbar(fe->me)) {
537         fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
538                                        WS_CHILD | WS_VISIBLE,
539                                        0, 0, 0, 0, /* status bar does these */
540                                        fe->hwnd, NULL, inst, NULL);
541         GetWindowRect(fe->statusbar, &sr);
542         SetWindowPos(fe->hwnd, NULL, 0, 0,
543                      r.right - r.left, r.bottom - r.top + sr.bottom - sr.top,
544                      SWP_NOMOVE | SWP_NOZORDER);
545         SetWindowPos(fe->statusbar, NULL, 0, y, x, sr.bottom - sr.top,
546                      SWP_NOZORDER);
547     } else {
548         fe->statusbar = NULL;
549     }
550
551     hdc = GetDC(fe->hwnd);
552     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
553     ReleaseDC(fe->hwnd, hdc);
554
555     SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
556
557     ShowWindow(fe->hwnd, SW_NORMAL);
558     SetForegroundWindow(fe->hwnd);
559
560     midend_redraw(fe->me);
561
562     return fe;
563 }
564
565 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
566                                   WPARAM wParam, LPARAM lParam)
567 {
568     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
569     config_item *i;
570     struct cfg_aux *j;
571
572     switch (msg) {
573       case WM_INITDIALOG:
574         return 0;
575
576       case WM_COMMAND:
577         /*
578          * OK and Cancel are special cases.
579          */
580         if ((HIWORD(wParam) == BN_CLICKED ||
581              HIWORD(wParam) == BN_DOUBLECLICKED) &&
582             (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
583             if (LOWORD(wParam) == IDOK) {
584                 char *err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
585
586                 if (err) {
587                     MessageBox(hwnd, err, "Validation error",
588                                MB_ICONERROR | MB_OK);
589                 } else {
590                     fe->cfg_done = 2;
591                 }
592             } else {
593                 fe->cfg_done = 1;
594             }
595             return 0;
596         }
597
598         /*
599          * First find the control whose id this is.
600          */
601         for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
602             if (j->ctlid == LOWORD(wParam))
603                 break;
604         }
605         if (i->type == C_END)
606             return 0;                  /* not our problem */
607
608         if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
609             char buffer[4096];
610             GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
611             buffer[lenof(buffer)-1] = '\0';
612             sfree(i->sval);
613             i->sval = dupstr(buffer);
614         } else if (i->type == C_BOOLEAN && 
615                    (HIWORD(wParam) == BN_CLICKED ||
616                     HIWORD(wParam) == BN_DOUBLECLICKED)) {
617             i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
618         } else if (i->type == C_CHOICES &&
619                    HIWORD(wParam) == CBN_SELCHANGE) {
620             i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
621                                          CB_GETCURSEL, 0, 0);
622         }
623
624         return 0;
625
626       case WM_CLOSE:
627         fe->cfg_done = 1;
628         return 0;
629     }
630
631     return 0;
632 }
633
634 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
635             char *wclass, int wstyle,
636             int exstyle, char *wtext, int wid)
637 {
638     HWND ret;
639     ret = CreateWindowEx(exstyle, wclass, wtext,
640                          wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
641                          fe->cfgbox, (HMENU) wid, fe->inst, NULL);
642     SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
643     return ret;
644 }
645
646 static int get_config(frontend *fe, int which)
647 {
648     config_item *i;
649     struct cfg_aux *j;
650     char *title;
651     WNDCLASS wc;
652     MSG msg;
653     TEXTMETRIC tm;
654     HDC hdc;
655     HFONT oldfont;
656     SIZE size;
657     HWND ctl;
658     int gm, id, nctrls;
659     int winwidth, winheight, col1l, col1r, col2l, col2r, y;
660     int height, width, maxlabel, maxcheckbox;
661
662     wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
663     wc.lpfnWndProc = DefDlgProc;
664     wc.cbClsExtra = 0;
665     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
666     wc.hInstance = fe->inst;
667     wc.hIcon = NULL;
668     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
669     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
670     wc.lpszMenuName = NULL;
671     wc.lpszClassName = "GameConfigBox";
672     RegisterClass(&wc);
673
674     hdc = GetDC(fe->hwnd);
675     SetMapMode(hdc, MM_TEXT);
676
677     fe->cfg_done = FALSE;
678
679     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
680                              0, 0, 0, 0,
681                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
682                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
683                              DEFAULT_QUALITY,
684                              FF_SWISS,
685                              "MS Shell Dlg");
686
687     oldfont = SelectObject(hdc, fe->cfgfont);
688     if (GetTextMetrics(hdc, &tm)) {
689         height = tm.tmAscent + tm.tmDescent;
690         width = tm.tmAveCharWidth;
691     } else {
692         height = width = 30;
693     }
694
695     fe->cfg = midend_get_config(fe->me, which, &title);
696     fe->cfg_which = which;
697
698     /*
699      * Figure out the layout of the config box by measuring the
700      * length of each piece of text.
701      */
702     maxlabel = maxcheckbox = 0;
703     winheight = height/2;
704
705     for (i = fe->cfg; i->type != C_END; i++) {
706         switch (i->type) {
707           case C_STRING:
708           case C_CHOICES:
709             /*
710              * Both these control types have a label filling only
711              * the left-hand column of the box.
712              */
713             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
714                 maxlabel < size.cx)
715                 maxlabel = size.cx;
716             winheight += height * 3 / 2 + (height / 2);
717             break;
718
719           case C_BOOLEAN:
720             /*
721              * Checkboxes take up the whole of the box width.
722              */
723             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
724                 maxcheckbox < size.cx)
725                 maxcheckbox = size.cx;
726             winheight += height + (height / 2);
727             break;
728         }
729     }
730
731     winheight += height + height * 7 / 4;      /* OK / Cancel buttons */
732
733     col1l = 2*width;
734     col1r = col1l + maxlabel;
735     col2l = col1r + 2*width;
736     col2r = col2l + 30*width;
737     if (col2r < col1l+2*height+maxcheckbox)
738         col2r = col1l+2*height+maxcheckbox;
739     winwidth = col2r + 2*width;
740
741     ReleaseDC(fe->hwnd, hdc);
742
743     /*
744      * Create the dialog, now that we know its size.
745      */
746     {
747         RECT r, r2;
748
749         r.left = r.top = 0;
750         r.right = winwidth;
751         r.bottom = winheight;
752
753         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
754                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
755                                 WS_CAPTION | WS_SYSMENU*/) &~
756                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
757                            FALSE, 0);
758
759         /*
760          * Centre the dialog on its parent window.
761          */
762         r.right -= r.left;
763         r.bottom -= r.top;
764         GetWindowRect(fe->hwnd, &r2);
765         r.left = (r2.left + r2.right - r.right) / 2;
766         r.top = (r2.top + r2.bottom - r.bottom) / 2;
767         r.right += r.left;
768         r.bottom += r.top;
769
770         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
771                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
772                                     WS_CAPTION | WS_SYSMENU,
773                                     r.left, r.top,
774                                     r.right-r.left, r.bottom-r.top,
775                                     fe->hwnd, NULL, fe->inst, NULL);
776         sfree(title);
777     }
778
779     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
780
781     SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
782     SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
783
784     /*
785      * Count the controls so we can allocate cfgaux.
786      */
787     for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
788         nctrls++;
789     fe->cfgaux = snewn(nctrls, struct cfg_aux);
790
791     id = 1000;
792     y = height/2;
793     for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
794         switch (i->type) {
795           case C_STRING:
796             /*
797              * Edit box with a label beside it.
798              */
799             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
800                    "Static", 0, 0, i->name, id++);
801             ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
802                          "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
803                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
804             SetWindowText(ctl, i->sval);
805             y += height*3/2;
806             break;
807
808           case C_BOOLEAN:
809             /*
810              * Simple checkbox.
811              */
812             mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
813                    BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
814                    0, i->name, (j->ctlid = id++));
815             CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
816             y += height;
817             break;
818
819           case C_CHOICES:
820             /*
821              * Drop-down list with a label beside it.
822              */
823             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
824                    "STATIC", 0, 0, i->name, id++);
825             ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
826                          "COMBOBOX", WS_TABSTOP |
827                          CBS_DROPDOWNLIST | CBS_HASSTRINGS,
828                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
829             {
830                 char c, *p, *q, *str;
831
832                 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
833                 p = i->sval;
834                 c = *p++;
835                 while (*p) {
836                     q = p;
837                     while (*q && *q != c) q++;
838                     str = snewn(q-p+1, char);
839                     strncpy(str, p, q-p);
840                     str[q-p] = '\0';
841                     SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
842                     sfree(str);
843                     if (*q) q++;
844                     p = q;
845                 }
846             }
847
848             SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
849
850             y += height*3/2;
851             break;
852         }
853
854         assert(y < winheight);
855         y += height/2;
856     }
857
858     y += height/2;                     /* extra space before OK and Cancel */
859     mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
860            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
861            "OK", IDOK);
862     mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
863            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP, 0, "Cancel", IDCANCEL);
864
865     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
866
867     EnableWindow(fe->hwnd, FALSE);
868     ShowWindow(fe->cfgbox, SW_NORMAL);
869     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
870         if (!IsDialogMessage(fe->cfgbox, &msg))
871             DispatchMessage(&msg);
872         if (fe->cfg_done)
873             break;
874     }
875     EnableWindow(fe->hwnd, TRUE);
876     SetForegroundWindow(fe->hwnd);
877     DestroyWindow(fe->cfgbox);
878     DeleteObject(fe->cfgfont);
879
880     free_cfg(fe->cfg);
881     sfree(fe->cfgaux);
882
883     return (fe->cfg_done == 2);
884 }
885
886 static void new_game_type(frontend *fe)
887 {
888     RECT r, sr;
889     HDC hdc;
890     int x, y;
891
892     midend_new_game(fe->me);
893     midend_size(fe->me, &x, &y);
894
895     r.left = r.top = 0;
896     r.right = x;
897     r.bottom = y;
898     AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
899                        (WS_THICKFRAME | WS_MAXIMIZEBOX |
900                         WS_OVERLAPPED),
901                        TRUE, 0);
902
903     if (fe->statusbar != NULL) {
904         GetWindowRect(fe->statusbar, &sr);
905     } else {
906         sr.left = sr.right = sr.top = sr.bottom = 0;
907     }
908     SetWindowPos(fe->hwnd, NULL, 0, 0,
909                  r.right - r.left,
910                  r.bottom - r.top + sr.bottom - sr.top,
911                  SWP_NOMOVE | SWP_NOZORDER);
912     if (fe->statusbar != NULL)
913         SetWindowPos(fe->statusbar, NULL, 0, y, x,
914                      sr.bottom - sr.top, SWP_NOZORDER);
915
916     DeleteObject(fe->bitmap);
917
918     hdc = GetDC(fe->hwnd);
919     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
920     ReleaseDC(fe->hwnd, hdc);
921
922     midend_redraw(fe->me);
923 }
924
925 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
926                                 WPARAM wParam, LPARAM lParam)
927 {
928     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
929
930     switch (message) {
931       case WM_CLOSE:
932         DestroyWindow(hwnd);
933         return 0;
934       case WM_COMMAND:
935         switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
936           case IDM_NEW:
937             if (!midend_process_key(fe->me, 0, 0, 'n'))
938                 PostQuitMessage(0);
939             break;
940           case IDM_RESTART:
941             if (!midend_process_key(fe->me, 0, 0, 'r'))
942                 PostQuitMessage(0);
943             break;
944           case IDM_UNDO:
945             if (!midend_process_key(fe->me, 0, 0, 'u'))
946                 PostQuitMessage(0);
947             break;
948           case IDM_REDO:
949             if (!midend_process_key(fe->me, 0, 0, '\x12'))
950                 PostQuitMessage(0);
951             break;
952           case IDM_COPY:
953             {
954                 char *text = midend_text_format(fe->me);
955                 if (text)
956                     write_clip(hwnd, text);
957                 else
958                     MessageBeep(MB_ICONWARNING);
959                 sfree(text);
960             }
961             break;
962           case IDM_SOLVE:
963             {
964                 char *msg = midend_solve(fe->me);
965                 if (msg)
966                     MessageBox(hwnd, msg, "Unable to solve",
967                                MB_ICONERROR | MB_OK);
968             }
969             break;
970           case IDM_QUIT:
971             if (!midend_process_key(fe->me, 0, 0, 'q'))
972                 PostQuitMessage(0);
973             break;
974           case IDM_CONFIG:
975             if (get_config(fe, CFG_SETTINGS))
976                 new_game_type(fe);
977             break;
978           case IDM_SEED:
979             if (get_config(fe, CFG_SEED))
980                 new_game_type(fe);
981             break;
982           case IDM_HELPC:
983             assert(fe->help_path);
984             WinHelp(hwnd, fe->help_path,
985                     fe->help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
986             break;
987           case IDM_GAMEHELP:
988             assert(fe->help_path);
989             assert(thegame.winhelp_topic);
990             {
991                 char *cmd = snewn(10+strlen(thegame.winhelp_topic), char);
992                 sprintf(cmd, "JI(`',`%s')", thegame.winhelp_topic);
993                 WinHelp(hwnd, fe->help_path, HELP_COMMAND, (DWORD)cmd);
994                 sfree(cmd);
995             }
996             break;
997           default:
998             {
999                 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
1000
1001                 if (p >= 0 && p < fe->npresets) {
1002                     midend_set_params(fe->me, fe->presets[p]);
1003                     new_game_type(fe);
1004                 }
1005             }
1006             break;
1007         }
1008         break;
1009       case WM_DESTROY:
1010         PostQuitMessage(0);
1011         return 0;
1012       case WM_PAINT:
1013         {
1014             PAINTSTRUCT p;
1015             HDC hdc, hdc2;
1016             HBITMAP prevbm;
1017
1018             hdc = BeginPaint(hwnd, &p);
1019             hdc2 = CreateCompatibleDC(hdc);
1020             prevbm = SelectObject(hdc2, fe->bitmap);
1021             BitBlt(hdc,
1022                    p.rcPaint.left, p.rcPaint.top,
1023                    p.rcPaint.right - p.rcPaint.left,
1024                    p.rcPaint.bottom - p.rcPaint.top,
1025                    hdc2,
1026                    p.rcPaint.left, p.rcPaint.top,
1027                    SRCCOPY);
1028             SelectObject(hdc2, prevbm);
1029             DeleteDC(hdc2);
1030             EndPaint(hwnd, &p);
1031         }
1032         return 0;
1033       case WM_KEYDOWN:
1034         {
1035             int key = -1;
1036
1037             switch (wParam) {
1038               case VK_LEFT:
1039                 if (!(lParam & 0x01000000))
1040                     key = MOD_NUM_KEYPAD | '4';
1041                 else
1042                     key = CURSOR_LEFT;
1043                 break;
1044               case VK_RIGHT:
1045                 if (!(lParam & 0x01000000))
1046                     key = MOD_NUM_KEYPAD | '6';
1047                 else
1048                     key = CURSOR_RIGHT;
1049                 break;
1050               case VK_UP:
1051                 if (!(lParam & 0x01000000))
1052                     key = MOD_NUM_KEYPAD | '8';
1053                 else
1054                     key = CURSOR_UP;
1055                 break;
1056               case VK_DOWN:
1057                 if (!(lParam & 0x01000000))
1058                     key = MOD_NUM_KEYPAD | '2';
1059                 else
1060                     key = CURSOR_DOWN;
1061                 break;
1062                 /*
1063                  * Diagonal keys on the numeric keypad.
1064                  */
1065               case VK_PRIOR:
1066                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
1067                 break;
1068               case VK_NEXT:
1069                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
1070                 break;
1071               case VK_HOME:
1072                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
1073                 break;
1074               case VK_END:
1075                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
1076                 break;
1077               case VK_INSERT:
1078                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
1079                 break;
1080               case VK_CLEAR:
1081                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
1082                 break;
1083                 /*
1084                  * Numeric keypad keys with Num Lock on.
1085                  */
1086               case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
1087               case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
1088               case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
1089               case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
1090               case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
1091               case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
1092               case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
1093               case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
1094               case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
1095               case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
1096             }
1097
1098             if (key != -1) {
1099                 if (!midend_process_key(fe->me, 0, 0, key))
1100                     PostQuitMessage(0);
1101             } else {
1102                 MSG m;
1103                 m.hwnd = hwnd;
1104                 m.message = WM_KEYDOWN;
1105                 m.wParam = wParam;
1106                 m.lParam = lParam & 0xdfff;
1107                 TranslateMessage(&m);
1108             }
1109         }
1110         break;
1111       case WM_LBUTTONDOWN:
1112       case WM_RBUTTONDOWN:
1113       case WM_MBUTTONDOWN:
1114         {
1115             int button;
1116
1117             /*
1118              * Shift-clicks count as middle-clicks, since otherwise
1119              * two-button Windows users won't have any kind of
1120              * middle click to use.
1121              */
1122             if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
1123                 button = MIDDLE_BUTTON;
1124             else if (message == WM_LBUTTONDOWN)
1125                 button = LEFT_BUTTON;
1126             else
1127                 button = RIGHT_BUTTON;
1128
1129             if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1130                                     (signed short)HIWORD(lParam), button))
1131                 PostQuitMessage(0);
1132
1133             SetCapture(hwnd);
1134         }
1135         break;
1136       case WM_LBUTTONUP:
1137       case WM_RBUTTONUP:
1138       case WM_MBUTTONUP:
1139         {
1140             int button;
1141
1142             /*
1143              * Shift-clicks count as middle-clicks, since otherwise
1144              * two-button Windows users won't have any kind of
1145              * middle click to use.
1146              */
1147             if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
1148                 button = MIDDLE_RELEASE;
1149             else if (message == WM_LBUTTONUP)
1150                 button = LEFT_RELEASE;
1151             else
1152                 button = RIGHT_RELEASE;
1153
1154             if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1155                                     (signed short)HIWORD(lParam), button))
1156                 PostQuitMessage(0);
1157
1158             ReleaseCapture();
1159         }
1160         break;
1161       case WM_MOUSEMOVE:
1162         {
1163             int button;
1164
1165             if (wParam & (MK_MBUTTON | MK_SHIFT))
1166                 button = MIDDLE_DRAG;
1167             else if (wParam & MK_LBUTTON)
1168                 button = LEFT_DRAG;
1169             else
1170                 button = RIGHT_DRAG;
1171             
1172             if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1173                                     (signed short)HIWORD(lParam), button))
1174                 PostQuitMessage(0);
1175         }
1176         break;
1177       case WM_CHAR:
1178         if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
1179             PostQuitMessage(0);
1180         return 0;
1181       case WM_TIMER:
1182         if (fe->timer) {
1183             DWORD now = GetTickCount();
1184             float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
1185             midend_timer(fe->me, elapsed);
1186             fe->timer_last_tickcount = now;
1187         }
1188         return 0;
1189     }
1190
1191     return DefWindowProc(hwnd, message, wParam, lParam);
1192 }
1193
1194 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
1195 {
1196     MSG msg;
1197     char *error;
1198
1199     InitCommonControls();
1200
1201     if (!prev) {
1202         WNDCLASS wndclass;
1203
1204         wndclass.style = 0;
1205         wndclass.lpfnWndProc = WndProc;
1206         wndclass.cbClsExtra = 0;
1207         wndclass.cbWndExtra = 0;
1208         wndclass.hInstance = inst;
1209         wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
1210         wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
1211         wndclass.hbrBackground = NULL;
1212         wndclass.lpszMenuName = NULL;
1213         wndclass.lpszClassName = thegame.name;
1214
1215         RegisterClass(&wndclass);
1216     }
1217
1218     while (*cmdline && isspace(*cmdline))
1219         cmdline++;
1220
1221     if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
1222         char buf[128];
1223         sprintf(buf, "%.100s Error", thegame.name);
1224         MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
1225         return 1;
1226     }
1227
1228     while (GetMessage(&msg, NULL, 0, 0)) {
1229         DispatchMessage(&msg);
1230     }
1231
1232     return msg.wParam;
1233 }