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