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