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