chiark / gitweb /
Substantial infrastructure upheaval. I've separated the drawing API
[sgt-puzzles.git] / windows.c
1 /*
2  * windows.c: Windows front end for my puzzle collection.
3  */
4
5 #include <windows.h>
6 #include <commctrl.h>
7
8 #include <stdio.h>
9 #include <assert.h>
10 #include <ctype.h>
11 #include <stdarg.h>
12 #include <stdlib.h>
13 #include <limits.h>
14 #include <time.h>
15
16 #include "puzzles.h"
17
18 #define IDM_NEW       0x0010
19 #define IDM_RESTART   0x0020
20 #define IDM_UNDO      0x0030
21 #define IDM_REDO      0x0040
22 #define IDM_COPY      0x0050
23 #define IDM_SOLVE     0x0060
24 #define IDM_QUIT      0x0070
25 #define IDM_CONFIG    0x0080
26 #define IDM_DESC      0x0090
27 #define IDM_SEED      0x00A0
28 #define IDM_HELPC     0x00B0
29 #define IDM_GAMEHELP  0x00C0
30 #define IDM_ABOUT     0x00D0
31 #define IDM_SAVE      0x00E0
32 #define IDM_LOAD      0x00F0
33 #define IDM_PRESETS   0x0100
34
35 #define HELP_FILE_NAME  "puzzles.hlp"
36 #define HELP_CNT_NAME   "puzzles.cnt"
37
38 #ifdef DEBUGGING
39 static FILE *debug_fp = NULL;
40 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
41 static int debug_got_console = 0;
42
43 void dputs(char *buf)
44 {
45     DWORD dw;
46
47     if (!debug_got_console) {
48         if (AllocConsole()) {
49             debug_got_console = 1;
50             debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
51         }
52     }
53     if (!debug_fp) {
54         debug_fp = fopen("debug.log", "w");
55     }
56
57     if (debug_hdl != INVALID_HANDLE_VALUE) {
58         WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
59     }
60     fputs(buf, debug_fp);
61     fflush(debug_fp);
62 }
63
64 void debug_printf(char *fmt, ...)
65 {
66     char buf[4096];
67     va_list ap;
68
69     va_start(ap, fmt);
70     vsprintf(buf, fmt, ap);
71     dputs(buf);
72     va_end(ap);
73 }
74 #endif
75
76 struct font {
77     HFONT font;
78     int type;
79     int size;
80 };
81
82 struct cfg_aux {
83     int ctlid;
84 };
85
86 struct blitter {
87     HBITMAP bitmap;
88     frontend *fe;
89     int x, y, w, h;
90 };
91
92 struct frontend {
93     midend *me;
94     HWND hwnd, statusbar, cfgbox;
95     HINSTANCE inst;
96     HBITMAP bitmap, prevbm;
97     HDC hdc_bm;
98     COLORREF *colours;
99     HBRUSH *brushes;
100     HPEN *pens;
101     HRGN clip;
102     UINT timer;
103     DWORD timer_last_tickcount;
104     int npresets;
105     game_params **presets;
106     struct font *fonts;
107     int nfonts, fontsize;
108     config_item *cfg;
109     struct cfg_aux *cfgaux;
110     int cfg_which, dlg_done;
111     HFONT cfgfont;
112     char *help_path;
113     int help_has_contents;
114     char *laststatus;
115 };
116
117 void fatal(char *fmt, ...)
118 {
119     char buf[2048];
120     va_list ap;
121
122     va_start(ap, fmt);
123     vsprintf(buf, fmt, ap);
124     va_end(ap);
125
126     MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
127
128     exit(1);
129 }
130
131 void get_random_seed(void **randseed, int *randseedsize)
132 {
133     time_t *tp = snew(time_t);
134     time(tp);
135     *randseed = (void *)tp;
136     *randseedsize = sizeof(time_t);
137 }
138
139 static void win_status_bar(void *handle, char *text)
140 {
141     frontend *fe = (frontend *)handle;
142     char *rewritten = midend_rewrite_statusbar(fe->me, text);
143     if (!fe->laststatus || strcmp(rewritten, fe->laststatus)) {
144         SetWindowText(fe->statusbar, rewritten);
145         sfree(fe->laststatus);
146         fe->laststatus = rewritten;
147     } else {
148         sfree(rewritten);
149     }
150 }
151
152 static blitter *win_blitter_new(void *handle, int w, int h)
153 {
154     blitter *bl = snew(blitter);
155
156     memset(bl, 0, sizeof(blitter));
157     bl->w = w;
158     bl->h = h;
159     bl->bitmap = 0;
160
161     return bl;
162 }
163
164 static void win_blitter_free(void *handle, blitter *bl)
165 {
166     if (bl->bitmap) DeleteObject(bl->bitmap);
167     sfree(bl);
168 }
169
170 static void blitter_mkbitmap(frontend *fe, blitter *bl)
171 {
172     HDC hdc = GetDC(fe->hwnd);
173     bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
174     ReleaseDC(fe->hwnd, hdc);
175 }
176
177 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
178
179 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
180 {
181     frontend *fe = (frontend *)handle;
182     HDC hdc_win, hdc_blit;
183     HBITMAP prev_blit;
184
185     if (!bl->bitmap) blitter_mkbitmap(fe, bl);
186
187     bl->x = x; bl->y = y;
188
189     hdc_win = GetDC(fe->hwnd);
190     hdc_blit = CreateCompatibleDC(hdc_win);
191     if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
192
193     prev_blit = SelectObject(hdc_blit, bl->bitmap);
194     if (prev_blit == NULL || prev_blit == HGDI_ERROR)
195         fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
196
197     if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
198                 fe->hdc_bm, x, y, SRCCOPY))
199         fatal("BitBlt failed: 0x%x", GetLastError());
200
201     SelectObject(hdc_blit, prev_blit);
202     DeleteDC(hdc_blit);
203     ReleaseDC(fe->hwnd, hdc_win);
204 }
205
206 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
207 {
208     frontend *fe = (frontend *)handle;
209     HDC hdc_win, hdc_blit;
210     HBITMAP prev_blit;
211
212     assert(bl->bitmap); /* we should always have saved before loading */
213
214     if (x == BLITTER_FROMSAVED) x = bl->x;
215     if (y == BLITTER_FROMSAVED) y = bl->y;
216
217     hdc_win = GetDC(fe->hwnd);
218     hdc_blit = CreateCompatibleDC(hdc_win);
219
220     prev_blit = SelectObject(hdc_blit, bl->bitmap);
221
222     BitBlt(fe->hdc_bm, x, y, bl->w, bl->h,
223            hdc_blit, 0, 0, SRCCOPY);
224
225     SelectObject(hdc_blit, prev_blit);
226     DeleteDC(hdc_blit);
227     ReleaseDC(fe->hwnd, hdc_win);
228 }
229
230 void frontend_default_colour(frontend *fe, float *output)
231 {
232     DWORD c = GetSysColor(COLOR_MENU); /* ick */
233
234     output[0] = (float)(GetRValue(c) / 255.0);
235     output[1] = (float)(GetGValue(c) / 255.0);
236     output[2] = (float)(GetBValue(c) / 255.0);
237 }
238
239 static void win_clip(void *handle, int x, int y, int w, int h)
240 {
241     frontend *fe = (frontend *)handle;
242     IntersectClipRect(fe->hdc_bm, x, y, x+w, y+h);
243 }
244
245 static void win_unclip(void *handle)
246 {
247     frontend *fe = (frontend *)handle;
248     SelectClipRgn(fe->hdc_bm, NULL);
249 }
250
251 static void win_draw_text(void *handle, int x, int y, int fonttype,
252                           int fontsize, int align, int colour, char *text)
253 {
254     frontend *fe = (frontend *)handle;
255     int i;
256
257     /*
258      * Find or create the font.
259      */
260     for (i = 0; i < fe->nfonts; i++)
261         if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
262             break;
263
264     if (i == fe->nfonts) {
265         if (fe->fontsize <= fe->nfonts) {
266             fe->fontsize = fe->nfonts + 10;
267             fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
268         }
269
270         fe->nfonts++;
271
272         fe->fonts[i].type = fonttype;
273         fe->fonts[i].size = fontsize;
274
275         fe->fonts[i].font = CreateFont(-fontsize, 0, 0, 0, FW_BOLD,
276                                        FALSE, FALSE, FALSE, DEFAULT_CHARSET,
277                                        OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
278                                        DEFAULT_QUALITY,
279                                        (fonttype == FONT_FIXED ?
280                                         FIXED_PITCH | FF_DONTCARE :
281                                         VARIABLE_PITCH | FF_SWISS),
282                                        NULL);
283     }
284
285     /*
286      * Position and draw the text.
287      */
288     {
289         HFONT oldfont;
290         TEXTMETRIC tm;
291         SIZE size;
292
293         oldfont = SelectObject(fe->hdc_bm, fe->fonts[i].font);
294         if (GetTextMetrics(fe->hdc_bm, &tm)) {
295             if (align & ALIGN_VCENTRE)
296                 y -= (tm.tmAscent+tm.tmDescent)/2;
297             else
298                 y -= tm.tmAscent;
299         }
300         if (GetTextExtentPoint32(fe->hdc_bm, text, strlen(text), &size)) {
301             if (align & ALIGN_HCENTRE)
302                 x -= size.cx / 2;
303             else if (align & ALIGN_HRIGHT)
304                 x -= size.cx;
305         }
306         SetBkMode(fe->hdc_bm, TRANSPARENT);
307         SetTextColor(fe->hdc_bm, fe->colours[colour]);
308         TextOut(fe->hdc_bm, x, y, text, strlen(text));
309         SelectObject(fe->hdc_bm, oldfont);
310     }
311 }
312
313 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
314 {
315     frontend *fe = (frontend *)handle;
316     if (w == 1 && h == 1) {
317         /*
318          * Rectangle() appears to get uppity if asked to draw a 1x1
319          * rectangle, presumably on the grounds that that's beneath
320          * its dignity and you ought to be using SetPixel instead.
321          * So I will.
322          */
323         SetPixel(fe->hdc_bm, x, y, fe->colours[colour]);
324     } else {
325         HBRUSH oldbrush = SelectObject(fe->hdc_bm, fe->brushes[colour]);
326         HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[colour]);
327         Rectangle(fe->hdc_bm, x, y, x+w, y+h);
328         SelectObject(fe->hdc_bm, oldbrush);
329         SelectObject(fe->hdc_bm, oldpen);
330     }
331 }
332
333 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
334 {
335     frontend *fe = (frontend *)handle;
336     HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[colour]);
337     MoveToEx(fe->hdc_bm, x1, y1, NULL);
338     LineTo(fe->hdc_bm, x2, y2);
339     SetPixel(fe->hdc_bm, x2, y2, fe->colours[colour]);
340     SelectObject(fe->hdc_bm, oldpen);
341 }
342
343 static void win_draw_circle(void *handle, int cx, int cy, int radius,
344                             int fillcolour, int outlinecolour)
345 {
346     frontend *fe = (frontend *)handle;
347     assert(outlinecolour >= 0);
348
349     if (fillcolour >= 0) {
350         HBRUSH oldbrush = SelectObject(fe->hdc_bm, fe->brushes[fillcolour]);
351         HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[outlinecolour]);
352         Ellipse(fe->hdc_bm, cx - radius, cy - radius,
353                 cx + radius + 1, cy + radius + 1);
354         SelectObject(fe->hdc_bm, oldbrush);
355         SelectObject(fe->hdc_bm, oldpen);
356     } else {
357         HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[outlinecolour]);
358         Arc(fe->hdc_bm, cx - radius, cy - radius,
359             cx + radius + 1, cy + radius + 1,
360             cx - radius, cy, cx - radius, cy);
361         SelectObject(fe->hdc_bm, oldpen);
362     }
363 }
364
365 static void win_draw_polygon(void *handle, int *coords, int npoints,
366                              int fillcolour, int outlinecolour)
367 {
368     frontend *fe = (frontend *)handle;
369     POINT *pts = snewn(npoints+1, POINT);
370     int i;
371
372     for (i = 0; i <= npoints; i++) {
373         int j = (i < npoints ? i : 0);
374         pts[i].x = coords[j*2];
375         pts[i].y = coords[j*2+1];
376     }
377
378     assert(outlinecolour >= 0);
379
380     if (fillcolour >= 0) {
381         HBRUSH oldbrush = SelectObject(fe->hdc_bm, fe->brushes[fillcolour]);
382         HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[outlinecolour]);
383         Polygon(fe->hdc_bm, pts, npoints);
384         SelectObject(fe->hdc_bm, oldbrush);
385         SelectObject(fe->hdc_bm, oldpen);
386     } else {
387         HPEN oldpen = SelectObject(fe->hdc_bm, fe->pens[outlinecolour]);
388         Polyline(fe->hdc_bm, pts, npoints+1);
389         SelectObject(fe->hdc_bm, oldpen);
390     }
391
392     sfree(pts);
393 }
394
395 static void win_start_draw(void *handle)
396 {
397     frontend *fe = (frontend *)handle;
398     HDC hdc_win;
399     hdc_win = GetDC(fe->hwnd);
400     fe->hdc_bm = CreateCompatibleDC(hdc_win);
401     fe->prevbm = SelectObject(fe->hdc_bm, fe->bitmap);
402     ReleaseDC(fe->hwnd, hdc_win);
403     fe->clip = NULL;
404     SetMapMode(fe->hdc_bm, MM_TEXT);
405 }
406
407 static void win_draw_update(void *handle, int x, int y, int w, int h)
408 {
409     frontend *fe = (frontend *)handle;
410     RECT r;
411
412     r.left = x;
413     r.top = y;
414     r.right = x + w;
415     r.bottom = y + h;
416
417     InvalidateRect(fe->hwnd, &r, FALSE);
418 }
419
420 static void win_end_draw(void *handle)
421 {
422     frontend *fe = (frontend *)handle;
423     SelectObject(fe->hdc_bm, fe->prevbm);
424     DeleteDC(fe->hdc_bm);
425     if (fe->clip) {
426         DeleteObject(fe->clip);
427         fe->clip = NULL;
428     }
429 }
430
431 const struct drawing_api win_drawing = {
432     win_draw_text,
433     win_draw_rect,
434     win_draw_line,
435     win_draw_polygon,
436     win_draw_circle,
437     win_draw_update,
438     win_clip,
439     win_unclip,
440     win_start_draw,
441     win_end_draw,
442     win_status_bar,
443     win_blitter_new,
444     win_blitter_free,
445     win_blitter_save,
446     win_blitter_load,
447     NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
448     NULL,                              /* line_width */
449 };
450
451 void deactivate_timer(frontend *fe)
452 {
453     if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
454     fe->timer = 0;
455 }
456
457 void activate_timer(frontend *fe)
458 {
459     if (!fe->timer) {
460         fe->timer = SetTimer(fe->hwnd, fe->timer, 20, NULL);
461         fe->timer_last_tickcount = GetTickCount();
462     }
463 }
464
465 /*
466  * Since this front end does not support printing (yet), we need
467  * this stub to satisfy the reference in midend_print_puzzle().
468  */
469 void document_add_puzzle(document *doc, const game *game, game_params *par,
470                          game_state *st, game_state *st2)
471 {
472 }
473
474 void write_clip(HWND hwnd, char *data)
475 {
476     HGLOBAL clipdata;
477     int len, i, j;
478     char *data2;
479     void *lock;
480
481     /*
482      * Windows expects CRLF in the clipboard, so we must convert
483      * any \n that has come out of the puzzle backend.
484      */
485     len = 0;
486     for (i = 0; data[i]; i++) {
487         if (data[i] == '\n')
488             len++;
489         len++;
490     }
491     data2 = snewn(len+1, char);
492     j = 0;
493     for (i = 0; data[i]; i++) {
494         if (data[i] == '\n')
495             data2[j++] = '\r';
496         data2[j++] = data[i];
497     }
498     assert(j == len);
499     data2[j] = '\0';
500
501     clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
502     if (!clipdata)
503         return;
504     lock = GlobalLock(clipdata);
505     if (!lock)
506         return;
507     memcpy(lock, data2, len);
508     ((unsigned char *) lock)[len] = 0;
509     GlobalUnlock(clipdata);
510
511     if (OpenClipboard(hwnd)) {
512         EmptyClipboard();
513         SetClipboardData(CF_TEXT, clipdata);
514         CloseClipboard();
515     } else
516         GlobalFree(clipdata);
517
518     sfree(data2);
519 }
520
521 /*
522  * See if we can find a help file.
523  */
524 static void find_help_file(frontend *fe)
525 {
526     char b[2048], *p, *q, *r;
527     FILE *fp;
528     if (!fe->help_path) {
529         GetModuleFileName(NULL, b, sizeof(b) - 1);
530         r = b;
531         p = strrchr(b, '\\');
532         if (p && p >= r) r = p+1;
533         q = strrchr(b, ':');
534         if (q && q >= r) r = q+1;
535         strcpy(r, HELP_FILE_NAME);
536         if ( (fp = fopen(b, "r")) != NULL) {
537             fe->help_path = dupstr(b);
538             fclose(fp);
539         } else
540             fe->help_path = NULL;
541         strcpy(r, HELP_CNT_NAME);
542         if ( (fp = fopen(b, "r")) != NULL) {
543             fe->help_has_contents = TRUE;
544             fclose(fp);
545         } else
546             fe->help_has_contents = FALSE;
547     }
548 }
549
550 static void check_window_size(frontend *fe, int *px, int *py)
551 {
552     RECT r;
553     int x, y, sy;
554
555     if (fe->statusbar) {
556         RECT sr;
557         GetWindowRect(fe->statusbar, &sr);
558         sy = sr.bottom - sr.top;
559     } else {
560         sy = 0;
561     }
562
563     /*
564      * See if we actually got the window size we wanted, and adjust
565      * the puzzle size if not.
566      */
567     GetClientRect(fe->hwnd, &r);
568     x = r.right - r.left;
569     y = r.bottom - r.top - sy;
570     midend_size(fe->me, &x, &y, FALSE);
571     if (x != r.right - r.left || y != r.bottom - r.top) {
572         /*
573          * Resize the window, now we know what size we _really_
574          * want it to be.
575          */
576         r.left = r.top = 0;
577         r.right = x;
578         r.bottom = y + sy;
579         AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
580                            (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED),
581                            TRUE, 0);
582         SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left, r.bottom - r.top,
583                      SWP_NOMOVE | SWP_NOZORDER);
584     }
585
586     if (fe->statusbar) {
587         GetClientRect(fe->hwnd, &r);
588         SetWindowPos(fe->statusbar, NULL, 0, r.bottom-r.top-sy, r.right-r.left,
589                      sy, SWP_NOZORDER);
590     }
591
592     *px = x;
593     *py = y;
594 }
595
596 static frontend *new_window(HINSTANCE inst, char *game_id, char **error)
597 {
598     frontend *fe;
599     int x, y;
600     RECT r;
601     HDC hdc;
602
603     fe = snew(frontend);
604
605     fe->me = midend_new(fe, &thegame, &win_drawing, fe);
606
607     if (game_id) {
608         *error = midend_game_id(fe->me, game_id);
609         if (*error) {
610             midend_free(fe->me);
611             sfree(fe);
612             return NULL;
613         }
614     }
615
616     fe->help_path = NULL;
617     find_help_file(fe);
618
619     fe->inst = inst;
620
621     fe->timer = 0;
622     fe->hwnd = NULL;
623
624     midend_new_game(fe->me);
625
626     fe->fonts = NULL;
627     fe->nfonts = fe->fontsize = 0;
628
629     fe->laststatus = NULL;
630
631     {
632         int i, ncolours;
633         float *colours;
634
635         colours = midend_colours(fe->me, &ncolours);
636
637         fe->colours = snewn(ncolours, COLORREF);
638         fe->brushes = snewn(ncolours, HBRUSH);
639         fe->pens = snewn(ncolours, HPEN);
640
641         for (i = 0; i < ncolours; i++) {
642             fe->colours[i] = RGB(255 * colours[i*3+0],
643                                  255 * colours[i*3+1],
644                                  255 * colours[i*3+2]);
645             fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
646             fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
647         }
648     }
649
650     x = y = INT_MAX;                   /* find puzzle's preferred size */
651     midend_size(fe->me, &x, &y, FALSE);
652
653     r.left = r.top = 0;
654     r.right = x;
655     r.bottom = y;
656     AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
657                        (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED),
658                        TRUE, 0);
659
660     fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
661                               WS_OVERLAPPEDWINDOW &~
662                               (WS_THICKFRAME | WS_MAXIMIZEBOX),
663                               CW_USEDEFAULT, CW_USEDEFAULT,
664                               r.right - r.left, r.bottom - r.top,
665                               NULL, NULL, inst, NULL);
666
667     if (midend_wants_statusbar(fe->me)) {
668         RECT sr;
669         fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
670                                        WS_CHILD | WS_VISIBLE,
671                                        0, 0, 0, 0, /* status bar does these */
672                                        fe->hwnd, NULL, inst, NULL);
673         /*
674          * Now resize the window to take account of the status bar.
675          */
676         GetWindowRect(fe->statusbar, &sr);
677         GetWindowRect(fe->hwnd, &r);
678         SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
679                      r.bottom - r.top + sr.bottom - sr.top,
680                      SWP_NOMOVE | SWP_NOZORDER);
681     } else {
682         fe->statusbar = NULL;
683     }
684
685     {
686         HMENU bar = CreateMenu();
687         HMENU menu = CreateMenu();
688
689         AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Game");
690         AppendMenu(menu, MF_ENABLED, IDM_NEW, "New");
691         AppendMenu(menu, MF_ENABLED, IDM_RESTART, "Restart");
692         AppendMenu(menu, MF_ENABLED, IDM_DESC, "Specific...");
693         AppendMenu(menu, MF_ENABLED, IDM_SEED, "Random Seed...");
694
695         if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
696             thegame.can_configure) {
697             HMENU sub = CreateMenu();
698             int i;
699
700             AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "Type");
701
702             fe->presets = snewn(fe->npresets, game_params *);
703
704             for (i = 0; i < fe->npresets; i++) {
705                 char *name;
706
707                 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
708
709                 /*
710                  * FIXME: we ought to go through and do something
711                  * with ampersands here.
712                  */
713
714                 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
715             }
716
717             if (thegame.can_configure) {
718                 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, "Custom...");
719             }
720         }
721
722         AppendMenu(menu, MF_SEPARATOR, 0, 0);
723         AppendMenu(menu, MF_ENABLED, IDM_LOAD, "Load");
724         AppendMenu(menu, MF_ENABLED, IDM_SAVE, "Save");
725         AppendMenu(menu, MF_SEPARATOR, 0, 0);
726         AppendMenu(menu, MF_ENABLED, IDM_UNDO, "Undo");
727         AppendMenu(menu, MF_ENABLED, IDM_REDO, "Redo");
728         if (thegame.can_format_as_text) {
729             AppendMenu(menu, MF_SEPARATOR, 0, 0);
730             AppendMenu(menu, MF_ENABLED, IDM_COPY, "Copy");
731         }
732         if (thegame.can_solve) {
733             AppendMenu(menu, MF_SEPARATOR, 0, 0);
734             AppendMenu(menu, MF_ENABLED, IDM_SOLVE, "Solve");
735         }
736         AppendMenu(menu, MF_SEPARATOR, 0, 0);
737         AppendMenu(menu, MF_ENABLED, IDM_QUIT, "Exit");
738         menu = CreateMenu();
739         AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Help");
740         AppendMenu(menu, MF_ENABLED, IDM_ABOUT, "About");
741         if (fe->help_path) {
742             AppendMenu(menu, MF_SEPARATOR, 0, 0);
743             AppendMenu(menu, MF_ENABLED, IDM_HELPC, "Contents");
744             if (thegame.winhelp_topic) {
745                 char *item;
746                 assert(thegame.name);
747                 item = snewn(9+strlen(thegame.name), char); /*ick*/
748                 sprintf(item, "Help on %s", thegame.name);
749                 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
750                 sfree(item);
751             }
752         }
753         SetMenu(fe->hwnd, bar);
754     }
755
756     check_window_size(fe, &x, &y);
757
758     hdc = GetDC(fe->hwnd);
759     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
760     ReleaseDC(fe->hwnd, hdc);
761
762     SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
763
764     ShowWindow(fe->hwnd, SW_NORMAL);
765     SetForegroundWindow(fe->hwnd);
766
767     midend_redraw(fe->me);
768
769     return fe;
770 }
771
772 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
773                                  WPARAM wParam, LPARAM lParam)
774 {
775     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
776
777     switch (msg) {
778       case WM_INITDIALOG:
779         return 0;
780
781       case WM_COMMAND:
782         if ((HIWORD(wParam) == BN_CLICKED ||
783              HIWORD(wParam) == BN_DOUBLECLICKED) &&
784             LOWORD(wParam) == IDOK)
785             fe->dlg_done = 1;
786         return 0;
787
788       case WM_CLOSE:
789         fe->dlg_done = 1;
790         return 0;
791     }
792
793     return 0;
794 }
795
796 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
797                                   WPARAM wParam, LPARAM lParam)
798 {
799     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
800     config_item *i;
801     struct cfg_aux *j;
802
803     switch (msg) {
804       case WM_INITDIALOG:
805         return 0;
806
807       case WM_COMMAND:
808         /*
809          * OK and Cancel are special cases.
810          */
811         if ((HIWORD(wParam) == BN_CLICKED ||
812              HIWORD(wParam) == BN_DOUBLECLICKED) &&
813             (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
814             if (LOWORD(wParam) == IDOK) {
815                 char *err = midend_set_config(fe->me, fe->cfg_which, fe->cfg);
816
817                 if (err) {
818                     MessageBox(hwnd, err, "Validation error",
819                                MB_ICONERROR | MB_OK);
820                 } else {
821                     fe->dlg_done = 2;
822                 }
823             } else {
824                 fe->dlg_done = 1;
825             }
826             return 0;
827         }
828
829         /*
830          * First find the control whose id this is.
831          */
832         for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
833             if (j->ctlid == LOWORD(wParam))
834                 break;
835         }
836         if (i->type == C_END)
837             return 0;                  /* not our problem */
838
839         if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
840             char buffer[4096];
841             GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
842             buffer[lenof(buffer)-1] = '\0';
843             sfree(i->sval);
844             i->sval = dupstr(buffer);
845         } else if (i->type == C_BOOLEAN && 
846                    (HIWORD(wParam) == BN_CLICKED ||
847                     HIWORD(wParam) == BN_DOUBLECLICKED)) {
848             i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
849         } else if (i->type == C_CHOICES &&
850                    HIWORD(wParam) == CBN_SELCHANGE) {
851             i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
852                                          CB_GETCURSEL, 0, 0);
853         }
854
855         return 0;
856
857       case WM_CLOSE:
858         fe->dlg_done = 1;
859         return 0;
860     }
861
862     return 0;
863 }
864
865 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
866             char *wclass, int wstyle,
867             int exstyle, const char *wtext, int wid)
868 {
869     HWND ret;
870     ret = CreateWindowEx(exstyle, wclass, wtext,
871                          wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
872                          fe->cfgbox, (HMENU) wid, fe->inst, NULL);
873     SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
874     return ret;
875 }
876
877 static void about(frontend *fe)
878 {
879     int i;
880     WNDCLASS wc;
881     MSG msg;
882     TEXTMETRIC tm;
883     HDC hdc;
884     HFONT oldfont;
885     SIZE size;
886     int gm, id;
887     int winwidth, winheight, y;
888     int height, width, maxwid;
889     const char *strings[16];
890     int lengths[16];
891     int nstrings = 0;
892     char titlebuf[512];
893
894     sprintf(titlebuf, "About %.250s", thegame.name);
895
896     strings[nstrings++] = thegame.name;
897     strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
898     strings[nstrings++] = ver;
899
900     wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
901     wc.lpfnWndProc = DefDlgProc;
902     wc.cbClsExtra = 0;
903     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
904     wc.hInstance = fe->inst;
905     wc.hIcon = NULL;
906     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
907     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
908     wc.lpszMenuName = NULL;
909     wc.lpszClassName = "GameAboutBox";
910     RegisterClass(&wc);
911
912     hdc = GetDC(fe->hwnd);
913     SetMapMode(hdc, MM_TEXT);
914
915     fe->dlg_done = FALSE;
916
917     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
918                              0, 0, 0, 0,
919                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
920                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
921                              DEFAULT_QUALITY,
922                              FF_SWISS,
923                              "MS Shell Dlg");
924
925     oldfont = SelectObject(hdc, fe->cfgfont);
926     if (GetTextMetrics(hdc, &tm)) {
927         height = tm.tmAscent + tm.tmDescent;
928         width = tm.tmAveCharWidth;
929     } else {
930         height = width = 30;
931     }
932
933     /*
934      * Figure out the layout of the About box by measuring the
935      * length of each piece of text.
936      */
937     maxwid = 0;
938     winheight = height/2;
939
940     for (i = 0; i < nstrings; i++) {
941         if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
942             lengths[i] = size.cx;
943         else
944             lengths[i] = 0;            /* *shrug* */
945         if (maxwid < lengths[i])
946             maxwid = lengths[i];
947         winheight += height * 3 / 2 + (height / 2);
948     }
949
950     winheight += height + height * 7 / 4;      /* OK button */
951     winwidth = maxwid + 4*width;
952
953     SelectObject(hdc, oldfont);
954     ReleaseDC(fe->hwnd, hdc);
955
956     /*
957      * Create the dialog, now that we know its size.
958      */
959     {
960         RECT r, r2;
961
962         r.left = r.top = 0;
963         r.right = winwidth;
964         r.bottom = winheight;
965
966         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
967                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
968                                 WS_CAPTION | WS_SYSMENU*/) &~
969                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
970                            FALSE, 0);
971
972         /*
973          * Centre the dialog on its parent window.
974          */
975         r.right -= r.left;
976         r.bottom -= r.top;
977         GetWindowRect(fe->hwnd, &r2);
978         r.left = (r2.left + r2.right - r.right) / 2;
979         r.top = (r2.top + r2.bottom - r.bottom) / 2;
980         r.right += r.left;
981         r.bottom += r.top;
982
983         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
984                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
985                                     WS_CAPTION | WS_SYSMENU,
986                                     r.left, r.top,
987                                     r.right-r.left, r.bottom-r.top,
988                                     fe->hwnd, NULL, fe->inst, NULL);
989     }
990
991     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
992
993     SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
994     SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
995
996     id = 1000;
997     y = height/2;
998     for (i = 0; i < nstrings; i++) {
999         int border = width*2 + (maxwid - lengths[i]) / 2;
1000         mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
1001                "Static", 0, 0, strings[i], id++);
1002         y += height*3/2;
1003
1004         assert(y < winheight);
1005         y += height/2;
1006     }
1007
1008     y += height/2;                     /* extra space before OK */
1009     mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
1010            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1011            "OK", IDOK);
1012
1013     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1014
1015     EnableWindow(fe->hwnd, FALSE);
1016     ShowWindow(fe->cfgbox, SW_NORMAL);
1017     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1018         if (!IsDialogMessage(fe->cfgbox, &msg))
1019             DispatchMessage(&msg);
1020         if (fe->dlg_done)
1021             break;
1022     }
1023     EnableWindow(fe->hwnd, TRUE);
1024     SetForegroundWindow(fe->hwnd);
1025     DestroyWindow(fe->cfgbox);
1026     DeleteObject(fe->cfgfont);
1027 }
1028
1029 static int get_config(frontend *fe, int which)
1030 {
1031     config_item *i;
1032     struct cfg_aux *j;
1033     char *title;
1034     WNDCLASS wc;
1035     MSG msg;
1036     TEXTMETRIC tm;
1037     HDC hdc;
1038     HFONT oldfont;
1039     SIZE size;
1040     HWND ctl;
1041     int gm, id, nctrls;
1042     int winwidth, winheight, col1l, col1r, col2l, col2r, y;
1043     int height, width, maxlabel, maxcheckbox;
1044
1045     wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1046     wc.lpfnWndProc = DefDlgProc;
1047     wc.cbClsExtra = 0;
1048     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1049     wc.hInstance = fe->inst;
1050     wc.hIcon = NULL;
1051     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1052     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1053     wc.lpszMenuName = NULL;
1054     wc.lpszClassName = "GameConfigBox";
1055     RegisterClass(&wc);
1056
1057     hdc = GetDC(fe->hwnd);
1058     SetMapMode(hdc, MM_TEXT);
1059
1060     fe->dlg_done = FALSE;
1061
1062     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1063                              0, 0, 0, 0,
1064                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1065                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1066                              DEFAULT_QUALITY,
1067                              FF_SWISS,
1068                              "MS Shell Dlg");
1069
1070     oldfont = SelectObject(hdc, fe->cfgfont);
1071     if (GetTextMetrics(hdc, &tm)) {
1072         height = tm.tmAscent + tm.tmDescent;
1073         width = tm.tmAveCharWidth;
1074     } else {
1075         height = width = 30;
1076     }
1077
1078     fe->cfg = midend_get_config(fe->me, which, &title);
1079     fe->cfg_which = which;
1080
1081     /*
1082      * Figure out the layout of the config box by measuring the
1083      * length of each piece of text.
1084      */
1085     maxlabel = maxcheckbox = 0;
1086     winheight = height/2;
1087
1088     for (i = fe->cfg; i->type != C_END; i++) {
1089         switch (i->type) {
1090           case C_STRING:
1091           case C_CHOICES:
1092             /*
1093              * Both these control types have a label filling only
1094              * the left-hand column of the box.
1095              */
1096             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1097                 maxlabel < size.cx)
1098                 maxlabel = size.cx;
1099             winheight += height * 3 / 2 + (height / 2);
1100             break;
1101
1102           case C_BOOLEAN:
1103             /*
1104              * Checkboxes take up the whole of the box width.
1105              */
1106             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1107                 maxcheckbox < size.cx)
1108                 maxcheckbox = size.cx;
1109             winheight += height + (height / 2);
1110             break;
1111         }
1112     }
1113
1114     winheight += height + height * 7 / 4;      /* OK / Cancel buttons */
1115
1116     col1l = 2*width;
1117     col1r = col1l + maxlabel;
1118     col2l = col1r + 2*width;
1119     col2r = col2l + 30*width;
1120     if (col2r < col1l+2*height+maxcheckbox)
1121         col2r = col1l+2*height+maxcheckbox;
1122     winwidth = col2r + 2*width;
1123
1124     SelectObject(hdc, oldfont);
1125     ReleaseDC(fe->hwnd, hdc);
1126
1127     /*
1128      * Create the dialog, now that we know its size.
1129      */
1130     {
1131         RECT r, r2;
1132
1133         r.left = r.top = 0;
1134         r.right = winwidth;
1135         r.bottom = winheight;
1136
1137         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1138                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1139                                 WS_CAPTION | WS_SYSMENU*/) &~
1140                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1141                            FALSE, 0);
1142
1143         /*
1144          * Centre the dialog on its parent window.
1145          */
1146         r.right -= r.left;
1147         r.bottom -= r.top;
1148         GetWindowRect(fe->hwnd, &r2);
1149         r.left = (r2.left + r2.right - r.right) / 2;
1150         r.top = (r2.top + r2.bottom - r.bottom) / 2;
1151         r.right += r.left;
1152         r.bottom += r.top;
1153
1154         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
1155                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1156                                     WS_CAPTION | WS_SYSMENU,
1157                                     r.left, r.top,
1158                                     r.right-r.left, r.bottom-r.top,
1159                                     fe->hwnd, NULL, fe->inst, NULL);
1160         sfree(title);
1161     }
1162
1163     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1164
1165     SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1166     SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
1167
1168     /*
1169      * Count the controls so we can allocate cfgaux.
1170      */
1171     for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
1172         nctrls++;
1173     fe->cfgaux = snewn(nctrls, struct cfg_aux);
1174
1175     id = 1000;
1176     y = height/2;
1177     for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1178         switch (i->type) {
1179           case C_STRING:
1180             /*
1181              * Edit box with a label beside it.
1182              */
1183             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1184                    "Static", 0, 0, i->name, id++);
1185             ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
1186                          "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
1187                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1188             SetWindowText(ctl, i->sval);
1189             y += height*3/2;
1190             break;
1191
1192           case C_BOOLEAN:
1193             /*
1194              * Simple checkbox.
1195              */
1196             mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
1197                    BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
1198                    0, i->name, (j->ctlid = id++));
1199             CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
1200             y += height;
1201             break;
1202
1203           case C_CHOICES:
1204             /*
1205              * Drop-down list with a label beside it.
1206              */
1207             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1208                    "STATIC", 0, 0, i->name, id++);
1209             ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
1210                          "COMBOBOX", WS_TABSTOP |
1211                          CBS_DROPDOWNLIST | CBS_HASSTRINGS,
1212                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1213             {
1214                 char c, *p, *q, *str;
1215
1216                 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
1217                 p = i->sval;
1218                 c = *p++;
1219                 while (*p) {
1220                     q = p;
1221                     while (*q && *q != c) q++;
1222                     str = snewn(q-p+1, char);
1223                     strncpy(str, p, q-p);
1224                     str[q-p] = '\0';
1225                     SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
1226                     sfree(str);
1227                     if (*q) q++;
1228                     p = q;
1229                 }
1230             }
1231
1232             SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
1233
1234             y += height*3/2;
1235             break;
1236         }
1237
1238         assert(y < winheight);
1239         y += height/2;
1240     }
1241
1242     y += height/2;                     /* extra space before OK and Cancel */
1243     mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
1244            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1245            "OK", IDOK);
1246     mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
1247            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP, 0, "Cancel", IDCANCEL);
1248
1249     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1250
1251     EnableWindow(fe->hwnd, FALSE);
1252     ShowWindow(fe->cfgbox, SW_NORMAL);
1253     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1254         if (!IsDialogMessage(fe->cfgbox, &msg))
1255             DispatchMessage(&msg);
1256         if (fe->dlg_done)
1257             break;
1258     }
1259     EnableWindow(fe->hwnd, TRUE);
1260     SetForegroundWindow(fe->hwnd);
1261     DestroyWindow(fe->cfgbox);
1262     DeleteObject(fe->cfgfont);
1263
1264     free_cfg(fe->cfg);
1265     sfree(fe->cfgaux);
1266
1267     return (fe->dlg_done == 2);
1268 }
1269
1270 static void new_game_size(frontend *fe)
1271 {
1272     RECT r, sr;
1273     HDC hdc;
1274     int x, y;
1275
1276     x = y = INT_MAX;
1277     midend_size(fe->me, &x, &y, FALSE);
1278
1279     r.left = r.top = 0;
1280     r.right = x;
1281     r.bottom = y;
1282     AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
1283                        (WS_THICKFRAME | WS_MAXIMIZEBOX |
1284                         WS_OVERLAPPED),
1285                        TRUE, 0);
1286
1287     if (fe->statusbar != NULL) {
1288         GetWindowRect(fe->statusbar, &sr);
1289     } else {
1290         sr.left = sr.right = sr.top = sr.bottom = 0;
1291     }
1292     SetWindowPos(fe->hwnd, NULL, 0, 0,
1293                  r.right - r.left,
1294                  r.bottom - r.top + sr.bottom - sr.top,
1295                  SWP_NOMOVE | SWP_NOZORDER);
1296
1297     check_window_size(fe, &x, &y);
1298
1299     if (fe->statusbar != NULL)
1300         SetWindowPos(fe->statusbar, NULL, 0, y, x,
1301                      sr.bottom - sr.top, SWP_NOZORDER);
1302
1303     DeleteObject(fe->bitmap);
1304
1305     hdc = GetDC(fe->hwnd);
1306     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
1307     ReleaseDC(fe->hwnd, hdc);
1308
1309     midend_redraw(fe->me);
1310 }
1311
1312 static void new_game_type(frontend *fe)
1313 {
1314     midend_new_game(fe->me);
1315     new_game_size(fe);
1316 }
1317
1318 static int is_alt_pressed(void)
1319 {
1320     BYTE keystate[256];
1321     int r = GetKeyboardState(keystate);
1322     if (!r)
1323         return FALSE;
1324     if (keystate[VK_MENU] & 0x80)
1325         return TRUE;
1326     if (keystate[VK_RMENU] & 0x80)
1327         return TRUE;
1328     return FALSE;
1329 }
1330
1331 static void savefile_write(void *wctx, void *buf, int len)
1332 {
1333     FILE *fp = (FILE *)wctx;
1334     fwrite(buf, 1, len, fp);
1335 }
1336
1337 static int savefile_read(void *wctx, void *buf, int len)
1338 {
1339     FILE *fp = (FILE *)wctx;
1340     int ret;
1341
1342     ret = fread(buf, 1, len, fp);
1343     return (ret == len);
1344 }
1345
1346 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1347                                 WPARAM wParam, LPARAM lParam)
1348 {
1349     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1350     int cmd;
1351
1352     switch (message) {
1353       case WM_CLOSE:
1354         DestroyWindow(hwnd);
1355         return 0;
1356       case WM_COMMAND:
1357         cmd = wParam & ~0xF;           /* low 4 bits reserved to Windows */
1358         switch (cmd) {
1359           case IDM_NEW:
1360             if (!midend_process_key(fe->me, 0, 0, 'n'))
1361                 PostQuitMessage(0);
1362             break;
1363           case IDM_RESTART:
1364             midend_restart_game(fe->me);
1365             break;
1366           case IDM_UNDO:
1367             if (!midend_process_key(fe->me, 0, 0, 'u'))
1368                 PostQuitMessage(0);
1369             break;
1370           case IDM_REDO:
1371             if (!midend_process_key(fe->me, 0, 0, '\x12'))
1372                 PostQuitMessage(0);
1373             break;
1374           case IDM_COPY:
1375             {
1376                 char *text = midend_text_format(fe->me);
1377                 if (text)
1378                     write_clip(hwnd, text);
1379                 else
1380                     MessageBeep(MB_ICONWARNING);
1381                 sfree(text);
1382             }
1383             break;
1384           case IDM_SOLVE:
1385             {
1386                 char *msg = midend_solve(fe->me);
1387                 if (msg)
1388                     MessageBox(hwnd, msg, "Unable to solve",
1389                                MB_ICONERROR | MB_OK);
1390             }
1391             break;
1392           case IDM_QUIT:
1393             if (!midend_process_key(fe->me, 0, 0, 'q'))
1394                 PostQuitMessage(0);
1395             break;
1396           case IDM_CONFIG:
1397             if (get_config(fe, CFG_SETTINGS))
1398                 new_game_type(fe);
1399             break;
1400           case IDM_SEED:
1401             if (get_config(fe, CFG_SEED))
1402                 new_game_type(fe);
1403             break;
1404           case IDM_DESC:
1405             if (get_config(fe, CFG_DESC))
1406                 new_game_type(fe);
1407             break;
1408           case IDM_ABOUT:
1409             about(fe);
1410             break;
1411           case IDM_LOAD:
1412           case IDM_SAVE:
1413             {
1414                 OPENFILENAME of;
1415                 char filename[FILENAME_MAX];
1416                 int ret;
1417
1418                 memset(&of, 0, sizeof(of));
1419                 of.hwndOwner = hwnd;
1420                 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
1421                 of.lpstrCustomFilter = NULL;
1422                 of.nFilterIndex = 1;
1423                 of.lpstrFile = filename;
1424                 filename[0] = '\0';
1425                 of.nMaxFile = lenof(filename);
1426                 of.lpstrFileTitle = NULL;
1427                 of.lpstrTitle = (cmd == IDM_SAVE ?
1428                                  "Enter name of game file to save" :
1429                                  "Enter name of saved game file to load");
1430                 of.Flags = 0;
1431 #ifdef OPENFILENAME_SIZE_VERSION_400
1432                 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
1433 #else
1434                 of.lStructSize = sizeof(of);
1435 #endif
1436                 of.lpstrInitialDir = NULL;
1437
1438                 if (cmd == IDM_SAVE)
1439                     ret = GetSaveFileName(&of);
1440                 else
1441                     ret = GetOpenFileName(&of);
1442
1443                 if (ret) {
1444                     if (cmd == IDM_SAVE) {
1445                         FILE *fp;
1446
1447                         if ((fp = fopen(filename, "r")) != NULL) {
1448                             char buf[256 + FILENAME_MAX];
1449                             fclose(fp);
1450                             /* file exists */
1451
1452                             sprintf(buf, "Are you sure you want to overwrite"
1453                                     " the file \"%.*s\"?",
1454                                     FILENAME_MAX, filename);
1455                             if (MessageBox(hwnd, buf, "Question",
1456                                            MB_YESNO | MB_ICONQUESTION)
1457                                 != IDYES)
1458                                 break;
1459                         }
1460
1461                         fp = fopen(filename, "w");
1462
1463                         if (!fp) {
1464                             MessageBox(hwnd, "Unable to open save file",
1465                                        "Error", MB_ICONERROR | MB_OK);
1466                             break;
1467                         }
1468
1469                         midend_serialise(fe->me, savefile_write, fp);
1470
1471                         fclose(fp);
1472                     } else {
1473                         FILE *fp = fopen(filename, "r");
1474                         char *err;
1475
1476                         if (!fp) {
1477                             MessageBox(hwnd, "Unable to open saved game file",
1478                                        "Error", MB_ICONERROR | MB_OK);
1479                             break;
1480                         }
1481
1482                         err = midend_deserialise(fe->me, savefile_read, fp);
1483
1484                         fclose(fp);
1485
1486                         if (err) {
1487                             MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
1488                             break;
1489                         }
1490
1491                         new_game_size(fe);
1492                     }
1493                 }
1494             }
1495
1496             break;
1497           case IDM_HELPC:
1498             assert(fe->help_path);
1499             WinHelp(hwnd, fe->help_path,
1500                     fe->help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
1501             break;
1502           case IDM_GAMEHELP:
1503             assert(fe->help_path);
1504             assert(thegame.winhelp_topic);
1505             {
1506                 char *cmd = snewn(10+strlen(thegame.winhelp_topic), char);
1507                 sprintf(cmd, "JI(`',`%s')", thegame.winhelp_topic);
1508                 WinHelp(hwnd, fe->help_path, HELP_COMMAND, (DWORD)cmd);
1509                 sfree(cmd);
1510             }
1511             break;
1512           default:
1513             {
1514                 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
1515
1516                 if (p >= 0 && p < fe->npresets) {
1517                     midend_set_params(fe->me, fe->presets[p]);
1518                     new_game_type(fe);
1519                 }
1520             }
1521             break;
1522         }
1523         break;
1524       case WM_DESTROY:
1525         PostQuitMessage(0);
1526         return 0;
1527       case WM_PAINT:
1528         {
1529             PAINTSTRUCT p;
1530             HDC hdc, hdc2;
1531             HBITMAP prevbm;
1532
1533             hdc = BeginPaint(hwnd, &p);
1534             hdc2 = CreateCompatibleDC(hdc);
1535             prevbm = SelectObject(hdc2, fe->bitmap);
1536             BitBlt(hdc,
1537                    p.rcPaint.left, p.rcPaint.top,
1538                    p.rcPaint.right - p.rcPaint.left,
1539                    p.rcPaint.bottom - p.rcPaint.top,
1540                    hdc2,
1541                    p.rcPaint.left, p.rcPaint.top,
1542                    SRCCOPY);
1543             SelectObject(hdc2, prevbm);
1544             DeleteDC(hdc2);
1545             EndPaint(hwnd, &p);
1546         }
1547         return 0;
1548       case WM_KEYDOWN:
1549         {
1550             int key = -1;
1551             BYTE keystate[256];
1552             int r = GetKeyboardState(keystate);
1553             int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
1554             int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
1555
1556             switch (wParam) {
1557               case VK_LEFT:
1558                 if (!(lParam & 0x01000000))
1559                     key = MOD_NUM_KEYPAD | '4';
1560                 else
1561                     key = shift | ctrl | CURSOR_LEFT;
1562                 break;
1563               case VK_RIGHT:
1564                 if (!(lParam & 0x01000000))
1565                     key = MOD_NUM_KEYPAD | '6';
1566                 else
1567                     key = shift | ctrl | CURSOR_RIGHT;
1568                 break;
1569               case VK_UP:
1570                 if (!(lParam & 0x01000000))
1571                     key = MOD_NUM_KEYPAD | '8';
1572                 else
1573                     key = shift | ctrl | CURSOR_UP;
1574                 break;
1575               case VK_DOWN:
1576                 if (!(lParam & 0x01000000))
1577                     key = MOD_NUM_KEYPAD | '2';
1578                 else
1579                     key = shift | ctrl | CURSOR_DOWN;
1580                 break;
1581                 /*
1582                  * Diagonal keys on the numeric keypad.
1583                  */
1584               case VK_PRIOR:
1585                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
1586                 break;
1587               case VK_NEXT:
1588                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
1589                 break;
1590               case VK_HOME:
1591                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
1592                 break;
1593               case VK_END:
1594                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
1595                 break;
1596               case VK_INSERT:
1597                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
1598                 break;
1599               case VK_CLEAR:
1600                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
1601                 break;
1602                 /*
1603                  * Numeric keypad keys with Num Lock on.
1604                  */
1605               case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
1606               case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
1607               case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
1608               case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
1609               case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
1610               case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
1611               case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
1612               case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
1613               case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
1614               case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
1615             }
1616
1617             if (key != -1) {
1618                 if (!midend_process_key(fe->me, 0, 0, key))
1619                     PostQuitMessage(0);
1620             } else {
1621                 MSG m;
1622                 m.hwnd = hwnd;
1623                 m.message = WM_KEYDOWN;
1624                 m.wParam = wParam;
1625                 m.lParam = lParam & 0xdfff;
1626                 TranslateMessage(&m);
1627             }
1628         }
1629         break;
1630       case WM_LBUTTONDOWN:
1631       case WM_RBUTTONDOWN:
1632       case WM_MBUTTONDOWN:
1633         {
1634             int button;
1635
1636             /*
1637              * Shift-clicks count as middle-clicks, since otherwise
1638              * two-button Windows users won't have any kind of
1639              * middle click to use.
1640              */
1641             if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
1642                 button = MIDDLE_BUTTON;
1643             else if (message == WM_RBUTTONDOWN || is_alt_pressed())
1644                 button = RIGHT_BUTTON;
1645             else
1646                 button = LEFT_BUTTON;
1647
1648             if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1649                                     (signed short)HIWORD(lParam), button))
1650                 PostQuitMessage(0);
1651
1652             SetCapture(hwnd);
1653         }
1654         break;
1655       case WM_LBUTTONUP:
1656       case WM_RBUTTONUP:
1657       case WM_MBUTTONUP:
1658         {
1659             int button;
1660
1661             /*
1662              * Shift-clicks count as middle-clicks, since otherwise
1663              * two-button Windows users won't have any kind of
1664              * middle click to use.
1665              */
1666             if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
1667                 button = MIDDLE_RELEASE;
1668             else if (message == WM_RBUTTONUP || is_alt_pressed())
1669                 button = RIGHT_RELEASE;
1670             else
1671                 button = LEFT_RELEASE;
1672
1673             if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1674                                     (signed short)HIWORD(lParam), button))
1675                 PostQuitMessage(0);
1676
1677             ReleaseCapture();
1678         }
1679         break;
1680       case WM_MOUSEMOVE:
1681         {
1682             int button;
1683
1684             if (wParam & (MK_MBUTTON | MK_SHIFT))
1685                 button = MIDDLE_DRAG;
1686             else if (wParam & MK_RBUTTON || is_alt_pressed())
1687                 button = RIGHT_DRAG;
1688             else
1689                 button = LEFT_DRAG;
1690             
1691             if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
1692                                     (signed short)HIWORD(lParam), button))
1693                 PostQuitMessage(0);
1694         }
1695         break;
1696       case WM_CHAR:
1697         if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
1698             PostQuitMessage(0);
1699         return 0;
1700       case WM_TIMER:
1701         if (fe->timer) {
1702             DWORD now = GetTickCount();
1703             float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
1704             midend_timer(fe->me, elapsed);
1705             fe->timer_last_tickcount = now;
1706         }
1707         return 0;
1708     }
1709
1710     return DefWindowProc(hwnd, message, wParam, lParam);
1711 }
1712
1713 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
1714 {
1715     MSG msg;
1716     char *error;
1717
1718     InitCommonControls();
1719
1720     if (!prev) {
1721         WNDCLASS wndclass;
1722
1723         wndclass.style = 0;
1724         wndclass.lpfnWndProc = WndProc;
1725         wndclass.cbClsExtra = 0;
1726         wndclass.cbWndExtra = 0;
1727         wndclass.hInstance = inst;
1728         wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
1729         wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
1730         wndclass.hbrBackground = NULL;
1731         wndclass.lpszMenuName = NULL;
1732         wndclass.lpszClassName = thegame.name;
1733
1734         RegisterClass(&wndclass);
1735     }
1736
1737     while (*cmdline && isspace((unsigned char)*cmdline))
1738         cmdline++;
1739
1740     if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
1741         char buf[128];
1742         sprintf(buf, "%.100s Error", thegame.name);
1743         MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
1744         return 1;
1745     }
1746
1747     while (GetMessage(&msg, NULL, 0, 0)) {
1748         DispatchMessage(&msg);
1749     }
1750
1751     return msg.wParam;
1752 }