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