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