chiark / gitweb /
Ben Hutchings's patch to add display of key accelerators in the Game
[sgt-puzzles.git] / windows.c
1 /*
2  * windows.c: Windows front end for my puzzle collection.
3  */
4
5 #include <windows.h>
6 #include <commctrl.h>
7
8 #include <stdio.h>
9 #include <assert.h>
10 #include <ctype.h>
11 #include <stdarg.h>
12 #include <stdlib.h>
13 #include <limits.h>
14 #include <time.h>
15
16 #include "puzzles.h"
17
18 #define IDM_NEW       0x0010
19 #define IDM_RESTART   0x0020
20 #define IDM_UNDO      0x0030
21 #define IDM_REDO      0x0040
22 #define IDM_COPY      0x0050
23 #define IDM_SOLVE     0x0060
24 #define IDM_QUIT      0x0070
25 #define IDM_CONFIG    0x0080
26 #define IDM_DESC      0x0090
27 #define IDM_SEED      0x00A0
28 #define IDM_HELPC     0x00B0
29 #define IDM_GAMEHELP  0x00C0
30 #define IDM_ABOUT     0x00D0
31 #define IDM_SAVE      0x00E0
32 #define IDM_LOAD      0x00F0
33 #define IDM_PRINT     0x0100
34 #define IDM_PRESETS   0x0110
35
36 #define HELP_FILE_NAME  "puzzles.hlp"
37 #define HELP_CNT_NAME   "puzzles.cnt"
38
39 #ifdef DEBUGGING
40 static FILE *debug_fp = NULL;
41 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
42 static int debug_got_console = 0;
43
44 void dputs(char *buf)
45 {
46     DWORD dw;
47
48     if (!debug_got_console) {
49         if (AllocConsole()) {
50             debug_got_console = 1;
51             debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
52         }
53     }
54     if (!debug_fp) {
55         debug_fp = fopen("debug.log", "w");
56     }
57
58     if (debug_hdl != INVALID_HANDLE_VALUE) {
59         WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
60     }
61     fputs(buf, debug_fp);
62     fflush(debug_fp);
63 }
64
65 void debug_printf(char *fmt, ...)
66 {
67     char buf[4096];
68     va_list ap;
69
70     va_start(ap, fmt);
71     vsprintf(buf, fmt, ap);
72     dputs(buf);
73     va_end(ap);
74 }
75 #endif
76
77 #define WINFLAGS (WS_OVERLAPPEDWINDOW &~ \
78                       (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED))
79
80 static void new_game_size(frontend *fe);
81
82 struct font {
83     HFONT font;
84     int type;
85     int size;
86 };
87
88 struct cfg_aux {
89     int ctlid;
90 };
91
92 struct blitter {
93     HBITMAP bitmap;
94     frontend *fe;
95     int x, y, w, h;
96 };
97
98 enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
99
100 struct frontend {
101     midend *me;
102     HWND hwnd, statusbar, cfgbox;
103     HINSTANCE inst;
104     HBITMAP bitmap, prevbm;
105     HDC hdc;
106     COLORREF *colours;
107     HBRUSH *brushes;
108     HPEN *pens;
109     HRGN clip;
110     UINT timer;
111     DWORD timer_last_tickcount;
112     int npresets;
113     game_params **presets;
114     struct font *fonts;
115     int nfonts, fontsize;
116     config_item *cfg;
117     struct cfg_aux *cfgaux;
118     int cfg_which, dlg_done;
119     HFONT cfgfont;
120     HBRUSH oldbr;
121     HPEN oldpen;
122     char *help_path;
123     int help_has_contents;
124     enum { DRAWING, PRINTING, NOTHING } drawstatus;
125     DOCINFO di;
126     int printcount, printw, printh, printsolns, printcurr, printcolour;
127     float printscale;
128     int printoffsetx, printoffsety;
129     float printpixelscale;
130     int fontstart;
131     int linewidth;
132     drawing *dr;
133 };
134
135 void fatal(char *fmt, ...)
136 {
137     char buf[2048];
138     va_list ap;
139
140     va_start(ap, fmt);
141     vsprintf(buf, fmt, ap);
142     va_end(ap);
143
144     MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
145
146     exit(1);
147 }
148
149 char *geterrstr(void)
150 {
151     LPVOID lpMsgBuf;
152     DWORD dw = GetLastError();
153     char *ret;
154
155     FormatMessage(
156         FORMAT_MESSAGE_ALLOCATE_BUFFER | 
157         FORMAT_MESSAGE_FROM_SYSTEM,
158         NULL,
159         dw,
160         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
161         (LPTSTR) &lpMsgBuf,
162         0, NULL );
163
164     ret = dupstr(lpMsgBuf);
165
166     LocalFree(lpMsgBuf);
167
168     return ret;
169 }
170
171 void get_random_seed(void **randseed, int *randseedsize)
172 {
173     time_t *tp = snew(time_t);
174     time(tp);
175     *randseed = (void *)tp;
176     *randseedsize = sizeof(time_t);
177 }
178
179 static void win_status_bar(void *handle, char *text)
180 {
181     frontend *fe = (frontend *)handle;
182
183     SetWindowText(fe->statusbar, text);
184 }
185
186 static blitter *win_blitter_new(void *handle, int w, int h)
187 {
188     blitter *bl = snew(blitter);
189
190     memset(bl, 0, sizeof(blitter));
191     bl->w = w;
192     bl->h = h;
193     bl->bitmap = 0;
194
195     return bl;
196 }
197
198 static void win_blitter_free(void *handle, blitter *bl)
199 {
200     if (bl->bitmap) DeleteObject(bl->bitmap);
201     sfree(bl);
202 }
203
204 static void blitter_mkbitmap(frontend *fe, blitter *bl)
205 {
206     HDC hdc = GetDC(fe->hwnd);
207     bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
208     ReleaseDC(fe->hwnd, hdc);
209 }
210
211 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
212
213 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
214 {
215     frontend *fe = (frontend *)handle;
216     HDC hdc_win, hdc_blit;
217     HBITMAP prev_blit;
218
219     assert(fe->drawstatus == DRAWING);
220
221     if (!bl->bitmap) blitter_mkbitmap(fe, bl);
222
223     bl->x = x; bl->y = y;
224
225     hdc_win = GetDC(fe->hwnd);
226     hdc_blit = CreateCompatibleDC(hdc_win);
227     if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
228
229     prev_blit = SelectObject(hdc_blit, bl->bitmap);
230     if (prev_blit == NULL || prev_blit == HGDI_ERROR)
231         fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
232
233     if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
234                 fe->hdc, x, y, SRCCOPY))
235         fatal("BitBlt failed: 0x%x", GetLastError());
236
237     SelectObject(hdc_blit, prev_blit);
238     DeleteDC(hdc_blit);
239     ReleaseDC(fe->hwnd, hdc_win);
240 }
241
242 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
243 {
244     frontend *fe = (frontend *)handle;
245     HDC hdc_win, hdc_blit;
246     HBITMAP prev_blit;
247
248     assert(fe->drawstatus == DRAWING);
249
250     assert(bl->bitmap); /* we should always have saved before loading */
251
252     if (x == BLITTER_FROMSAVED) x = bl->x;
253     if (y == BLITTER_FROMSAVED) y = bl->y;
254
255     hdc_win = GetDC(fe->hwnd);
256     hdc_blit = CreateCompatibleDC(hdc_win);
257
258     prev_blit = SelectObject(hdc_blit, bl->bitmap);
259
260     BitBlt(fe->hdc, x, y, bl->w, bl->h,
261            hdc_blit, 0, 0, SRCCOPY);
262
263     SelectObject(hdc_blit, prev_blit);
264     DeleteDC(hdc_blit);
265     ReleaseDC(fe->hwnd, hdc_win);
266 }
267
268 void frontend_default_colour(frontend *fe, float *output)
269 {
270     DWORD c = GetSysColor(COLOR_MENU); /* ick */
271
272     output[0] = (float)(GetRValue(c) / 255.0);
273     output[1] = (float)(GetGValue(c) / 255.0);
274     output[2] = (float)(GetBValue(c) / 255.0);
275 }
276
277 static POINT win_transform_point(frontend *fe, int x, int y)
278 {
279     POINT ret;
280
281     assert(fe->drawstatus != NOTHING);
282
283     if (fe->drawstatus == PRINTING) {
284         ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
285         ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
286     } else {
287         ret.x = x;
288         ret.y = y;
289     }
290
291     return ret;
292 }
293
294 static void win_text_colour(frontend *fe, int colour)
295 {
296     assert(fe->drawstatus != NOTHING);
297
298     if (fe->drawstatus == PRINTING) {
299         int hatch;
300         float r, g, b;
301         print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
302         if (fe->printcolour)
303             SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
304         else
305             SetTextColor(fe->hdc,
306                          hatch == HATCH_CLEAR ? RGB(255,255,255) : RGB(0,0,0));
307     } else {
308         SetTextColor(fe->hdc, fe->colours[colour]);
309     }
310 }
311
312 static void win_set_brush(frontend *fe, int colour)
313 {
314     HBRUSH br;
315     assert(fe->drawstatus != NOTHING);
316
317     if (fe->drawstatus == PRINTING) {
318         int hatch;
319         float r, g, b;
320         print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
321
322         if (fe->printcolour)
323             br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
324         else if (hatch == HATCH_SOLID)
325             br = CreateSolidBrush(RGB(0,0,0));
326         else if (hatch == HATCH_CLEAR)
327             br = CreateSolidBrush(RGB(255,255,255));
328         else
329             br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
330                                   hatch == HATCH_SLASH ? HS_BDIAGONAL :
331                                   hatch == HATCH_HORIZ ? HS_HORIZONTAL :
332                                   hatch == HATCH_VERT ? HS_VERTICAL :
333                                   hatch == HATCH_PLUS ? HS_CROSS :
334                                   /* hatch == HATCH_X ? */ HS_DIAGCROSS,
335                                   RGB(0,0,0));
336     } else {
337         br = fe->brushes[colour];
338     }
339     fe->oldbr = SelectObject(fe->hdc, br);
340 }
341
342 static void win_reset_brush(frontend *fe)
343 {
344     HBRUSH br;
345
346     assert(fe->drawstatus != NOTHING);
347
348     br = SelectObject(fe->hdc, fe->oldbr);
349     if (fe->drawstatus == PRINTING)
350         DeleteObject(br);
351 }
352
353 static void win_set_pen(frontend *fe, int colour, int thin)
354 {
355     HPEN pen;
356     assert(fe->drawstatus != NOTHING);
357
358     if (fe->drawstatus == PRINTING) {
359         int hatch;
360         float r, g, b;
361         int width = thin ? 0 : fe->linewidth;
362
363         print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
364         if (fe->printcolour)
365             pen = CreatePen(PS_SOLID, width,
366                             RGB(r * 255, g * 255, b * 255));
367         else if (hatch == HATCH_SOLID)
368             pen = CreatePen(PS_SOLID, width, RGB(0, 0, 0));
369         else if (hatch == HATCH_CLEAR)
370             pen = CreatePen(PS_SOLID, width, RGB(255,255,255));
371         else {
372             assert(!"This shouldn't happen");
373             pen = CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
374         }
375     } else {
376         pen = fe->pens[colour];
377     }
378     fe->oldpen = SelectObject(fe->hdc, pen);
379 }
380
381 static void win_reset_pen(frontend *fe)
382 {
383     HPEN pen;
384
385     assert(fe->drawstatus != NOTHING);
386
387     pen = SelectObject(fe->hdc, fe->oldpen);
388     if (fe->drawstatus == PRINTING)
389         DeleteObject(pen);
390 }
391
392 static void win_clip(void *handle, int x, int y, int w, int h)
393 {
394     frontend *fe = (frontend *)handle;
395     POINT p, q;
396
397     if (fe->drawstatus == NOTHING)
398         return;
399
400     p = win_transform_point(fe, x, y);
401     q = win_transform_point(fe, x+w, y+h);
402     IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
403 }
404
405 static void win_unclip(void *handle)
406 {
407     frontend *fe = (frontend *)handle;
408
409     if (fe->drawstatus == NOTHING)
410         return;
411
412     SelectClipRgn(fe->hdc, NULL);
413 }
414
415 static void win_draw_text(void *handle, int x, int y, int fonttype,
416                           int fontsize, int align, int colour, char *text)
417 {
418     frontend *fe = (frontend *)handle;
419     POINT xy;
420     int i;
421
422     if (fe->drawstatus == NOTHING)
423         return;
424
425     if (fe->drawstatus == PRINTING)
426         fontsize = (int)(fontsize * fe->printpixelscale);
427
428     xy = win_transform_point(fe, x, y);
429
430     /*
431      * Find or create the font.
432      */
433     for (i = fe->fontstart; i < fe->nfonts; i++)
434         if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
435             break;
436
437     if (i == fe->nfonts) {
438         if (fe->fontsize <= fe->nfonts) {
439             fe->fontsize = fe->nfonts + 10;
440             fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
441         }
442
443         fe->nfonts++;
444
445         fe->fonts[i].type = fonttype;
446         fe->fonts[i].size = fontsize;
447
448         fe->fonts[i].font = CreateFont(-fontsize, 0, 0, 0,
449                                        fe->drawstatus == PRINTING ? 0 : FW_BOLD,
450                                        FALSE, FALSE, FALSE, DEFAULT_CHARSET,
451                                        OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
452                                        DEFAULT_QUALITY,
453                                        (fonttype == FONT_FIXED ?
454                                         FIXED_PITCH | FF_DONTCARE :
455                                         VARIABLE_PITCH | FF_SWISS),
456                                        NULL);
457     }
458
459     /*
460      * Position and draw the text.
461      */
462     {
463         HFONT oldfont;
464         TEXTMETRIC tm;
465         SIZE size;
466
467         oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
468         if (GetTextMetrics(fe->hdc, &tm)) {
469             if (align & ALIGN_VCENTRE)
470                 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
471             else
472                 xy.y -= tm.tmAscent;
473         }
474         if (GetTextExtentPoint32(fe->hdc, text, strlen(text), &size)) {
475             if (align & ALIGN_HCENTRE)
476                 xy.x -= size.cx / 2;
477             else if (align & ALIGN_HRIGHT)
478                 xy.x -= size.cx;
479         }
480         SetBkMode(fe->hdc, TRANSPARENT);
481         win_text_colour(fe, colour);
482         TextOut(fe->hdc, xy.x, xy.y, text, strlen(text));
483         SelectObject(fe->hdc, oldfont);
484     }
485 }
486
487 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
488 {
489     frontend *fe = (frontend *)handle;
490     POINT p, q;
491
492     if (fe->drawstatus == NOTHING)
493         return;
494
495     if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
496         /*
497          * Rectangle() appears to get uppity if asked to draw a 1x1
498          * rectangle, presumably on the grounds that that's beneath
499          * its dignity and you ought to be using SetPixel instead.
500          * So I will.
501          */
502         SetPixel(fe->hdc, x, y, fe->colours[colour]);
503     } else {
504         win_set_brush(fe, colour);
505         win_set_pen(fe, colour, TRUE);
506         p = win_transform_point(fe, x, y);
507         q = win_transform_point(fe, x+w, y+h);
508         Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
509         win_reset_brush(fe);
510         win_reset_pen(fe);
511     }
512 }
513
514 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
515 {
516     frontend *fe = (frontend *)handle;
517     POINT p, q;
518
519     if (fe->drawstatus == NOTHING)
520         return;
521
522     win_set_pen(fe, colour, FALSE);
523     p = win_transform_point(fe, x1, y1);
524     q = win_transform_point(fe, x2, y2);
525     MoveToEx(fe->hdc, p.x, p.y, NULL);
526     LineTo(fe->hdc, q.x, q.y);
527     if (fe->drawstatus == DRAWING)
528         SetPixel(fe->hdc, q.x, q.y, fe->colours[colour]);
529     win_reset_pen(fe);
530 }
531
532 static void win_draw_circle(void *handle, int cx, int cy, int radius,
533                             int fillcolour, int outlinecolour)
534 {
535     frontend *fe = (frontend *)handle;
536     POINT p, q, r;
537
538     assert(outlinecolour >= 0);
539
540     if (fe->drawstatus == NOTHING)
541         return;
542
543     if (fillcolour >= 0) {
544         win_set_brush(fe, fillcolour);
545         win_set_pen(fe, outlinecolour, FALSE);
546         p = win_transform_point(fe, cx - radius, cy - radius);
547         q = win_transform_point(fe, cx + radius, cy + radius);
548         Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
549         win_reset_brush(fe);
550         win_reset_pen(fe);
551     } else {
552         win_set_pen(fe, outlinecolour, FALSE);
553         p = win_transform_point(fe, cx - radius, cy - radius);
554         q = win_transform_point(fe, cx + radius, cy + radius);
555         r = win_transform_point(fe, cx - radius, cy);
556         Arc(fe->hdc, p.x, p.y, q.x+1, q.y+1, r.x, r.y, r.x, r.y);
557         win_reset_pen(fe);
558     }
559 }
560
561 static void win_draw_polygon(void *handle, int *coords, int npoints,
562                              int fillcolour, int outlinecolour)
563 {
564     frontend *fe = (frontend *)handle;
565     POINT *pts;
566     int i;
567
568     if (fe->drawstatus == NOTHING)
569         return;
570
571     pts = snewn(npoints+1, POINT);
572
573     for (i = 0; i <= npoints; i++) {
574         int j = (i < npoints ? i : 0);
575         pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
576     }
577
578     assert(outlinecolour >= 0);
579
580     if (fillcolour >= 0) {
581         win_set_brush(fe, fillcolour);
582         win_set_pen(fe, outlinecolour, FALSE);
583         Polygon(fe->hdc, pts, npoints);
584         win_reset_brush(fe);
585         win_reset_pen(fe);
586     } else {
587         win_set_pen(fe, outlinecolour, FALSE);
588         Polyline(fe->hdc, pts, npoints+1);
589         win_reset_pen(fe);
590     }
591
592     sfree(pts);
593 }
594
595 static void win_start_draw(void *handle)
596 {
597     frontend *fe = (frontend *)handle;
598     HDC hdc_win;
599
600     assert(fe->drawstatus == NOTHING);
601
602     hdc_win = GetDC(fe->hwnd);
603     fe->hdc = CreateCompatibleDC(hdc_win);
604     fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
605     ReleaseDC(fe->hwnd, hdc_win);
606     fe->clip = NULL;
607     SetMapMode(fe->hdc, MM_TEXT);
608     fe->drawstatus = DRAWING;
609 }
610
611 static void win_draw_update(void *handle, int x, int y, int w, int h)
612 {
613     frontend *fe = (frontend *)handle;
614     RECT r;
615
616     if (fe->drawstatus != DRAWING)
617         return;
618
619     r.left = x;
620     r.top = y;
621     r.right = x + w;
622     r.bottom = y + h;
623
624     InvalidateRect(fe->hwnd, &r, FALSE);
625 }
626
627 static void win_end_draw(void *handle)
628 {
629     frontend *fe = (frontend *)handle;
630     assert(fe->drawstatus == DRAWING);
631     SelectObject(fe->hdc, fe->prevbm);
632     DeleteDC(fe->hdc);
633     if (fe->clip) {
634         DeleteObject(fe->clip);
635         fe->clip = NULL;
636     }
637     fe->drawstatus = NOTHING;
638 }
639
640 static void win_line_width(void *handle, float width)
641 {
642     frontend *fe = (frontend *)handle;
643
644     assert(fe->drawstatus != DRAWING);
645     if (fe->drawstatus == NOTHING)
646         return;
647
648     fe->linewidth = (int)(width * fe->printpixelscale);
649 }
650
651 static void win_begin_doc(void *handle, int pages)
652 {
653     frontend *fe = (frontend *)handle;
654
655     assert(fe->drawstatus != DRAWING);
656     if (fe->drawstatus == NOTHING)
657         return;
658
659     if (StartDoc(fe->hdc, &fe->di) <= 0) {
660         char *e = geterrstr();
661         MessageBox(fe->hwnd, e, "Error starting to print",
662                    MB_ICONERROR | MB_OK);
663         sfree(e);
664         fe->drawstatus = NOTHING;
665     }
666
667     /*
668      * Push a marker on the font stack so that we won't use the
669      * same fonts for printing and drawing. (This is because
670      * drawing seems to look generally better in bold, but printing
671      * is better not in bold.)
672      */
673     fe->fontstart = fe->nfonts;
674 }
675
676 static void win_begin_page(void *handle, int number)
677 {
678     frontend *fe = (frontend *)handle;
679
680     assert(fe->drawstatus != DRAWING);
681     if (fe->drawstatus == NOTHING)
682         return;
683
684     if (StartPage(fe->hdc) <= 0) {
685         char *e = geterrstr();
686         MessageBox(fe->hwnd, e, "Error starting a page",
687                    MB_ICONERROR | MB_OK);
688         sfree(e);
689         fe->drawstatus = NOTHING;
690     }
691 }
692
693 static void win_begin_puzzle(void *handle, float xm, float xc,
694                              float ym, float yc, int pw, int ph, float wmm)
695 {
696     frontend *fe = (frontend *)handle;
697     int ppw, pph, pox, poy;
698     float mmpw, mmph, mmox, mmoy;
699     float scale;
700
701     assert(fe->drawstatus != DRAWING);
702     if (fe->drawstatus == NOTHING)
703         return;
704
705     ppw = GetDeviceCaps(fe->hdc, HORZRES);
706     pph = GetDeviceCaps(fe->hdc, VERTRES);
707     mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
708     mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
709
710     /*
711      * Compute the puzzle's position on the logical page.
712      */
713     mmox = xm * mmpw + xc;
714     mmoy = ym * mmph + yc;
715
716     /*
717      * Work out what that comes to in pixels.
718      */
719     pox = (int)(mmox * (float)ppw / mmpw);
720     poy = (int)(mmoy * (float)ppw / mmpw);
721
722     /*
723      * And determine the scale.
724      * 
725      * I need a scale such that the maximum puzzle-coordinate
726      * extent of the rectangle (pw * scale) is equal to the pixel
727      * equivalent of the puzzle's millimetre width (wmm * ppw /
728      * mmpw).
729      */
730     scale = (wmm * ppw) / (mmpw * pw);
731
732     /*
733      * Now store pox, poy and scale for use in the main drawing
734      * functions.
735      */
736     fe->printoffsetx = pox;
737     fe->printoffsety = poy;
738     fe->printpixelscale = scale;
739
740     fe->linewidth = 1;
741 }
742
743 static void win_end_puzzle(void *handle)
744 {
745     /* Nothing needs to be done here. */
746 }
747
748 static void win_end_page(void *handle, int number)
749 {
750     frontend *fe = (frontend *)handle;
751
752     assert(fe->drawstatus != DRAWING);
753
754     if (fe->drawstatus == NOTHING)
755         return;
756
757     if (EndPage(fe->hdc) <= 0) {
758         char *e = geterrstr();
759         MessageBox(fe->hwnd, e, "Error finishing a page",
760                    MB_ICONERROR | MB_OK);
761         sfree(e);
762         fe->drawstatus = NOTHING;
763     }
764 }
765
766 static void win_end_doc(void *handle)
767 {
768     frontend *fe = (frontend *)handle;
769
770     assert(fe->drawstatus != DRAWING);
771
772     /*
773      * Free all the fonts created since we began printing.
774      */
775     while (fe->nfonts > fe->fontstart) {
776         fe->nfonts--;
777         DeleteObject(fe->fonts[fe->nfonts].font);
778     }
779     fe->fontstart = 0;
780
781     /*
782      * The MSDN web site sample code doesn't bother to call EndDoc
783      * if an error occurs half way through printing. I expect doing
784      * so would cause the erroneous document to actually be
785      * printed, or something equally undesirable.
786      */
787     if (fe->drawstatus == NOTHING)
788         return;
789
790     if (EndDoc(fe->hdc) <= 0) {
791         char *e = geterrstr();
792         MessageBox(fe->hwnd, e, "Error finishing printing",
793                    MB_ICONERROR | MB_OK);
794         sfree(e);
795         fe->drawstatus = NOTHING;
796     }
797 }
798
799 const struct drawing_api win_drawing = {
800     win_draw_text,
801     win_draw_rect,
802     win_draw_line,
803     win_draw_polygon,
804     win_draw_circle,
805     win_draw_update,
806     win_clip,
807     win_unclip,
808     win_start_draw,
809     win_end_draw,
810     win_status_bar,
811     win_blitter_new,
812     win_blitter_free,
813     win_blitter_save,
814     win_blitter_load,
815     win_begin_doc,
816     win_begin_page,
817     win_begin_puzzle,
818     win_end_puzzle,
819     win_end_page,
820     win_end_doc,
821     win_line_width,
822 };
823
824 void print(frontend *fe)
825 {
826     PRINTDLG pd;
827     char doctitle[256];
828     document *doc;
829     midend *nme = NULL;  /* non-interactive midend for bulk puzzle generation */
830     int i;
831     char *err = NULL;
832
833     /*
834      * Create our document structure and fill it up with puzzles.
835      */
836     doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
837     for (i = 0; i < fe->printcount; i++) {
838         if (i == 0 && fe->printcurr) {
839             err = midend_print_puzzle(fe->me, doc, fe->printsolns);
840         } else {
841             if (!nme) {
842                 game_params *params;
843
844                 nme = midend_new(NULL, &thegame, NULL, NULL);
845
846                 /*
847                  * Set the non-interactive mid-end to have the same
848                  * parameters as the standard one.
849                  */
850                 params = midend_get_params(fe->me);
851                 midend_set_params(nme, params);
852                 thegame.free_params(params);
853             }
854
855             midend_new_game(nme);
856             err = midend_print_puzzle(nme, doc, fe->printsolns);
857         }
858         if (err)
859             break;
860     }
861     if (nme)
862         midend_free(nme);
863
864     if (err) {
865         MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
866                    MB_ICONERROR | MB_OK);
867         document_free(doc);
868         return;
869     }
870
871     memset(&pd, 0, sizeof(pd));
872     pd.lStructSize = sizeof(pd);
873     pd.hwndOwner = fe->hwnd;
874     pd.hDevMode = NULL;
875     pd.hDevNames = NULL;
876     pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
877         PD_NOPAGENUMS | PD_NOSELECTION;
878     pd.nCopies = 1;
879     pd.nFromPage = pd.nToPage = 0xFFFF;
880     pd.nMinPage = pd.nMaxPage = 1;
881
882     if (!PrintDlg(&pd)) {
883         document_free(doc);
884         return;
885     }
886
887     /*
888      * Now pd.hDC is a device context for the printer.
889      */
890
891     /*
892      * FIXME: IWBNI we put up an Abort box here.
893      */
894
895     memset(&fe->di, 0, sizeof(fe->di));
896     fe->di.cbSize = sizeof(fe->di);
897     sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
898             " Portable Puzzle Collection)", thegame.name);
899     fe->di.lpszDocName = doctitle;
900     fe->di.lpszOutput = NULL;
901     fe->di.lpszDatatype = NULL;
902     fe->di.fwType = 0;
903
904     fe->drawstatus = PRINTING;
905     fe->hdc = pd.hDC;
906
907     fe->dr = drawing_new(&win_drawing, NULL, fe);
908     document_print(doc, fe->dr);
909     drawing_free(fe->dr);
910     fe->dr = NULL;
911
912     fe->drawstatus = NOTHING;
913
914     DeleteDC(pd.hDC);
915     document_free(doc);
916 }
917
918 void deactivate_timer(frontend *fe)
919 {
920     if (!fe)
921         return;                        /* for non-interactive midend */
922     if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
923     fe->timer = 0;
924 }
925
926 void activate_timer(frontend *fe)
927 {
928     if (!fe)
929         return;                        /* for non-interactive midend */
930     if (!fe->timer) {
931         fe->timer = SetTimer(fe->hwnd, fe->timer, 20, NULL);
932         fe->timer_last_tickcount = GetTickCount();
933     }
934 }
935
936 void write_clip(HWND hwnd, char *data)
937 {
938     HGLOBAL clipdata;
939     int len, i, j;
940     char *data2;
941     void *lock;
942
943     /*
944      * Windows expects CRLF in the clipboard, so we must convert
945      * any \n that has come out of the puzzle backend.
946      */
947     len = 0;
948     for (i = 0; data[i]; i++) {
949         if (data[i] == '\n')
950             len++;
951         len++;
952     }
953     data2 = snewn(len+1, char);
954     j = 0;
955     for (i = 0; data[i]; i++) {
956         if (data[i] == '\n')
957             data2[j++] = '\r';
958         data2[j++] = data[i];
959     }
960     assert(j == len);
961     data2[j] = '\0';
962
963     clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
964     if (!clipdata)
965         return;
966     lock = GlobalLock(clipdata);
967     if (!lock)
968         return;
969     memcpy(lock, data2, len);
970     ((unsigned char *) lock)[len] = 0;
971     GlobalUnlock(clipdata);
972
973     if (OpenClipboard(hwnd)) {
974         EmptyClipboard();
975         SetClipboardData(CF_TEXT, clipdata);
976         CloseClipboard();
977     } else
978         GlobalFree(clipdata);
979
980     sfree(data2);
981 }
982
983 /*
984  * See if we can find a help file.
985  */
986 static void find_help_file(frontend *fe)
987 {
988     char b[2048], *p, *q, *r;
989     FILE *fp;
990     if (!fe->help_path) {
991         GetModuleFileName(NULL, b, sizeof(b) - 1);
992         r = b;
993         p = strrchr(b, '\\');
994         if (p && p >= r) r = p+1;
995         q = strrchr(b, ':');
996         if (q && q >= r) r = q+1;
997         strcpy(r, HELP_FILE_NAME);
998         if ( (fp = fopen(b, "r")) != NULL) {
999             fe->help_path = dupstr(b);
1000             fclose(fp);
1001         } else
1002             fe->help_path = NULL;
1003         strcpy(r, HELP_CNT_NAME);
1004         if ( (fp = fopen(b, "r")) != NULL) {
1005             fe->help_has_contents = TRUE;
1006             fclose(fp);
1007         } else
1008             fe->help_has_contents = FALSE;
1009     }
1010 }
1011
1012 static void check_window_size(frontend *fe, int *px, int *py)
1013 {
1014     RECT r;
1015     int x, y, sy;
1016
1017     if (fe->statusbar) {
1018         RECT sr;
1019         GetWindowRect(fe->statusbar, &sr);
1020         sy = sr.bottom - sr.top;
1021     } else {
1022         sy = 0;
1023     }
1024
1025     /*
1026      * See if we actually got the window size we wanted, and adjust
1027      * the puzzle size if not.
1028      */
1029     GetClientRect(fe->hwnd, &r);
1030     x = r.right - r.left;
1031     y = r.bottom - r.top - sy;
1032     midend_size(fe->me, &x, &y, FALSE);
1033     if (x != r.right - r.left || y != r.bottom - r.top) {
1034         /*
1035          * Resize the window, now we know what size we _really_
1036          * want it to be.
1037          */
1038         r.left = r.top = 0;
1039         r.right = x;
1040         r.bottom = y + sy;
1041         AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1042         SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left, r.bottom - r.top,
1043                      SWP_NOMOVE | SWP_NOZORDER);
1044     }
1045
1046     if (fe->statusbar) {
1047         GetClientRect(fe->hwnd, &r);
1048         SetWindowPos(fe->statusbar, NULL, 0, r.bottom-r.top-sy, r.right-r.left,
1049                      sy, SWP_NOZORDER);
1050     }
1051
1052     *px = x;
1053     *py = y;
1054 }
1055
1056 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1057 {
1058     RECT r, sr;
1059
1060     if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1061         *x = sr.right - sr.left;
1062         *y = sr.bottom - sr.top;
1063         r.left = 100;
1064         r.right = 200;
1065         r.top = 100;
1066         r.bottom = 200;
1067         AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1068         *x -= r.right - r.left - 100;
1069         *y -= r.bottom - r.top - 100;
1070     } else {
1071         *x = *y = INT_MAX;
1072     }
1073
1074     if (fe->statusbar != NULL) {
1075         GetWindowRect(fe->statusbar, &sr);
1076         *y -= sr.bottom - sr.top;
1077     }
1078 }
1079
1080 static frontend *new_window(HINSTANCE inst, char *game_id, char **error)
1081 {
1082     frontend *fe;
1083     int x, y;
1084     RECT r;
1085
1086     fe = snew(frontend);
1087
1088     fe->me = midend_new(fe, &thegame, &win_drawing, fe);
1089
1090     if (game_id) {
1091         *error = midend_game_id(fe->me, game_id);
1092         if (*error) {
1093             midend_free(fe->me);
1094             sfree(fe);
1095             return NULL;
1096         }
1097     }
1098
1099     fe->help_path = NULL;
1100     find_help_file(fe);
1101
1102     fe->inst = inst;
1103
1104     fe->timer = 0;
1105     fe->hwnd = NULL;
1106
1107     fe->drawstatus = NOTHING;
1108     fe->dr = NULL;
1109     fe->fontstart = 0;
1110
1111     midend_new_game(fe->me);
1112
1113     fe->fonts = NULL;
1114     fe->nfonts = fe->fontsize = 0;
1115
1116     {
1117         int i, ncolours;
1118         float *colours;
1119
1120         colours = midend_colours(fe->me, &ncolours);
1121
1122         fe->colours = snewn(ncolours, COLORREF);
1123         fe->brushes = snewn(ncolours, HBRUSH);
1124         fe->pens = snewn(ncolours, HPEN);
1125
1126         for (i = 0; i < ncolours; i++) {
1127             fe->colours[i] = RGB(255 * colours[i*3+0],
1128                                  255 * colours[i*3+1],
1129                                  255 * colours[i*3+2]);
1130             fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1131             fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1132         }
1133         sfree(colours);
1134     }
1135
1136     if (midend_wants_statusbar(fe->me)) {
1137         fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
1138                                        WS_CHILD | WS_VISIBLE,
1139                                        0, 0, 0, 0, /* status bar does these */
1140                                        NULL, NULL, inst, NULL);
1141     } else
1142         fe->statusbar = NULL;
1143
1144     get_max_puzzle_size(fe, &x, &y);
1145     midend_size(fe->me, &x, &y, FALSE);
1146
1147     r.left = r.top = 0;
1148     r.right = x;
1149     r.bottom = y;
1150     AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1151
1152     fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
1153                               WS_OVERLAPPEDWINDOW &~
1154                               (WS_THICKFRAME | WS_MAXIMIZEBOX),
1155                               CW_USEDEFAULT, CW_USEDEFAULT,
1156                               r.right - r.left, r.bottom - r.top,
1157                               NULL, NULL, inst, NULL);
1158
1159     if (midend_wants_statusbar(fe->me)) {
1160         RECT sr;
1161         DestroyWindow(fe->statusbar);
1162         fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
1163                                        WS_CHILD | WS_VISIBLE,
1164                                        0, 0, 0, 0, /* status bar does these */
1165                                        fe->hwnd, NULL, inst, NULL);
1166         /*
1167          * Now resize the window to take account of the status bar.
1168          */
1169         GetWindowRect(fe->statusbar, &sr);
1170         GetWindowRect(fe->hwnd, &r);
1171         SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1172                      r.bottom - r.top + sr.bottom - sr.top,
1173                      SWP_NOMOVE | SWP_NOZORDER);
1174     } else {
1175         fe->statusbar = NULL;
1176     }
1177
1178     {
1179         HMENU bar = CreateMenu();
1180         HMENU menu = CreateMenu();
1181
1182         AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Game");
1183         AppendMenu(menu, MF_ENABLED, IDM_NEW, "New");
1184         AppendMenu(menu, MF_ENABLED, IDM_RESTART, "Restart");
1185         AppendMenu(menu, MF_ENABLED, IDM_DESC, "Specific...");
1186         AppendMenu(menu, MF_ENABLED, IDM_SEED, "Random Seed...");
1187
1188         if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1189             thegame.can_configure) {
1190             HMENU sub = CreateMenu();
1191             int i;
1192
1193             AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "Type");
1194
1195             fe->presets = snewn(fe->npresets, game_params *);
1196
1197             for (i = 0; i < fe->npresets; i++) {
1198                 char *name;
1199
1200                 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1201
1202                 /*
1203                  * FIXME: we ought to go through and do something
1204                  * with ampersands here.
1205                  */
1206
1207                 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1208             }
1209
1210             if (thegame.can_configure) {
1211                 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, "Custom...");
1212             }
1213         }
1214
1215         AppendMenu(menu, MF_SEPARATOR, 0, 0);
1216         AppendMenu(menu, MF_ENABLED, IDM_LOAD, "Load");
1217         AppendMenu(menu, MF_ENABLED, IDM_SAVE, "Save");
1218         AppendMenu(menu, MF_SEPARATOR, 0, 0);
1219         if (thegame.can_print) {
1220             AppendMenu(menu, MF_ENABLED, IDM_PRINT, "Print");
1221             AppendMenu(menu, MF_SEPARATOR, 0, 0);
1222         }
1223         AppendMenu(menu, MF_ENABLED, IDM_UNDO, "Undo");
1224         AppendMenu(menu, MF_ENABLED, IDM_REDO, "Redo");
1225         if (thegame.can_format_as_text) {
1226             AppendMenu(menu, MF_SEPARATOR, 0, 0);
1227             AppendMenu(menu, MF_ENABLED, IDM_COPY, "Copy");
1228         }
1229         if (thegame.can_solve) {
1230             AppendMenu(menu, MF_SEPARATOR, 0, 0);
1231             AppendMenu(menu, MF_ENABLED, IDM_SOLVE, "Solve");
1232         }
1233         AppendMenu(menu, MF_SEPARATOR, 0, 0);
1234         AppendMenu(menu, MF_ENABLED, IDM_QUIT, "Exit");
1235         menu = CreateMenu();
1236         AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Help");
1237         AppendMenu(menu, MF_ENABLED, IDM_ABOUT, "About");
1238         if (fe->help_path) {
1239             AppendMenu(menu, MF_SEPARATOR, 0, 0);
1240             AppendMenu(menu, MF_ENABLED, IDM_HELPC, "Contents");
1241             if (thegame.winhelp_topic) {
1242                 char *item;
1243                 assert(thegame.name);
1244                 item = snewn(9+strlen(thegame.name), char); /*ick*/
1245                 sprintf(item, "Help on %s", thegame.name);
1246                 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1247                 sfree(item);
1248             }
1249         }
1250         SetMenu(fe->hwnd, bar);
1251     }
1252
1253     fe->bitmap = NULL;
1254     new_game_size(fe); /* initialises fe->bitmap */
1255     check_window_size(fe, &x, &y);
1256
1257     SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1258
1259     ShowWindow(fe->hwnd, SW_NORMAL);
1260     SetForegroundWindow(fe->hwnd);
1261
1262     midend_redraw(fe->me);
1263
1264     return fe;
1265 }
1266
1267 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1268                                  WPARAM wParam, LPARAM lParam)
1269 {
1270     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1271
1272     switch (msg) {
1273       case WM_INITDIALOG:
1274         return 0;
1275
1276       case WM_COMMAND:
1277         if ((HIWORD(wParam) == BN_CLICKED ||
1278              HIWORD(wParam) == BN_DOUBLECLICKED) &&
1279             LOWORD(wParam) == IDOK)
1280             fe->dlg_done = 1;
1281         return 0;
1282
1283       case WM_CLOSE:
1284         fe->dlg_done = 1;
1285         return 0;
1286     }
1287
1288     return 0;
1289 }
1290
1291 /*
1292  * Wrappers on midend_{get,set}_config, which extend the CFG_*
1293  * enumeration to add CFG_PRINT.
1294  */
1295 static config_item *frontend_get_config(frontend *fe, int which,
1296                                         char **wintitle)
1297 {
1298     if (which < CFG_FRONTEND_SPECIFIC) {
1299         return midend_get_config(fe->me, which, wintitle);
1300     } else if (which == CFG_PRINT) {
1301         config_item *ret;
1302         int i;
1303
1304         *wintitle = snewn(40 + strlen(thegame.name), char);
1305         sprintf(*wintitle, "%s print setup", thegame.name);
1306
1307         ret = snewn(8, config_item);
1308
1309         i = 0;
1310
1311         ret[i].name = "Number of puzzles to print";
1312         ret[i].type = C_STRING;
1313         ret[i].sval = dupstr("1");
1314         ret[i].ival = 0;
1315         i++;
1316
1317         ret[i].name = "Number of puzzles across the page";
1318         ret[i].type = C_STRING;
1319         ret[i].sval = dupstr("1");
1320         ret[i].ival = 0;
1321         i++;
1322
1323         ret[i].name = "Number of puzzles down the page";
1324         ret[i].type = C_STRING;
1325         ret[i].sval = dupstr("1");
1326         ret[i].ival = 0;
1327         i++;
1328
1329         ret[i].name = "Percentage of standard size";
1330         ret[i].type = C_STRING;
1331         ret[i].sval = dupstr("100.0");
1332         ret[i].ival = 0;
1333         i++;
1334
1335         ret[i].name = "Include currently shown puzzle";
1336         ret[i].type = C_BOOLEAN;
1337         ret[i].sval = NULL;
1338         ret[i].ival = TRUE;
1339         i++;
1340
1341         ret[i].name = "Print solutions";
1342         ret[i].type = C_BOOLEAN;
1343         ret[i].sval = NULL;
1344         ret[i].ival = FALSE;
1345         i++;
1346
1347         if (thegame.can_print_in_colour) {
1348             ret[i].name = "Print in colour";
1349             ret[i].type = C_BOOLEAN;
1350             ret[i].sval = NULL;
1351             ret[i].ival = FALSE;
1352             i++;
1353         }
1354
1355         ret[i].name = NULL;
1356         ret[i].type = C_END;
1357         ret[i].sval = NULL;
1358         ret[i].ival = 0;
1359         i++;
1360
1361         return ret;
1362     } else {
1363         assert(!"We should never get here");
1364         return NULL;
1365     }
1366 }
1367
1368 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
1369 {
1370     if (which < CFG_FRONTEND_SPECIFIC) {
1371         return midend_set_config(fe->me, which, cfg);
1372     } else if (which == CFG_PRINT) {
1373         if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
1374             return "Number of puzzles to print should be at least one";
1375         if ((fe->printw = atoi(cfg[1].sval)) <= 0)
1376             return "Number of puzzles across the page should be at least one";
1377         if ((fe->printh = atoi(cfg[2].sval)) <= 0)
1378             return "Number of puzzles down the page should be at least one";
1379         if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
1380             return "Print size should be positive";
1381         fe->printcurr = cfg[4].ival;
1382         fe->printsolns = cfg[5].ival;
1383         fe->printcolour = thegame.can_print_in_colour && cfg[6].ival;
1384         return NULL;
1385     } else {
1386         assert(!"We should never get here");
1387         return "Internal error";
1388     }
1389 }
1390
1391 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
1392                                   WPARAM wParam, LPARAM lParam)
1393 {
1394     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1395     config_item *i;
1396     struct cfg_aux *j;
1397
1398     switch (msg) {
1399       case WM_INITDIALOG:
1400         return 0;
1401
1402       case WM_COMMAND:
1403         /*
1404          * OK and Cancel are special cases.
1405          */
1406         if ((HIWORD(wParam) == BN_CLICKED ||
1407              HIWORD(wParam) == BN_DOUBLECLICKED) &&
1408             (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
1409             if (LOWORD(wParam) == IDOK) {
1410                 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
1411
1412                 if (err) {
1413                     MessageBox(hwnd, err, "Validation error",
1414                                MB_ICONERROR | MB_OK);
1415                 } else {
1416                     fe->dlg_done = 2;
1417                 }
1418             } else {
1419                 fe->dlg_done = 1;
1420             }
1421             return 0;
1422         }
1423
1424         /*
1425          * First find the control whose id this is.
1426          */
1427         for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1428             if (j->ctlid == LOWORD(wParam))
1429                 break;
1430         }
1431         if (i->type == C_END)
1432             return 0;                  /* not our problem */
1433
1434         if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
1435             char buffer[4096];
1436             GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
1437             buffer[lenof(buffer)-1] = '\0';
1438             sfree(i->sval);
1439             i->sval = dupstr(buffer);
1440         } else if (i->type == C_BOOLEAN && 
1441                    (HIWORD(wParam) == BN_CLICKED ||
1442                     HIWORD(wParam) == BN_DOUBLECLICKED)) {
1443             i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
1444         } else if (i->type == C_CHOICES &&
1445                    HIWORD(wParam) == CBN_SELCHANGE) {
1446             i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
1447                                          CB_GETCURSEL, 0, 0);
1448         }
1449
1450         return 0;
1451
1452       case WM_CLOSE:
1453         fe->dlg_done = 1;
1454         return 0;
1455     }
1456
1457     return 0;
1458 }
1459
1460 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
1461             char *wclass, int wstyle,
1462             int exstyle, const char *wtext, int wid)
1463 {
1464     HWND ret;
1465     ret = CreateWindowEx(exstyle, wclass, wtext,
1466                          wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
1467                          fe->cfgbox, (HMENU) wid, fe->inst, NULL);
1468     SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
1469     return ret;
1470 }
1471
1472 static void about(frontend *fe)
1473 {
1474     int i;
1475     WNDCLASS wc;
1476     MSG msg;
1477     TEXTMETRIC tm;
1478     HDC hdc;
1479     HFONT oldfont;
1480     SIZE size;
1481     int gm, id;
1482     int winwidth, winheight, y;
1483     int height, width, maxwid;
1484     const char *strings[16];
1485     int lengths[16];
1486     int nstrings = 0;
1487     char titlebuf[512];
1488
1489     sprintf(titlebuf, "About %.250s", thegame.name);
1490
1491     strings[nstrings++] = thegame.name;
1492     strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
1493     strings[nstrings++] = ver;
1494
1495     wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1496     wc.lpfnWndProc = DefDlgProc;
1497     wc.cbClsExtra = 0;
1498     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1499     wc.hInstance = fe->inst;
1500     wc.hIcon = NULL;
1501     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1502     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1503     wc.lpszMenuName = NULL;
1504     wc.lpszClassName = "GameAboutBox";
1505     RegisterClass(&wc);
1506
1507     hdc = GetDC(fe->hwnd);
1508     SetMapMode(hdc, MM_TEXT);
1509
1510     fe->dlg_done = FALSE;
1511
1512     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1513                              0, 0, 0, 0,
1514                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1515                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1516                              DEFAULT_QUALITY,
1517                              FF_SWISS,
1518                              "MS Shell Dlg");
1519
1520     oldfont = SelectObject(hdc, fe->cfgfont);
1521     if (GetTextMetrics(hdc, &tm)) {
1522         height = tm.tmAscent + tm.tmDescent;
1523         width = tm.tmAveCharWidth;
1524     } else {
1525         height = width = 30;
1526     }
1527
1528     /*
1529      * Figure out the layout of the About box by measuring the
1530      * length of each piece of text.
1531      */
1532     maxwid = 0;
1533     winheight = height/2;
1534
1535     for (i = 0; i < nstrings; i++) {
1536         if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
1537             lengths[i] = size.cx;
1538         else
1539             lengths[i] = 0;            /* *shrug* */
1540         if (maxwid < lengths[i])
1541             maxwid = lengths[i];
1542         winheight += height * 3 / 2 + (height / 2);
1543     }
1544
1545     winheight += height + height * 7 / 4;      /* OK button */
1546     winwidth = maxwid + 4*width;
1547
1548     SelectObject(hdc, oldfont);
1549     ReleaseDC(fe->hwnd, hdc);
1550
1551     /*
1552      * Create the dialog, now that we know its size.
1553      */
1554     {
1555         RECT r, r2;
1556
1557         r.left = r.top = 0;
1558         r.right = winwidth;
1559         r.bottom = winheight;
1560
1561         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1562                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1563                                 WS_CAPTION | WS_SYSMENU*/) &~
1564                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1565                            FALSE, 0);
1566
1567         /*
1568          * Centre the dialog on its parent window.
1569          */
1570         r.right -= r.left;
1571         r.bottom -= r.top;
1572         GetWindowRect(fe->hwnd, &r2);
1573         r.left = (r2.left + r2.right - r.right) / 2;
1574         r.top = (r2.top + r2.bottom - r.bottom) / 2;
1575         r.right += r.left;
1576         r.bottom += r.top;
1577
1578         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
1579                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1580                                     WS_CAPTION | WS_SYSMENU,
1581                                     r.left, r.top,
1582                                     r.right-r.left, r.bottom-r.top,
1583                                     fe->hwnd, NULL, fe->inst, NULL);
1584     }
1585
1586     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1587
1588     SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1589     SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
1590
1591     id = 1000;
1592     y = height/2;
1593     for (i = 0; i < nstrings; i++) {
1594         int border = width*2 + (maxwid - lengths[i]) / 2;
1595         mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
1596                "Static", 0, 0, strings[i], id++);
1597         y += height*3/2;
1598
1599         assert(y < winheight);
1600         y += height/2;
1601     }
1602
1603     y += height/2;                     /* extra space before OK */
1604     mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
1605            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1606            "OK", IDOK);
1607
1608     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1609
1610     EnableWindow(fe->hwnd, FALSE);
1611     ShowWindow(fe->cfgbox, SW_NORMAL);
1612     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1613         if (!IsDialogMessage(fe->cfgbox, &msg))
1614             DispatchMessage(&msg);
1615         if (fe->dlg_done)
1616             break;
1617     }
1618     EnableWindow(fe->hwnd, TRUE);
1619     SetForegroundWindow(fe->hwnd);
1620     DestroyWindow(fe->cfgbox);
1621     DeleteObject(fe->cfgfont);
1622 }
1623
1624 static int get_config(frontend *fe, int which)
1625 {
1626     config_item *i;
1627     struct cfg_aux *j;
1628     char *title;
1629     WNDCLASS wc;
1630     MSG msg;
1631     TEXTMETRIC tm;
1632     HDC hdc;
1633     HFONT oldfont;
1634     SIZE size;
1635     HWND ctl;
1636     int gm, id, nctrls;
1637     int winwidth, winheight, col1l, col1r, col2l, col2r, y;
1638     int height, width, maxlabel, maxcheckbox;
1639
1640     wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1641     wc.lpfnWndProc = DefDlgProc;
1642     wc.cbClsExtra = 0;
1643     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1644     wc.hInstance = fe->inst;
1645     wc.hIcon = NULL;
1646     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1647     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1648     wc.lpszMenuName = NULL;
1649     wc.lpszClassName = "GameConfigBox";
1650     RegisterClass(&wc);
1651
1652     hdc = GetDC(fe->hwnd);
1653     SetMapMode(hdc, MM_TEXT);
1654
1655     fe->dlg_done = FALSE;
1656
1657     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1658                              0, 0, 0, 0,
1659                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1660                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1661                              DEFAULT_QUALITY,
1662                              FF_SWISS,
1663                              "MS Shell Dlg");
1664
1665     oldfont = SelectObject(hdc, fe->cfgfont);
1666     if (GetTextMetrics(hdc, &tm)) {
1667         height = tm.tmAscent + tm.tmDescent;
1668         width = tm.tmAveCharWidth;
1669     } else {
1670         height = width = 30;
1671     }
1672
1673     fe->cfg = frontend_get_config(fe, which, &title);
1674     fe->cfg_which = which;
1675
1676     /*
1677      * Figure out the layout of the config box by measuring the
1678      * length of each piece of text.
1679      */
1680     maxlabel = maxcheckbox = 0;
1681     winheight = height/2;
1682
1683     for (i = fe->cfg; i->type != C_END; i++) {
1684         switch (i->type) {
1685           case C_STRING:
1686           case C_CHOICES:
1687             /*
1688              * Both these control types have a label filling only
1689              * the left-hand column of the box.
1690              */
1691             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1692                 maxlabel < size.cx)
1693                 maxlabel = size.cx;
1694             winheight += height * 3 / 2 + (height / 2);
1695             break;
1696
1697           case C_BOOLEAN:
1698             /*
1699              * Checkboxes take up the whole of the box width.
1700              */
1701             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1702                 maxcheckbox < size.cx)
1703                 maxcheckbox = size.cx;
1704             winheight += height + (height / 2);
1705             break;
1706         }
1707     }
1708
1709     winheight += height + height * 7 / 4;      /* OK / Cancel buttons */
1710
1711     col1l = 2*width;
1712     col1r = col1l + maxlabel;
1713     col2l = col1r + 2*width;
1714     col2r = col2l + 30*width;
1715     if (col2r < col1l+2*height+maxcheckbox)
1716         col2r = col1l+2*height+maxcheckbox;
1717     winwidth = col2r + 2*width;
1718
1719     SelectObject(hdc, oldfont);
1720     ReleaseDC(fe->hwnd, hdc);
1721
1722     /*
1723      * Create the dialog, now that we know its size.
1724      */
1725     {
1726         RECT r, r2;
1727
1728         r.left = r.top = 0;
1729         r.right = winwidth;
1730         r.bottom = winheight;
1731
1732         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1733                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1734                                 WS_CAPTION | WS_SYSMENU*/) &~
1735                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1736                            FALSE, 0);
1737
1738         /*
1739          * Centre the dialog on its parent window.
1740          */
1741         r.right -= r.left;
1742         r.bottom -= r.top;
1743         GetWindowRect(fe->hwnd, &r2);
1744         r.left = (r2.left + r2.right - r.right) / 2;
1745         r.top = (r2.top + r2.bottom - r.bottom) / 2;
1746         r.right += r.left;
1747         r.bottom += r.top;
1748
1749         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
1750                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1751                                     WS_CAPTION | WS_SYSMENU,
1752                                     r.left, r.top,
1753                                     r.right-r.left, r.bottom-r.top,
1754                                     fe->hwnd, NULL, fe->inst, NULL);
1755         sfree(title);
1756     }
1757
1758     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1759
1760     SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1761     SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
1762
1763     /*
1764      * Count the controls so we can allocate cfgaux.
1765      */
1766     for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
1767         nctrls++;
1768     fe->cfgaux = snewn(nctrls, struct cfg_aux);
1769
1770     id = 1000;
1771     y = height/2;
1772     for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1773         switch (i->type) {
1774           case C_STRING:
1775             /*
1776              * Edit box with a label beside it.
1777              */
1778             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1779                    "Static", 0, 0, i->name, id++);
1780             ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
1781                          "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
1782                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1783             SetWindowText(ctl, i->sval);
1784             y += height*3/2;
1785             break;
1786
1787           case C_BOOLEAN:
1788             /*
1789              * Simple checkbox.
1790              */
1791             mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
1792                    BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
1793                    0, i->name, (j->ctlid = id++));
1794             CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
1795             y += height;
1796             break;
1797
1798           case C_CHOICES:
1799             /*
1800              * Drop-down list with a label beside it.
1801              */
1802             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1803                    "STATIC", 0, 0, i->name, id++);
1804             ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
1805                          "COMBOBOX", WS_TABSTOP |
1806                          CBS_DROPDOWNLIST | CBS_HASSTRINGS,
1807                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1808             {
1809                 char c, *p, *q, *str;
1810
1811                 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
1812                 p = i->sval;
1813                 c = *p++;
1814                 while (*p) {
1815                     q = p;
1816                     while (*q && *q != c) q++;
1817                     str = snewn(q-p+1, char);
1818                     strncpy(str, p, q-p);
1819                     str[q-p] = '\0';
1820                     SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
1821                     sfree(str);
1822                     if (*q) q++;
1823                     p = q;
1824                 }
1825             }
1826
1827             SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
1828
1829             y += height*3/2;
1830             break;
1831         }
1832
1833         assert(y < winheight);
1834         y += height/2;
1835     }
1836
1837     y += height/2;                     /* extra space before OK and Cancel */
1838     mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
1839            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1840            "OK", IDOK);
1841     mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
1842            BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP, 0, "Cancel", IDCANCEL);
1843
1844     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1845
1846     EnableWindow(fe->hwnd, FALSE);
1847     ShowWindow(fe->cfgbox, SW_NORMAL);
1848     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1849         if (!IsDialogMessage(fe->cfgbox, &msg))
1850             DispatchMessage(&msg);
1851         if (fe->dlg_done)
1852             break;
1853     }
1854     EnableWindow(fe->hwnd, TRUE);
1855     SetForegroundWindow(fe->hwnd);
1856     DestroyWindow(fe->cfgbox);
1857     DeleteObject(fe->cfgfont);
1858
1859     free_cfg(fe->cfg);
1860     sfree(fe->cfgaux);
1861
1862     return (fe->dlg_done == 2);
1863 }
1864
1865 static void new_game_size(frontend *fe)
1866 {
1867     RECT r, sr;
1868     HDC hdc;
1869     int x, y;
1870
1871     get_max_puzzle_size(fe, &x, &y);
1872     midend_size(fe->me, &x, &y, FALSE);
1873
1874     r.left = r.top = 0;
1875     r.right = x;
1876     r.bottom = y;
1877     AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1878
1879     if (fe->statusbar != NULL) {
1880         GetWindowRect(fe->statusbar, &sr);
1881     } else {
1882         sr.left = sr.right = sr.top = sr.bottom = 0;
1883     }
1884     SetWindowPos(fe->hwnd, NULL, 0, 0,
1885                  r.right - r.left,
1886                  r.bottom - r.top + sr.bottom - sr.top,
1887                  SWP_NOMOVE | SWP_NOZORDER);
1888
1889     check_window_size(fe, &x, &y);
1890
1891     if (fe->statusbar != NULL)
1892         SetWindowPos(fe->statusbar, NULL, 0, y, x,
1893                      sr.bottom - sr.top, SWP_NOZORDER);
1894
1895     if (fe->bitmap) DeleteObject(fe->bitmap);
1896
1897     hdc = GetDC(fe->hwnd);
1898     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
1899     ReleaseDC(fe->hwnd, hdc);
1900
1901     midend_redraw(fe->me);
1902 }
1903
1904 static void new_game_type(frontend *fe)
1905 {
1906     midend_new_game(fe->me);
1907     new_game_size(fe);
1908 }
1909
1910 static int is_alt_pressed(void)
1911 {
1912     BYTE keystate[256];
1913     int r = GetKeyboardState(keystate);
1914     if (!r)
1915         return FALSE;
1916     if (keystate[VK_MENU] & 0x80)
1917         return TRUE;
1918     if (keystate[VK_RMENU] & 0x80)
1919         return TRUE;
1920     return FALSE;
1921 }
1922
1923 static void savefile_write(void *wctx, void *buf, int len)
1924 {
1925     FILE *fp = (FILE *)wctx;
1926     fwrite(buf, 1, len, fp);
1927 }
1928
1929 static int savefile_read(void *wctx, void *buf, int len)
1930 {
1931     FILE *fp = (FILE *)wctx;
1932     int ret;
1933
1934     ret = fread(buf, 1, len, fp);
1935     return (ret == len);
1936 }
1937
1938 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1939                                 WPARAM wParam, LPARAM lParam)
1940 {
1941     frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1942     int cmd;
1943
1944     switch (message) {
1945       case WM_CLOSE:
1946         DestroyWindow(hwnd);
1947         return 0;
1948       case WM_COMMAND:
1949         cmd = wParam & ~0xF;           /* low 4 bits reserved to Windows */
1950         switch (cmd) {
1951           case IDM_NEW:
1952             if (!midend_process_key(fe->me, 0, 0, 'n'))
1953                 PostQuitMessage(0);
1954             break;
1955           case IDM_RESTART:
1956             midend_restart_game(fe->me);
1957             break;
1958           case IDM_UNDO:
1959             if (!midend_process_key(fe->me, 0, 0, 'u'))
1960                 PostQuitMessage(0);
1961             break;
1962           case IDM_REDO:
1963             if (!midend_process_key(fe->me, 0, 0, '\x12'))
1964                 PostQuitMessage(0);
1965             break;
1966           case IDM_COPY:
1967             {
1968                 char *text = midend_text_format(fe->me);
1969                 if (text)
1970                     write_clip(hwnd, text);
1971                 else
1972                     MessageBeep(MB_ICONWARNING);
1973                 sfree(text);
1974             }
1975             break;
1976           case IDM_SOLVE:
1977             {
1978                 char *msg = midend_solve(fe->me);
1979                 if (msg)
1980                     MessageBox(hwnd, msg, "Unable to solve",
1981                                MB_ICONERROR | MB_OK);
1982             }
1983             break;
1984           case IDM_QUIT:
1985             if (!midend_process_key(fe->me, 0, 0, 'q'))
1986                 PostQuitMessage(0);
1987             break;
1988           case IDM_CONFIG:
1989             if (get_config(fe, CFG_SETTINGS))
1990                 new_game_type(fe);
1991             break;
1992           case IDM_SEED:
1993             if (get_config(fe, CFG_SEED))
1994                 new_game_type(fe);
1995             break;
1996           case IDM_DESC:
1997             if (get_config(fe, CFG_DESC))
1998                 new_game_type(fe);
1999             break;
2000           case IDM_PRINT:
2001             if (get_config(fe, CFG_PRINT))
2002                 print(fe);
2003             break;
2004           case IDM_ABOUT:
2005             about(fe);
2006             break;
2007           case IDM_LOAD:
2008           case IDM_SAVE:
2009             {
2010                 OPENFILENAME of;
2011                 char filename[FILENAME_MAX];
2012                 int ret;
2013
2014                 memset(&of, 0, sizeof(of));
2015                 of.hwndOwner = hwnd;
2016                 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
2017                 of.lpstrCustomFilter = NULL;
2018                 of.nFilterIndex = 1;
2019                 of.lpstrFile = filename;
2020                 filename[0] = '\0';
2021                 of.nMaxFile = lenof(filename);
2022                 of.lpstrFileTitle = NULL;
2023                 of.lpstrTitle = (cmd == IDM_SAVE ?
2024                                  "Enter name of game file to save" :
2025                                  "Enter name of saved game file to load");
2026                 of.Flags = 0;
2027 #ifdef OPENFILENAME_SIZE_VERSION_400
2028                 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2029 #else
2030                 of.lStructSize = sizeof(of);
2031 #endif
2032                 of.lpstrInitialDir = NULL;
2033
2034                 if (cmd == IDM_SAVE)
2035                     ret = GetSaveFileName(&of);
2036                 else
2037                     ret = GetOpenFileName(&of);
2038
2039                 if (ret) {
2040                     if (cmd == IDM_SAVE) {
2041                         FILE *fp;
2042
2043                         if ((fp = fopen(filename, "r")) != NULL) {
2044                             char buf[256 + FILENAME_MAX];
2045                             fclose(fp);
2046                             /* file exists */
2047
2048                             sprintf(buf, "Are you sure you want to overwrite"
2049                                     " the file \"%.*s\"?",
2050                                     FILENAME_MAX, filename);
2051                             if (MessageBox(hwnd, buf, "Question",
2052                                            MB_YESNO | MB_ICONQUESTION)
2053                                 != IDYES)
2054                                 break;
2055                         }
2056
2057                         fp = fopen(filename, "w");
2058
2059                         if (!fp) {
2060                             MessageBox(hwnd, "Unable to open save file",
2061                                        "Error", MB_ICONERROR | MB_OK);
2062                             break;
2063                         }
2064
2065                         midend_serialise(fe->me, savefile_write, fp);
2066
2067                         fclose(fp);
2068                     } else {
2069                         FILE *fp = fopen(filename, "r");
2070                         char *err;
2071
2072                         if (!fp) {
2073                             MessageBox(hwnd, "Unable to open saved game file",
2074                                        "Error", MB_ICONERROR | MB_OK);
2075                             break;
2076                         }
2077
2078                         err = midend_deserialise(fe->me, savefile_read, fp);
2079
2080                         fclose(fp);
2081
2082                         if (err) {
2083                             MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
2084                             break;
2085                         }
2086
2087                         new_game_size(fe);
2088                     }
2089                 }
2090             }
2091
2092             break;
2093           case IDM_HELPC:
2094             assert(fe->help_path);
2095             WinHelp(hwnd, fe->help_path,
2096                     fe->help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
2097             break;
2098           case IDM_GAMEHELP:
2099             assert(fe->help_path);
2100             assert(thegame.winhelp_topic);
2101             {
2102                 char *cmd = snewn(10+strlen(thegame.winhelp_topic), char);
2103                 sprintf(cmd, "JI(`',`%s')", thegame.winhelp_topic);
2104                 WinHelp(hwnd, fe->help_path, HELP_COMMAND, (DWORD)cmd);
2105                 sfree(cmd);
2106             }
2107             break;
2108           default:
2109             {
2110                 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
2111
2112                 if (p >= 0 && p < fe->npresets) {
2113                     midend_set_params(fe->me, fe->presets[p]);
2114                     new_game_type(fe);
2115                 }
2116             }
2117             break;
2118         }
2119         break;
2120       case WM_DESTROY:
2121         PostQuitMessage(0);
2122         return 0;
2123       case WM_PAINT:
2124         {
2125             PAINTSTRUCT p;
2126             HDC hdc, hdc2;
2127             HBITMAP prevbm;
2128
2129             hdc = BeginPaint(hwnd, &p);
2130             hdc2 = CreateCompatibleDC(hdc);
2131             prevbm = SelectObject(hdc2, fe->bitmap);
2132             BitBlt(hdc,
2133                    p.rcPaint.left, p.rcPaint.top,
2134                    p.rcPaint.right - p.rcPaint.left,
2135                    p.rcPaint.bottom - p.rcPaint.top,
2136                    hdc2,
2137                    p.rcPaint.left, p.rcPaint.top,
2138                    SRCCOPY);
2139             SelectObject(hdc2, prevbm);
2140             DeleteDC(hdc2);
2141             EndPaint(hwnd, &p);
2142         }
2143         return 0;
2144       case WM_KEYDOWN:
2145         {
2146             int key = -1;
2147             BYTE keystate[256];
2148             int r = GetKeyboardState(keystate);
2149             int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
2150             int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
2151
2152             switch (wParam) {
2153               case VK_LEFT:
2154                 if (!(lParam & 0x01000000))
2155                     key = MOD_NUM_KEYPAD | '4';
2156                 else
2157                     key = shift | ctrl | CURSOR_LEFT;
2158                 break;
2159               case VK_RIGHT:
2160                 if (!(lParam & 0x01000000))
2161                     key = MOD_NUM_KEYPAD | '6';
2162                 else
2163                     key = shift | ctrl | CURSOR_RIGHT;
2164                 break;
2165               case VK_UP:
2166                 if (!(lParam & 0x01000000))
2167                     key = MOD_NUM_KEYPAD | '8';
2168                 else
2169                     key = shift | ctrl | CURSOR_UP;
2170                 break;
2171               case VK_DOWN:
2172                 if (!(lParam & 0x01000000))
2173                     key = MOD_NUM_KEYPAD | '2';
2174                 else
2175                     key = shift | ctrl | CURSOR_DOWN;
2176                 break;
2177                 /*
2178                  * Diagonal keys on the numeric keypad.
2179                  */
2180               case VK_PRIOR:
2181                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
2182                 break;
2183               case VK_NEXT:
2184                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
2185                 break;
2186               case VK_HOME:
2187                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
2188                 break;
2189               case VK_END:
2190                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
2191                 break;
2192               case VK_INSERT:
2193                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
2194                 break;
2195               case VK_CLEAR:
2196                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
2197                 break;
2198                 /*
2199                  * Numeric keypad keys with Num Lock on.
2200                  */
2201               case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
2202               case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
2203               case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
2204               case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
2205               case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
2206               case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
2207               case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
2208               case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
2209               case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
2210               case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
2211             }
2212
2213             if (key != -1) {
2214                 if (!midend_process_key(fe->me, 0, 0, key))
2215                     PostQuitMessage(0);
2216             } else {
2217                 MSG m;
2218                 m.hwnd = hwnd;
2219                 m.message = WM_KEYDOWN;
2220                 m.wParam = wParam;
2221                 m.lParam = lParam & 0xdfff;
2222                 TranslateMessage(&m);
2223             }
2224         }
2225         break;
2226       case WM_LBUTTONDOWN:
2227       case WM_RBUTTONDOWN:
2228       case WM_MBUTTONDOWN:
2229         {
2230             int button;
2231
2232             /*
2233              * Shift-clicks count as middle-clicks, since otherwise
2234              * two-button Windows users won't have any kind of
2235              * middle click to use.
2236              */
2237             if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
2238                 button = MIDDLE_BUTTON;
2239             else if (message == WM_RBUTTONDOWN || is_alt_pressed())
2240                 button = RIGHT_BUTTON;
2241             else
2242                 button = LEFT_BUTTON;
2243
2244             if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2245                                     (signed short)HIWORD(lParam), button))
2246                 PostQuitMessage(0);
2247
2248             SetCapture(hwnd);
2249         }
2250         break;
2251       case WM_LBUTTONUP:
2252       case WM_RBUTTONUP:
2253       case WM_MBUTTONUP:
2254         {
2255             int button;
2256
2257             /*
2258              * Shift-clicks count as middle-clicks, since otherwise
2259              * two-button Windows users won't have any kind of
2260              * middle click to use.
2261              */
2262             if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
2263                 button = MIDDLE_RELEASE;
2264             else if (message == WM_RBUTTONUP || is_alt_pressed())
2265                 button = RIGHT_RELEASE;
2266             else
2267                 button = LEFT_RELEASE;
2268
2269             if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2270                                     (signed short)HIWORD(lParam), button))
2271                 PostQuitMessage(0);
2272
2273             ReleaseCapture();
2274         }
2275         break;
2276       case WM_MOUSEMOVE:
2277         {
2278             int button;
2279
2280             if (wParam & (MK_MBUTTON | MK_SHIFT))
2281                 button = MIDDLE_DRAG;
2282             else if (wParam & MK_RBUTTON || is_alt_pressed())
2283                 button = RIGHT_DRAG;
2284             else
2285                 button = LEFT_DRAG;
2286             
2287             if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2288                                     (signed short)HIWORD(lParam), button))
2289                 PostQuitMessage(0);
2290         }
2291         break;
2292       case WM_CHAR:
2293         if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
2294             PostQuitMessage(0);
2295         return 0;
2296       case WM_TIMER:
2297         if (fe->timer) {
2298             DWORD now = GetTickCount();
2299             float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
2300             midend_timer(fe->me, elapsed);
2301             fe->timer_last_tickcount = now;
2302         }
2303         return 0;
2304     }
2305
2306     return DefWindowProc(hwnd, message, wParam, lParam);
2307 }
2308
2309 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
2310 {
2311     MSG msg;
2312     char *error;
2313
2314     InitCommonControls();
2315
2316     if (!prev) {
2317         WNDCLASS wndclass;
2318
2319         wndclass.style = 0;
2320         wndclass.lpfnWndProc = WndProc;
2321         wndclass.cbClsExtra = 0;
2322         wndclass.cbWndExtra = 0;
2323         wndclass.hInstance = inst;
2324         wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
2325         wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
2326         wndclass.hbrBackground = NULL;
2327         wndclass.lpszMenuName = NULL;
2328         wndclass.lpszClassName = thegame.name;
2329
2330         RegisterClass(&wndclass);
2331     }
2332
2333     while (*cmdline && isspace((unsigned char)*cmdline))
2334         cmdline++;
2335
2336     if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
2337         char buf[128];
2338         sprintf(buf, "%.100s Error", thegame.name);
2339         MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
2340         return 1;
2341     }
2342
2343     while (GetMessage(&msg, NULL, 0, 0)) {
2344         DispatchMessage(&msg);
2345     }
2346
2347     return msg.wParam;
2348 }