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