chiark / gitweb /
changelog: document last change
[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 #ifndef NO_HTMLHELP
8 #include <htmlhelp.h>
9 #endif /* NO_HTMLHELP */
10
11 #ifdef _WIN32_WCE
12 #include <commdlg.h>
13 #include <aygshell.h>
14 #endif
15
16 #include <stdio.h>
17 #include <assert.h>
18 #include <ctype.h>
19 #include <stdarg.h>
20 #include <stdlib.h>
21 #include <limits.h>
22 #include <time.h>
23
24 #include "puzzles.h"
25
26 #ifdef _WIN32_WCE
27 #include "resource.h"
28 #endif
29
30 #define IDM_NEW       0x0010
31 #define IDM_RESTART   0x0020
32 #define IDM_UNDO      0x0030
33 #define IDM_REDO      0x0040
34 #define IDM_COPY      0x0050
35 #define IDM_SOLVE     0x0060
36 #define IDM_QUIT      0x0070
37 #define IDM_CONFIG    0x0080
38 #define IDM_DESC      0x0090
39 #define IDM_SEED      0x00A0
40 #define IDM_HELPC     0x00B0
41 #define IDM_GAMEHELP  0x00C0
42 #define IDM_ABOUT     0x00D0
43 #define IDM_SAVE      0x00E0
44 #define IDM_LOAD      0x00F0
45 #define IDM_PRINT     0x0100
46 #define IDM_PRESETS   0x0110
47 #define IDM_GAMES     0x0300
48
49 #define IDM_KEYEMUL   0x0400
50
51 #define HELP_FILE_NAME  "puzzles.hlp"
52 #define HELP_CNT_NAME   "puzzles.cnt"
53 #ifndef NO_HTMLHELP
54 #define CHM_FILE_NAME   "puzzles.chm"
55 #endif /* NO_HTMLHELP */
56
57 #ifndef NO_HTMLHELP
58 typedef HWND (CALLBACK *htmlhelp_t)(HWND, LPCSTR, UINT, DWORD);
59 static htmlhelp_t htmlhelp;
60 static HINSTANCE hh_dll;
61 #endif /* NO_HTMLHELP */
62 enum { NONE, HLP, CHM } help_type;
63 char *help_path;
64 int help_has_contents;
65
66 #ifndef FILENAME_MAX
67 #define FILENAME_MAX    (260)
68 #endif
69
70 #ifndef HGDI_ERROR
71 #define HGDI_ERROR ((HANDLE)GDI_ERROR)
72 #endif
73
74 #ifdef COMBINED
75 #define CLASSNAME "Puzzles"
76 #else
77 #define CLASSNAME thegame.name
78 #endif
79
80 #ifdef _WIN32_WCE
81
82 /*
83  * Wrapper implementations of functions not supplied by the
84  * PocketPC API.
85  */
86
87 #define SHGetSubMenu(hWndMB,ID_MENU) (HMENU)SendMessage((hWndMB), SHCMBM_GETSUBMENU, (WPARAM)0, (LPARAM)ID_MENU)
88
89 #undef MessageBox
90
91 int MessageBox(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType)
92 {
93     TCHAR wText[2048];
94     TCHAR wCaption[2048];
95
96     MultiByteToWideChar (CP_ACP, 0, lpText,    -1, wText,    2048);
97     MultiByteToWideChar (CP_ACP, 0, lpCaption, -1, wCaption, 2048);
98
99     return MessageBoxW (hWnd, wText, wCaption, uType);
100 }
101
102 BOOL SetDlgItemTextA(HWND hDlg, int nIDDlgItem, LPCSTR lpString)
103 {
104     TCHAR wText[256];
105
106     MultiByteToWideChar (CP_ACP, 0, lpString, -1, wText, 256);
107     return SetDlgItemTextW(hDlg, nIDDlgItem, wText);
108 }
109
110 LPCSTR getenv(LPCSTR buf)
111 {
112     return NULL;
113 }
114
115 BOOL GetKeyboardState(PBYTE pb)
116 {
117   return FALSE;
118 }
119
120 static TCHAR wClassName[256], wGameName[256];
121
122 #endif
123
124 #ifdef DEBUGGING
125 static FILE *debug_fp = NULL;
126 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
127 static int debug_got_console = 0;
128
129 void dputs(char *buf)
130 {
131     /*DWORD dw;
132
133     if (!debug_got_console) {
134         if (AllocConsole()) {
135             debug_got_console = 1;
136             debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
137         }
138     }
139     if (!debug_fp) {
140         debug_fp = fopen("debug.log", "w");
141     }
142
143     if (debug_hdl != INVALID_HANDLE_VALUE) {
144         WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
145     }
146     if (debug_fp) {
147       fputs(buf, debug_fp);
148       fflush(debug_fp);
149     }*/
150     OutputDebugString(buf);
151 }
152
153 void debug_printf(char *fmt, ...)
154 {
155     char buf[4096];
156     va_list ap;
157     static int debugging = -1;
158
159     if (debugging == -1)
160         debugging = getenv("DEBUG_PUZZLES") ? 1 : 0;
161
162     if (debugging) {
163         va_start(ap, fmt);
164         _vsnprintf(buf, 4095, fmt, ap);
165         dputs(buf);
166         va_end(ap);
167     }
168 }
169 #endif
170
171 #ifndef _WIN32_WCE
172 #define WINFLAGS (WS_OVERLAPPEDWINDOW &~ \
173                       (WS_MAXIMIZEBOX | WS_OVERLAPPED))
174 #else
175 #define WINFLAGS (WS_CAPTION | WS_SYSMENU)
176 #endif
177
178 static void new_game_size(frontend *fe, float scale);
179
180 struct font {
181     HFONT font;
182     int type;
183     int size;
184 };
185
186 struct cfg_aux {
187     int ctlid;
188 };
189
190 struct blitter {
191     HBITMAP bitmap;
192     frontend *fe;
193     int x, y, w, h;
194 };
195
196 enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
197
198 struct preset_menuitemref {
199     HMENU which_menu;
200     int item_index;
201 };
202
203 struct frontend {
204     const game *game;
205     midend *me;
206     HWND hwnd, statusbar, cfgbox;
207 #ifdef _WIN32_WCE
208     HWND numpad;  /* window handle for the numeric pad */
209 #endif
210     HINSTANCE inst;
211     HBITMAP bitmap, prevbm;
212     RECT bitmapPosition;  /* game bitmap position within game window */
213     HDC hdc;
214     COLORREF *colours;
215     HBRUSH *brushes;
216     HPEN *pens;
217     HRGN clip;
218     HMENU gamemenu, typemenu;
219     UINT timer;
220     DWORD timer_last_tickcount;
221     struct preset_menu *preset_menu;
222     struct preset_menuitemref *preset_menuitems;
223     int n_preset_menuitems;
224     struct font *fonts;
225     int nfonts, fontsize;
226     config_item *cfg;
227     struct cfg_aux *cfgaux;
228     int cfg_which, dlg_done;
229     HFONT cfgfont;
230     HBRUSH oldbr;
231     HPEN oldpen;
232     int help_running;
233     enum { DRAWING, PRINTING, NOTHING } drawstatus;
234     DOCINFO di;
235     int printcount, printw, printh, printsolns, printcurr, printcolour;
236     float printscale;
237     int printoffsetx, printoffsety;
238     float printpixelscale;
239     int fontstart;
240     int linewidth, linedotted;
241     drawing *dr;
242     int xmin, ymin;
243     float puzz_scale;
244 };
245
246 void frontend_free(frontend *fe)
247 {
248     midend_free(fe->me);
249
250     sfree(fe->colours);
251     sfree(fe->brushes);
252     sfree(fe->pens);
253     sfree(fe->fonts);
254
255     sfree(fe);
256 }
257
258 static void update_type_menu_tick(frontend *fe);
259 static void update_copy_menu_greying(frontend *fe);
260
261 void fatal(char *fmt, ...)
262 {
263     char buf[2048];
264     va_list ap;
265
266     va_start(ap, fmt);
267     vsprintf(buf, fmt, ap);
268     va_end(ap);
269
270     MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
271
272     exit(1);
273 }
274
275 char *geterrstr(void)
276 {
277     LPVOID lpMsgBuf;
278     DWORD dw = GetLastError();
279     char *ret;
280
281     FormatMessage(
282         FORMAT_MESSAGE_ALLOCATE_BUFFER | 
283         FORMAT_MESSAGE_FROM_SYSTEM,
284         NULL,
285         dw,
286         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
287         (LPTSTR) &lpMsgBuf,
288         0, NULL );
289
290     ret = dupstr(lpMsgBuf);
291
292     LocalFree(lpMsgBuf);
293
294     return ret;
295 }
296
297 void get_random_seed(void **randseed, int *randseedsize)
298 {
299     SYSTEMTIME *st = snew(SYSTEMTIME);
300
301     GetLocalTime(st);
302
303     *randseed = (void *)st;
304     *randseedsize = sizeof(SYSTEMTIME);
305 }
306
307 static void win_status_bar(void *handle, char *text)
308 {
309 #ifdef _WIN32_WCE
310     TCHAR wText[255];
311 #endif
312     frontend *fe = (frontend *)handle;
313
314 #ifdef _WIN32_WCE
315     MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 255);
316     SendMessage(fe->statusbar, SB_SETTEXT,
317                 (WPARAM) 255 | SBT_NOBORDERS,
318                 (LPARAM) wText);
319 #else
320     SetWindowText(fe->statusbar, text);
321 #endif
322 }
323
324 static blitter *win_blitter_new(void *handle, int w, int h)
325 {
326     blitter *bl = snew(blitter);
327
328     memset(bl, 0, sizeof(blitter));
329     bl->w = w;
330     bl->h = h;
331     bl->bitmap = 0;
332
333     return bl;
334 }
335
336 static void win_blitter_free(void *handle, blitter *bl)
337 {
338     if (bl->bitmap) DeleteObject(bl->bitmap);
339     sfree(bl);
340 }
341
342 static void blitter_mkbitmap(frontend *fe, blitter *bl)
343 {
344     HDC hdc = GetDC(fe->hwnd);
345     bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
346     ReleaseDC(fe->hwnd, hdc);
347 }
348
349 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
350
351 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
352 {
353     frontend *fe = (frontend *)handle;
354     HDC hdc_win, hdc_blit;
355     HBITMAP prev_blit;
356
357     assert(fe->drawstatus == DRAWING);
358
359     if (!bl->bitmap) blitter_mkbitmap(fe, bl);
360
361     bl->x = x; bl->y = y;
362
363     hdc_win = GetDC(fe->hwnd);
364     hdc_blit = CreateCompatibleDC(hdc_win);
365     if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
366
367     prev_blit = SelectObject(hdc_blit, bl->bitmap);
368     if (prev_blit == NULL || prev_blit == HGDI_ERROR)
369         fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
370
371     if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
372                 fe->hdc, x, y, SRCCOPY))
373         fatal("BitBlt failed: 0x%x", GetLastError());
374
375     SelectObject(hdc_blit, prev_blit);
376     DeleteDC(hdc_blit);
377     ReleaseDC(fe->hwnd, hdc_win);
378 }
379
380 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
381 {
382     frontend *fe = (frontend *)handle;
383     HDC hdc_win, hdc_blit;
384     HBITMAP prev_blit;
385
386     assert(fe->drawstatus == DRAWING);
387
388     assert(bl->bitmap); /* we should always have saved before loading */
389
390     if (x == BLITTER_FROMSAVED) x = bl->x;
391     if (y == BLITTER_FROMSAVED) y = bl->y;
392
393     hdc_win = GetDC(fe->hwnd);
394     hdc_blit = CreateCompatibleDC(hdc_win);
395
396     prev_blit = SelectObject(hdc_blit, bl->bitmap);
397
398     BitBlt(fe->hdc, x, y, bl->w, bl->h,
399            hdc_blit, 0, 0, SRCCOPY);
400
401     SelectObject(hdc_blit, prev_blit);
402     DeleteDC(hdc_blit);
403     ReleaseDC(fe->hwnd, hdc_win);
404 }
405
406 void frontend_default_colour(frontend *fe, float *output)
407 {
408     DWORD c = GetSysColor(COLOR_MENU); /* ick */
409
410     output[0] = (float)(GetRValue(c) / 255.0);
411     output[1] = (float)(GetGValue(c) / 255.0);
412     output[2] = (float)(GetBValue(c) / 255.0);
413 }
414
415 static POINT win_transform_point(frontend *fe, int x, int y)
416 {
417     POINT ret;
418
419     assert(fe->drawstatus != NOTHING);
420
421     if (fe->drawstatus == PRINTING) {
422         ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
423         ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
424     } else {
425         ret.x = x;
426         ret.y = y;
427     }
428
429     return ret;
430 }
431
432 static void win_text_colour(frontend *fe, int colour)
433 {
434     assert(fe->drawstatus != NOTHING);
435
436     if (fe->drawstatus == PRINTING) {
437         int hatch;
438         float r, g, b;
439         print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
440
441         /*
442          * Displaying text in hatched colours is not permitted.
443          */
444         assert(hatch < 0);
445
446         SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
447     } else {
448         SetTextColor(fe->hdc, fe->colours[colour]);
449     }
450 }
451
452 static void win_set_brush(frontend *fe, int colour)
453 {
454     HBRUSH br;
455     assert(fe->drawstatus != NOTHING);
456
457     if (fe->drawstatus == PRINTING) {
458         int hatch;
459         float r, g, b;
460         print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
461
462         if (hatch < 0) {
463             br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
464         } else {
465 #ifdef _WIN32_WCE
466             /*
467              * This is only ever required during printing, and the
468              * PocketPC port doesn't support printing.
469              */
470             fatal("CreateHatchBrush not supported");
471 #else
472             br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
473                                   hatch == HATCH_SLASH ? HS_BDIAGONAL :
474                                   hatch == HATCH_HORIZ ? HS_HORIZONTAL :
475                                   hatch == HATCH_VERT ? HS_VERTICAL :
476                                   hatch == HATCH_PLUS ? HS_CROSS :
477                                   /* hatch == HATCH_X ? */ HS_DIAGCROSS,
478                                   RGB(0,0,0));
479 #endif
480         }
481     } else {
482         br = fe->brushes[colour];
483     }
484     fe->oldbr = SelectObject(fe->hdc, br);
485 }
486
487 static void win_reset_brush(frontend *fe)
488 {
489     HBRUSH br;
490
491     assert(fe->drawstatus != NOTHING);
492
493     br = SelectObject(fe->hdc, fe->oldbr);
494     if (fe->drawstatus == PRINTING)
495         DeleteObject(br);
496 }
497
498 static void win_set_pen(frontend *fe, int colour, int thin)
499 {
500     HPEN pen;
501     assert(fe->drawstatus != NOTHING);
502
503     if (fe->drawstatus == PRINTING) {
504         int hatch;
505         float r, g, b;
506         int width = thin ? 0 : fe->linewidth;
507
508         if (fe->linedotted)
509             width = 0;
510
511         print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
512         /*
513          * Stroking in hatched colours is not permitted.
514          */
515         assert(hatch < 0);
516         pen = CreatePen(fe->linedotted ? PS_DOT : PS_SOLID,
517                         width, RGB(r * 255, g * 255, b * 255));
518     } else {
519         pen = fe->pens[colour];
520     }
521     fe->oldpen = SelectObject(fe->hdc, pen);
522 }
523
524 static void win_reset_pen(frontend *fe)
525 {
526     HPEN pen;
527
528     assert(fe->drawstatus != NOTHING);
529
530     pen = SelectObject(fe->hdc, fe->oldpen);
531     if (fe->drawstatus == PRINTING)
532         DeleteObject(pen);
533 }
534
535 static void win_clip(void *handle, int x, int y, int w, int h)
536 {
537     frontend *fe = (frontend *)handle;
538     POINT p, q;
539
540     if (fe->drawstatus == NOTHING)
541         return;
542
543     p = win_transform_point(fe, x, y);
544     q = win_transform_point(fe, x+w, y+h);
545     IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
546 }
547
548 static void win_unclip(void *handle)
549 {
550     frontend *fe = (frontend *)handle;
551
552     if (fe->drawstatus == NOTHING)
553         return;
554
555     SelectClipRgn(fe->hdc, NULL);
556 }
557
558 static void win_draw_text(void *handle, int x, int y, int fonttype,
559                           int fontsize, int align, int colour, char *text)
560 {
561     frontend *fe = (frontend *)handle;
562     POINT xy;
563     int i;
564     LOGFONT lf;
565
566     if (fe->drawstatus == NOTHING)
567         return;
568
569     if (fe->drawstatus == PRINTING)
570         fontsize = (int)(fontsize * fe->printpixelscale);
571
572     xy = win_transform_point(fe, x, y);
573
574     /*
575      * Find or create the font.
576      */
577     for (i = fe->fontstart; i < fe->nfonts; i++)
578         if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
579             break;
580
581     if (i == fe->nfonts) {
582         if (fe->fontsize <= fe->nfonts) {
583             fe->fontsize = fe->nfonts + 10;
584             fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
585         }
586
587         fe->nfonts++;
588
589         fe->fonts[i].type = fonttype;
590         fe->fonts[i].size = fontsize;
591
592         memset (&lf, 0, sizeof(LOGFONT));
593         lf.lfHeight = -fontsize;
594         lf.lfWeight = (fe->drawstatus == PRINTING ? 0 : FW_BOLD);
595         lf.lfCharSet = DEFAULT_CHARSET;
596         lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
597         lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
598         lf.lfQuality = DEFAULT_QUALITY;
599         lf.lfPitchAndFamily = (fonttype == FONT_FIXED ?
600                                FIXED_PITCH | FF_DONTCARE :
601                                VARIABLE_PITCH | FF_SWISS);
602 #ifdef _WIN32_WCE
603         wcscpy(lf.lfFaceName, TEXT("Tahoma"));
604 #endif
605
606         fe->fonts[i].font = CreateFontIndirect(&lf);
607     }
608
609     /*
610      * Position and draw the text.
611      */
612     {
613         HFONT oldfont;
614         TEXTMETRIC tm;
615         SIZE size;
616         WCHAR wText[256];
617         MultiByteToWideChar (CP_UTF8, 0, text, -1, wText, 256);
618
619         oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
620         if (GetTextMetrics(fe->hdc, &tm)) {
621             if (align & ALIGN_VCENTRE)
622                 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
623             else
624                 xy.y -= tm.tmAscent;
625         }
626         if (GetTextExtentPoint32W(fe->hdc, wText, wcslen(wText), &size))
627         {
628             if (align & ALIGN_HCENTRE)
629                 xy.x -= size.cx / 2;
630             else if (align & ALIGN_HRIGHT)
631                 xy.x -= size.cx;
632         }
633         SetBkMode(fe->hdc, TRANSPARENT);
634         win_text_colour(fe, colour);
635         ExtTextOutW(fe->hdc, xy.x, xy.y, 0, NULL, wText, wcslen(wText), NULL);
636         SelectObject(fe->hdc, oldfont);
637     }
638 }
639
640 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
641 {
642     frontend *fe = (frontend *)handle;
643     POINT p, q;
644
645     if (fe->drawstatus == NOTHING)
646         return;
647
648     if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
649         /*
650          * Rectangle() appears to get uppity if asked to draw a 1x1
651          * rectangle, presumably on the grounds that that's beneath
652          * its dignity and you ought to be using SetPixel instead.
653          * So I will.
654          */
655         SetPixel(fe->hdc, x, y, fe->colours[colour]);
656     } else {
657         win_set_brush(fe, colour);
658         win_set_pen(fe, colour, TRUE);
659         p = win_transform_point(fe, x, y);
660         q = win_transform_point(fe, x+w, y+h);
661         Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
662         win_reset_brush(fe);
663         win_reset_pen(fe);
664     }
665 }
666
667 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
668 {
669     frontend *fe = (frontend *)handle;
670     POINT pp[2];
671
672     if (fe->drawstatus == NOTHING)
673         return;
674
675     win_set_pen(fe, colour, FALSE);
676     pp[0] = win_transform_point(fe, x1, y1);
677     pp[1] = win_transform_point(fe, x2, y2);
678     Polyline(fe->hdc, pp, 2);
679     if (fe->drawstatus == DRAWING)
680         SetPixel(fe->hdc, pp[1].x, pp[1].y, fe->colours[colour]);
681     win_reset_pen(fe);
682 }
683
684 static void win_draw_circle(void *handle, int cx, int cy, int radius,
685                             int fillcolour, int outlinecolour)
686 {
687     frontend *fe = (frontend *)handle;
688     POINT p, q;
689
690     assert(outlinecolour >= 0);
691
692     if (fe->drawstatus == NOTHING)
693         return;
694
695     if (fillcolour >= 0)
696         win_set_brush(fe, fillcolour);
697     else
698         fe->oldbr = SelectObject(fe->hdc, GetStockObject(NULL_BRUSH));
699
700     win_set_pen(fe, outlinecolour, FALSE);
701     p = win_transform_point(fe, cx - radius, cy - radius);
702     q = win_transform_point(fe, cx + radius, cy + radius);
703     Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
704     win_reset_brush(fe);
705     win_reset_pen(fe);
706 }
707
708 static void win_draw_polygon(void *handle, int *coords, int npoints,
709                              int fillcolour, int outlinecolour)
710 {
711     frontend *fe = (frontend *)handle;
712     POINT *pts;
713     int i;
714
715     if (fe->drawstatus == NOTHING)
716         return;
717
718     pts = snewn(npoints+1, POINT);
719
720     for (i = 0; i <= npoints; i++) {
721         int j = (i < npoints ? i : 0);
722         pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
723     }
724
725     assert(outlinecolour >= 0);
726
727     if (fillcolour >= 0) {
728         win_set_brush(fe, fillcolour);
729         win_set_pen(fe, outlinecolour, FALSE);
730         Polygon(fe->hdc, pts, npoints);
731         win_reset_brush(fe);
732         win_reset_pen(fe);
733     } else {
734         win_set_pen(fe, outlinecolour, FALSE);
735         Polyline(fe->hdc, pts, npoints+1);
736         win_reset_pen(fe);
737     }
738
739     sfree(pts);
740 }
741
742 static void win_start_draw(void *handle)
743 {
744     frontend *fe = (frontend *)handle;
745     HDC hdc_win;
746
747     assert(fe->drawstatus == NOTHING);
748
749     hdc_win = GetDC(fe->hwnd);
750     fe->hdc = CreateCompatibleDC(hdc_win);
751     fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
752     ReleaseDC(fe->hwnd, hdc_win);
753     fe->clip = NULL;
754 #ifndef _WIN32_WCE
755     SetMapMode(fe->hdc, MM_TEXT);
756 #endif
757     fe->drawstatus = DRAWING;
758 }
759
760 static void win_draw_update(void *handle, int x, int y, int w, int h)
761 {
762     frontend *fe = (frontend *)handle;
763     RECT r;
764
765     if (fe->drawstatus != DRAWING)
766         return;
767
768     r.left = x;
769     r.top = y;
770     r.right = x + w;
771     r.bottom = y + h;
772
773     OffsetRect(&r, fe->bitmapPosition.left, fe->bitmapPosition.top);
774     InvalidateRect(fe->hwnd, &r, FALSE);
775 }
776
777 static void win_end_draw(void *handle)
778 {
779     frontend *fe = (frontend *)handle;
780     assert(fe->drawstatus == DRAWING);
781     SelectObject(fe->hdc, fe->prevbm);
782     DeleteDC(fe->hdc);
783     if (fe->clip) {
784         DeleteObject(fe->clip);
785         fe->clip = NULL;
786     }
787     fe->drawstatus = NOTHING;
788 }
789
790 static void win_line_width(void *handle, float width)
791 {
792     frontend *fe = (frontend *)handle;
793
794     assert(fe->drawstatus != DRAWING);
795     if (fe->drawstatus == NOTHING)
796         return;
797
798     fe->linewidth = (int)(width * fe->printpixelscale);
799 }
800
801 static void win_line_dotted(void *handle, int dotted)
802 {
803     frontend *fe = (frontend *)handle;
804
805     assert(fe->drawstatus != DRAWING);
806     if (fe->drawstatus == NOTHING)
807         return;
808
809     fe->linedotted = dotted;
810 }
811
812 static void win_begin_doc(void *handle, int pages)
813 {
814     frontend *fe = (frontend *)handle;
815
816     assert(fe->drawstatus != DRAWING);
817     if (fe->drawstatus == NOTHING)
818         return;
819
820     if (StartDoc(fe->hdc, &fe->di) <= 0) {
821         char *e = geterrstr();
822         MessageBox(fe->hwnd, e, "Error starting to print",
823                    MB_ICONERROR | MB_OK);
824         sfree(e);
825         fe->drawstatus = NOTHING;
826     }
827
828     /*
829      * Push a marker on the font stack so that we won't use the
830      * same fonts for printing and drawing. (This is because
831      * drawing seems to look generally better in bold, but printing
832      * is better not in bold.)
833      */
834     fe->fontstart = fe->nfonts;
835 }
836
837 static void win_begin_page(void *handle, int number)
838 {
839     frontend *fe = (frontend *)handle;
840
841     assert(fe->drawstatus != DRAWING);
842     if (fe->drawstatus == NOTHING)
843         return;
844
845     if (StartPage(fe->hdc) <= 0) {
846         char *e = geterrstr();
847         MessageBox(fe->hwnd, e, "Error starting a page",
848                    MB_ICONERROR | MB_OK);
849         sfree(e);
850         fe->drawstatus = NOTHING;
851     }
852 }
853
854 static void win_begin_puzzle(void *handle, float xm, float xc,
855                              float ym, float yc, int pw, int ph, float wmm)
856 {
857     frontend *fe = (frontend *)handle;
858     int ppw, pph, pox, poy;
859     float mmpw, mmph, mmox, mmoy;
860     float scale;
861
862     assert(fe->drawstatus != DRAWING);
863     if (fe->drawstatus == NOTHING)
864         return;
865
866     ppw = GetDeviceCaps(fe->hdc, HORZRES);
867     pph = GetDeviceCaps(fe->hdc, VERTRES);
868     mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
869     mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
870
871     /*
872      * Compute the puzzle's position on the logical page.
873      */
874     mmox = xm * mmpw + xc;
875     mmoy = ym * mmph + yc;
876
877     /*
878      * Work out what that comes to in pixels.
879      */
880     pox = (int)(mmox * (float)ppw / mmpw);
881     poy = (int)(mmoy * (float)pph / mmph);
882
883     /*
884      * And determine the scale.
885      * 
886      * I need a scale such that the maximum puzzle-coordinate
887      * extent of the rectangle (pw * scale) is equal to the pixel
888      * equivalent of the puzzle's millimetre width (wmm * ppw /
889      * mmpw).
890      */
891     scale = (wmm * ppw) / (mmpw * pw);
892
893     /*
894      * Now store pox, poy and scale for use in the main drawing
895      * functions.
896      */
897     fe->printoffsetx = pox;
898     fe->printoffsety = poy;
899     fe->printpixelscale = scale;
900
901     fe->linewidth = 1;
902     fe->linedotted = FALSE;
903 }
904
905 static void win_end_puzzle(void *handle)
906 {
907     /* Nothing needs to be done here. */
908 }
909
910 static void win_end_page(void *handle, int number)
911 {
912     frontend *fe = (frontend *)handle;
913
914     assert(fe->drawstatus != DRAWING);
915
916     if (fe->drawstatus == NOTHING)
917         return;
918
919     if (EndPage(fe->hdc) <= 0) {
920         char *e = geterrstr();
921         MessageBox(fe->hwnd, e, "Error finishing a page",
922                    MB_ICONERROR | MB_OK);
923         sfree(e);
924         fe->drawstatus = NOTHING;
925     }
926 }
927
928 static void win_end_doc(void *handle)
929 {
930     frontend *fe = (frontend *)handle;
931
932     assert(fe->drawstatus != DRAWING);
933
934     /*
935      * Free all the fonts created since we began printing.
936      */
937     while (fe->nfonts > fe->fontstart) {
938         fe->nfonts--;
939         DeleteObject(fe->fonts[fe->nfonts].font);
940     }
941     fe->fontstart = 0;
942
943     /*
944      * The MSDN web site sample code doesn't bother to call EndDoc
945      * if an error occurs half way through printing. I expect doing
946      * so would cause the erroneous document to actually be
947      * printed, or something equally undesirable.
948      */
949     if (fe->drawstatus == NOTHING)
950         return;
951
952     if (EndDoc(fe->hdc) <= 0) {
953         char *e = geterrstr();
954         MessageBox(fe->hwnd, e, "Error finishing printing",
955                    MB_ICONERROR | MB_OK);
956         sfree(e);
957         fe->drawstatus = NOTHING;
958     }
959 }
960
961 char *win_text_fallback(void *handle, const char *const *strings, int nstrings)
962 {
963     /*
964      * We assume Windows can cope with any UTF-8 likely to be
965      * emitted by a puzzle.
966      */
967     return dupstr(strings[0]);
968 }
969
970 const struct drawing_api win_drawing = {
971     win_draw_text,
972     win_draw_rect,
973     win_draw_line,
974     win_draw_polygon,
975     win_draw_circle,
976     win_draw_update,
977     win_clip,
978     win_unclip,
979     win_start_draw,
980     win_end_draw,
981     win_status_bar,
982     win_blitter_new,
983     win_blitter_free,
984     win_blitter_save,
985     win_blitter_load,
986     win_begin_doc,
987     win_begin_page,
988     win_begin_puzzle,
989     win_end_puzzle,
990     win_end_page,
991     win_end_doc,
992     win_line_width,
993     win_line_dotted,
994     win_text_fallback,
995 };
996
997 void print(frontend *fe)
998 {
999 #ifndef _WIN32_WCE
1000     PRINTDLG pd;
1001     char doctitle[256];
1002     document *doc;
1003     midend *nme = NULL;  /* non-interactive midend for bulk puzzle generation */
1004     int i;
1005     char *err = NULL;
1006
1007     /*
1008      * Create our document structure and fill it up with puzzles.
1009      */
1010     doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
1011     for (i = 0; i < fe->printcount; i++) {
1012         if (i == 0 && fe->printcurr) {
1013             err = midend_print_puzzle(fe->me, doc, fe->printsolns);
1014         } else {
1015             if (!nme) {
1016                 game_params *params;
1017
1018                 nme = midend_new(NULL, fe->game, NULL, NULL);
1019
1020                 /*
1021                  * Set the non-interactive mid-end to have the same
1022                  * parameters as the standard one.
1023                  */
1024                 params = midend_get_params(fe->me);
1025                 midend_set_params(nme, params);
1026                 fe->game->free_params(params);
1027             }
1028
1029             midend_new_game(nme);
1030             err = midend_print_puzzle(nme, doc, fe->printsolns);
1031         }
1032         if (err)
1033             break;
1034     }
1035     if (nme)
1036         midend_free(nme);
1037
1038     if (err) {
1039         MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
1040                    MB_ICONERROR | MB_OK);
1041         document_free(doc);
1042         return;
1043     }
1044
1045     memset(&pd, 0, sizeof(pd));
1046     pd.lStructSize = sizeof(pd);
1047     pd.hwndOwner = fe->hwnd;
1048     pd.hDevMode = NULL;
1049     pd.hDevNames = NULL;
1050     pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
1051         PD_NOPAGENUMS | PD_NOSELECTION;
1052     pd.nCopies = 1;
1053     pd.nFromPage = pd.nToPage = 0xFFFF;
1054     pd.nMinPage = pd.nMaxPage = 1;
1055
1056     if (!PrintDlg(&pd)) {
1057         document_free(doc);
1058         return;
1059     }
1060
1061     /*
1062      * Now pd.hDC is a device context for the printer.
1063      */
1064
1065     /*
1066      * FIXME: IWBNI we put up an Abort box here.
1067      */
1068
1069     memset(&fe->di, 0, sizeof(fe->di));
1070     fe->di.cbSize = sizeof(fe->di);
1071     sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
1072             " Portable Puzzle Collection)", fe->game->name);
1073     fe->di.lpszDocName = doctitle;
1074     fe->di.lpszOutput = NULL;
1075     fe->di.lpszDatatype = NULL;
1076     fe->di.fwType = 0;
1077
1078     fe->drawstatus = PRINTING;
1079     fe->hdc = pd.hDC;
1080
1081     fe->dr = drawing_new(&win_drawing, NULL, fe);
1082     document_print(doc, fe->dr);
1083     drawing_free(fe->dr);
1084     fe->dr = NULL;
1085
1086     fe->drawstatus = NOTHING;
1087
1088     DeleteDC(pd.hDC);
1089     document_free(doc);
1090 #endif
1091 }
1092
1093 void deactivate_timer(frontend *fe)
1094 {
1095     if (!fe)
1096         return;                        /* for non-interactive midend */
1097     if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
1098     fe->timer = 0;
1099 }
1100
1101 void activate_timer(frontend *fe)
1102 {
1103     if (!fe)
1104         return;                        /* for non-interactive midend */
1105     if (!fe->timer) {
1106         fe->timer = SetTimer(fe->hwnd, 1, 20, NULL);
1107         fe->timer_last_tickcount = GetTickCount();
1108     }
1109 }
1110
1111 void write_clip(HWND hwnd, char *data)
1112 {
1113     HGLOBAL clipdata;
1114     int len, i, j;
1115     char *data2;
1116     void *lock;
1117
1118     /*
1119      * Windows expects CRLF in the clipboard, so we must convert
1120      * any \n that has come out of the puzzle backend.
1121      */
1122     len = 0;
1123     for (i = 0; data[i]; i++) {
1124         if (data[i] == '\n')
1125             len++;
1126         len++;
1127     }
1128     data2 = snewn(len+1, char);
1129     j = 0;
1130     for (i = 0; data[i]; i++) {
1131         if (data[i] == '\n')
1132             data2[j++] = '\r';
1133         data2[j++] = data[i];
1134     }
1135     assert(j == len);
1136     data2[j] = '\0';
1137
1138     clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
1139     if (!clipdata) {
1140         sfree(data2);
1141         return;
1142     }
1143     lock = GlobalLock(clipdata);
1144     if (!lock) {
1145         GlobalFree(clipdata);
1146         sfree(data2);
1147         return;
1148     }
1149     memcpy(lock, data2, len);
1150     ((unsigned char *) lock)[len] = 0;
1151     GlobalUnlock(clipdata);
1152
1153     if (OpenClipboard(hwnd)) {
1154         EmptyClipboard();
1155         SetClipboardData(CF_TEXT, clipdata);
1156         CloseClipboard();
1157     } else
1158         GlobalFree(clipdata);
1159
1160     sfree(data2);
1161 }
1162
1163 /*
1164  * Set up Help and see if we can find a help file.
1165  */
1166 static void init_help(void)
1167 {
1168 #ifndef _WIN32_WCE
1169     char b[2048], *p, *q, *r;
1170     FILE *fp;
1171
1172     /*
1173      * Find the executable file path, so we can look alongside
1174      * it for help files. Trim the filename off the end.
1175      */
1176     GetModuleFileName(NULL, b, sizeof(b) - 1);
1177     r = b;
1178     p = strrchr(b, '\\');
1179     if (p && p >= r) r = p+1;
1180     q = strrchr(b, ':');
1181     if (q && q >= r) r = q+1;
1182
1183 #ifndef NO_HTMLHELP
1184     /*
1185      * Try HTML Help first.
1186      */
1187     strcpy(r, CHM_FILE_NAME);
1188     if ( (fp = fopen(b, "r")) != NULL) {
1189         fclose(fp);
1190
1191         /*
1192          * We have a .CHM. See if we can use it.
1193          */
1194         hh_dll = LoadLibrary("hhctrl.ocx");
1195         if (hh_dll) {
1196             htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
1197             if (!htmlhelp)
1198                 FreeLibrary(hh_dll);
1199         }
1200         if (htmlhelp) {
1201             help_path = dupstr(b);
1202             help_type = CHM;
1203             return;
1204         }
1205     }
1206 #endif /* NO_HTMLHELP */
1207
1208     /*
1209      * Now try old-style .HLP.
1210      */
1211     strcpy(r, HELP_FILE_NAME);
1212     if ( (fp = fopen(b, "r")) != NULL) {
1213         fclose(fp);
1214
1215         help_path = dupstr(b);
1216         help_type = HLP;
1217
1218         /*
1219          * See if there's a .CNT file alongside it.
1220          */
1221         strcpy(r, HELP_CNT_NAME);
1222         if ( (fp = fopen(b, "r")) != NULL) {
1223             fclose(fp);
1224             help_has_contents = TRUE;
1225         } else
1226             help_has_contents = FALSE;
1227
1228         return;
1229     }
1230
1231     help_type = NONE;          /* didn't find any */
1232 #endif
1233 }
1234
1235 #ifndef _WIN32_WCE
1236
1237 /*
1238  * Start Help.
1239  */
1240 static void start_help(frontend *fe, const char *topic)
1241 {
1242     char *str = NULL;
1243     int cmd;
1244
1245     switch (help_type) {
1246       case HLP:
1247         assert(help_path);
1248         if (topic) {
1249             str = snewn(10+strlen(topic), char);
1250             sprintf(str, "JI(`',`%s')", topic);
1251             cmd = HELP_COMMAND;
1252         } else if (help_has_contents) {
1253             cmd = HELP_FINDER;
1254         } else {
1255             cmd = HELP_CONTENTS;
1256         }
1257         WinHelp(fe->hwnd, help_path, cmd, (DWORD)str);
1258         fe->help_running = TRUE;
1259         break;
1260       case CHM:
1261 #ifndef NO_HTMLHELP
1262         assert(help_path);
1263         assert(htmlhelp);
1264         if (topic) {
1265             str = snewn(20 + strlen(topic) + strlen(help_path), char);
1266             sprintf(str, "%s::/%s.html>main", help_path, topic);
1267         } else {
1268             str = dupstr(help_path);
1269         }
1270         htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
1271         fe->help_running = TRUE;
1272         break;
1273 #endif /* NO_HTMLHELP */
1274       case NONE:
1275         assert(!"This shouldn't happen");
1276         break;
1277     }
1278
1279     sfree(str);
1280 }
1281
1282 /*
1283  * Stop Help on window cleanup.
1284  */
1285 static void stop_help(frontend *fe)
1286 {
1287     if (fe->help_running) {
1288         switch (help_type) {
1289           case HLP:
1290             WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
1291             break;
1292           case CHM:
1293 #ifndef NO_HTMLHELP
1294             assert(htmlhelp);
1295             htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
1296             break;
1297 #endif /* NO_HTMLHELP */
1298           case NONE:
1299             assert(!"This shouldn't happen");
1300             break;
1301         }
1302         fe->help_running = FALSE;
1303     }
1304 }
1305
1306 #endif
1307
1308 /*
1309  * Terminate Help on process exit.
1310  */
1311 static void cleanup_help(void)
1312 {
1313     /* Nothing to do currently.
1314      * (If we were running HTML Help single-threaded, this is where we'd
1315      * call HH_UNINITIALIZE.) */
1316 }
1317
1318 static int get_statusbar_height(frontend *fe)
1319 {
1320     int sy;
1321     if (fe->statusbar) {
1322         RECT sr;
1323         GetWindowRect(fe->statusbar, &sr);
1324         sy = sr.bottom - sr.top;
1325     } else {
1326         sy = 0;
1327     }
1328     return sy;
1329 }
1330
1331 static void adjust_statusbar(frontend *fe, RECT *r)
1332 {
1333     int sy;
1334
1335     if (!fe->statusbar) return;
1336
1337     sy = get_statusbar_height(fe);
1338 #ifndef _WIN32_WCE
1339     SetWindowPos(fe->statusbar, NULL, 0, r->bottom-r->top-sy, r->right-r->left,
1340                  sy, SWP_NOZORDER);
1341 #endif
1342 }
1343
1344 static void get_menu_size(HWND wh, RECT *r)
1345 {
1346     HMENU bar = GetMenu(wh);
1347     RECT rect;
1348     int i;
1349
1350     SetRect(r, 0, 0, 0, 0);
1351     for (i = 0; i < GetMenuItemCount(bar); i++) {
1352         GetMenuItemRect(wh, bar, i, &rect);
1353         UnionRect(r, r, &rect);
1354     }
1355 }
1356
1357 /*
1358  * Given a proposed new puzzle size (cx,cy), work out the actual
1359  * puzzle size that would be (px,py) and the window size including
1360  * furniture (wx,wy).
1361  */
1362
1363 static int check_window_resize(frontend *fe, int cx, int cy,
1364                                int *px, int *py,
1365                                int *wx, int *wy)
1366 {
1367     RECT r;
1368     int x, y, sy = get_statusbar_height(fe), changed = 0;
1369
1370     /* disallow making window thinner than menu bar */
1371     x = max(cx, fe->xmin);
1372     y = max(cy - sy, fe->ymin);
1373
1374     /*
1375      * See if we actually got the window size we wanted, and adjust
1376      * the puzzle size if not.
1377      */
1378     midend_size(fe->me, &x, &y, TRUE);
1379     if (x != cx || y != cy) {
1380         /*
1381          * Resize the window, now we know what size we _really_
1382          * want it to be.
1383          */
1384         r.left = r.top = 0;
1385         r.right = x;
1386         r.bottom = y + sy;
1387         AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1388         *wx = r.right - r.left;
1389         *wy = r.bottom - r.top;
1390         changed = 1;
1391     }
1392
1393     *px = x;
1394     *py = y;
1395
1396     fe->puzz_scale =
1397       (float)midend_tilesize(fe->me) / (float)fe->game->preferred_tilesize;
1398
1399     return changed;
1400 }
1401
1402 /*
1403  * Given the current window size, make sure it's sane for the
1404  * current puzzle and resize if necessary.
1405  */
1406
1407 static void check_window_size(frontend *fe, int *px, int *py)
1408 {
1409     RECT r;
1410     int wx, wy, cx, cy;
1411
1412     GetClientRect(fe->hwnd, &r);
1413     cx = r.right - r.left;
1414     cy = r.bottom - r.top;
1415
1416     if (check_window_resize(fe, cx, cy, px, py, &wx, &wy)) {
1417 #ifdef _WIN32_WCE
1418         SetWindowPos(fe->hwnd, NULL, 0, 0, wx, wy,
1419                      SWP_NOMOVE | SWP_NOZORDER);
1420 #endif
1421         ;
1422     }
1423
1424     GetClientRect(fe->hwnd, &r);
1425     adjust_statusbar(fe, &r);
1426 }
1427
1428 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1429 {
1430     RECT r, sr;
1431
1432     if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1433         *x = sr.right - sr.left;
1434         *y = sr.bottom - sr.top;
1435         r.left = 100;
1436         r.right = 200;
1437         r.top = 100;
1438         r.bottom = 200;
1439         AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1440         *x -= r.right - r.left - 100;
1441         *y -= r.bottom - r.top - 100;
1442     } else {
1443         *x = *y = INT_MAX;
1444     }
1445
1446     if (fe->statusbar != NULL) {
1447         GetWindowRect(fe->statusbar, &sr);
1448         *y -= sr.bottom - sr.top;
1449     }
1450 }
1451
1452 #ifdef _WIN32_WCE
1453 /* Toolbar buttons on the numeric pad */
1454 static TBBUTTON tbNumpadButtons[] =
1455 {
1456     {0, IDM_KEYEMUL + '1', TBSTATE_ENABLED, TBSTYLE_BUTTON,  0, -1},
1457     {1, IDM_KEYEMUL + '2', TBSTATE_ENABLED, TBSTYLE_BUTTON,  0, -1},
1458     {2, IDM_KEYEMUL + '3', TBSTATE_ENABLED, TBSTYLE_BUTTON,  0, -1},
1459     {3, IDM_KEYEMUL + '4', TBSTATE_ENABLED, TBSTYLE_BUTTON,  0, -1},
1460     {4, IDM_KEYEMUL + '5', TBSTATE_ENABLED, TBSTYLE_BUTTON,  0, -1},
1461     {5, IDM_KEYEMUL + '6', TBSTATE_ENABLED, TBSTYLE_BUTTON,  0, -1},
1462     {6, IDM_KEYEMUL + '7', TBSTATE_ENABLED, TBSTYLE_BUTTON,  0, -1},
1463     {7, IDM_KEYEMUL + '8', TBSTATE_ENABLED, TBSTYLE_BUTTON,  0, -1},
1464     {8, IDM_KEYEMUL + '9', TBSTATE_ENABLED, TBSTYLE_BUTTON,  0, -1},
1465     {9, IDM_KEYEMUL + ' ', TBSTATE_ENABLED, TBSTYLE_BUTTON,  0, -1}
1466 };
1467 #endif
1468
1469 /*
1470  * Allocate a new frontend structure and create its main window.
1471  */
1472 static frontend *frontend_new(HINSTANCE inst)
1473 {
1474     frontend *fe;
1475     const char *nogame = "Puzzles (no game selected)";
1476
1477     fe = snew(frontend);
1478
1479     fe->inst = inst;
1480
1481     fe->game = NULL;
1482     fe->me = NULL;
1483
1484     fe->timer = 0;
1485     fe->hwnd = NULL;
1486
1487     fe->help_running = FALSE;
1488
1489     fe->drawstatus = NOTHING;
1490     fe->dr = NULL;
1491     fe->fontstart = 0;
1492
1493     fe->fonts = NULL;
1494     fe->nfonts = fe->fontsize = 0;
1495
1496     fe->colours = NULL;
1497     fe->brushes = NULL;
1498     fe->pens = NULL;
1499
1500     fe->puzz_scale = 1.0;
1501
1502     #ifdef _WIN32_WCE
1503     MultiByteToWideChar (CP_ACP, 0, nogame, -1, wGameName, 256);
1504     fe->hwnd = CreateWindowEx(0, wClassName, wGameName,
1505                               WS_VISIBLE,
1506                               CW_USEDEFAULT, CW_USEDEFAULT,
1507                               CW_USEDEFAULT, CW_USEDEFAULT,
1508                               NULL, NULL, inst, NULL);
1509
1510     {
1511         SHMENUBARINFO mbi;
1512         RECT rc, rcBar, rcTB, rcClient;
1513
1514         memset (&mbi, 0, sizeof(SHMENUBARINFO));
1515         mbi.cbSize     = sizeof(SHMENUBARINFO);
1516         mbi.hwndParent = fe->hwnd;
1517         mbi.nToolBarId = IDR_MENUBAR1;
1518         mbi.hInstRes   = inst;
1519
1520         SHCreateMenuBar(&mbi);
1521
1522         GetWindowRect(fe->hwnd, &rc);
1523         GetWindowRect(mbi.hwndMB, &rcBar);
1524         rc.bottom -= rcBar.bottom - rcBar.top;
1525         MoveWindow(fe->hwnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, FALSE);
1526
1527         fe->numpad = NULL;
1528     }
1529 #else
1530     fe->hwnd = CreateWindowEx(0, CLASSNAME, nogame,
1531                               WS_OVERLAPPEDWINDOW &~
1532                               (WS_MAXIMIZEBOX),
1533                               CW_USEDEFAULT, CW_USEDEFAULT,
1534                               CW_USEDEFAULT, CW_USEDEFAULT,
1535                               NULL, NULL, inst, NULL);
1536     if (!fe->hwnd) {
1537         DWORD lerr = GetLastError();
1538         printf("no window: 0x%x\n", (unsigned)lerr);
1539     }
1540 #endif
1541
1542     fe->gamemenu = NULL;
1543     fe->preset_menu = NULL;
1544
1545     fe->statusbar = NULL;
1546     fe->bitmap = NULL;
1547
1548     SetWindowLongPtr(fe->hwnd, GWLP_USERDATA, (LONG_PTR)fe);
1549
1550     return fe;
1551 }
1552
1553 static void savefile_write(void *wctx, void *buf, int len)
1554 {
1555     FILE *fp = (FILE *)wctx;
1556     fwrite(buf, 1, len, fp);
1557 }
1558
1559 static int savefile_read(void *wctx, void *buf, int len)
1560 {
1561     FILE *fp = (FILE *)wctx;
1562     int ret;
1563
1564     ret = fread(buf, 1, len, fp);
1565     return (ret == len);
1566 }
1567
1568 /*
1569  * Create an appropriate midend structure to go in a puzzle window,
1570  * given a game type and/or a command-line argument.
1571  *
1572  * 'arg' can be either a game ID string (descriptive, random, or a
1573  * plain set of parameters) or the filename of a save file. The two
1574  * boolean flag arguments indicate which possibilities are
1575  * permissible.
1576  */
1577 static midend *midend_for_new_game(frontend *fe, const game *cgame,
1578                                    char *arg, int maybe_game_id,
1579                                    int maybe_save_file, char **error)
1580 {
1581     midend *me = NULL;
1582
1583     if (!arg) {
1584         if (me) midend_free(me);
1585         me = midend_new(fe, cgame, &win_drawing, fe);
1586         midend_new_game(me);
1587     } else {
1588         FILE *fp;
1589         char *err_param, *err_load;
1590
1591         /*
1592          * See if arg is a valid filename of a save game file.
1593          */
1594         err_load = NULL;
1595         if (maybe_save_file && (fp = fopen(arg, "r")) != NULL) {
1596             const game *loadgame;
1597
1598 #ifdef COMBINED
1599             /*
1600              * Find out what kind of game is stored in the save
1601              * file; if we're going to end up loading that, it
1602              * will have to override our caller's judgment as to
1603              * what game to initialise our midend with.
1604              */
1605             char *id_name;
1606             err_load = identify_game(&id_name, savefile_read, fp);
1607             if (!err_load) {
1608                 int i;
1609                 for (i = 0; i < gamecount; i++)
1610                     if (!strcmp(id_name, gamelist[i]->name))
1611                         break;
1612                 if (i == gamecount) {
1613                     err_load = "Save file is for a game not supported by"
1614                         " this program";
1615                 } else {
1616                     loadgame = gamelist[i];
1617                     rewind(fp); /* go back to the start for actual load */
1618                 }
1619             }
1620 #else
1621             loadgame = cgame;
1622 #endif
1623             if (!err_load) {
1624                 if (me) midend_free(me);
1625                 me = midend_new(fe, loadgame, &win_drawing, fe);
1626                 err_load = midend_deserialise(me, savefile_read, fp);
1627             }
1628         } else {
1629             err_load = "Unable to open file";
1630         }
1631
1632         if (maybe_game_id && (!maybe_save_file || err_load)) {
1633             /*
1634              * See if arg is a game description.
1635              */
1636             if (me) midend_free(me);
1637             me = midend_new(fe, cgame, &win_drawing, fe);
1638             err_param = midend_game_id(me, arg);
1639             if (!err_param) {
1640                 midend_new_game(me);
1641             } else {
1642                 if (maybe_save_file) {
1643                     *error = snewn(256 + strlen(arg) + strlen(err_param) +
1644                                    strlen(err_load), char);
1645                     sprintf(*error, "Supplied argument \"%s\" is neither a"
1646                             " game ID (%s) nor a save file (%s)",
1647                             arg, err_param, err_load);
1648                 } else {
1649                     *error = dupstr(err_param);
1650                 }
1651                 midend_free(me);
1652                 sfree(fe);
1653                 return NULL;
1654             }
1655         } else if (err_load) {
1656             *error = dupstr(err_load);
1657             midend_free(me);
1658             sfree(fe);
1659             return NULL;
1660         }
1661     }
1662
1663     return me;
1664 }
1665
1666 static void populate_preset_menu(frontend *fe,
1667                                  struct preset_menu *menu, HMENU winmenu)
1668 {
1669     int i;
1670     for (i = 0; i < menu->n_entries; i++) {
1671         struct preset_menu_entry *entry = &menu->entries[i];
1672         UINT_PTR id_or_sub;
1673         UINT flags = MF_ENABLED;
1674
1675         if (entry->params) {
1676             id_or_sub = (UINT_PTR)(IDM_PRESETS + 0x10 * entry->id);
1677
1678             fe->preset_menuitems[entry->id].which_menu = winmenu;
1679             fe->preset_menuitems[entry->id].item_index =
1680                 GetMenuItemCount(winmenu);
1681         } else {
1682             HMENU winsubmenu = CreateMenu();
1683             id_or_sub = (UINT_PTR)winsubmenu;
1684             flags |= MF_POPUP;
1685
1686             populate_preset_menu(fe, entry->submenu, winsubmenu);
1687         }
1688
1689         /*
1690          * FIXME: we ought to go through and do something with ampersands
1691          * here.
1692          */
1693
1694 #ifndef _WIN32_WCE
1695         AppendMenu(winmenu, flags, id_or_sub, entry->title);
1696 #else
1697         {
1698             TCHAR wName[255];
1699             MultiByteToWideChar(CP_ACP, 0, entry->title, -1, wName, 255);
1700             AppendMenu(winmenu, flags, id_or_sub, wName);
1701         }
1702 #endif
1703     }
1704 }
1705
1706 /*
1707  * Populate a frontend structure with a new midend structure, and
1708  * create any window furniture that it needs.
1709  *
1710  * Previously-allocated memory and window furniture will be freed by
1711  * this function.
1712  *
1713  */
1714 static int fe_set_midend(frontend *fe, midend *me)
1715 {
1716     int x, y;
1717     RECT r;
1718
1719     if (fe->me) midend_free(fe->me);
1720     fe->me = me;
1721     fe->game = midend_which_game(fe->me);
1722
1723     {
1724         int i, ncolours;
1725         float *colours;
1726
1727         colours = midend_colours(fe->me, &ncolours);
1728
1729         if (fe->colours) sfree(fe->colours);
1730         if (fe->brushes) sfree(fe->brushes);
1731         if (fe->pens) sfree(fe->pens);
1732
1733         fe->colours = snewn(ncolours, COLORREF);
1734         fe->brushes = snewn(ncolours, HBRUSH);
1735         fe->pens = snewn(ncolours, HPEN);
1736
1737         for (i = 0; i < ncolours; i++) {
1738             fe->colours[i] = RGB(255 * colours[i*3+0],
1739                                  255 * colours[i*3+1],
1740                                  255 * colours[i*3+2]);
1741             fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1742             fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1743         }
1744         sfree(colours);
1745     }
1746
1747     if (fe->statusbar)
1748         DestroyWindow(fe->statusbar);
1749     if (midend_wants_statusbar(fe->me)) {
1750         fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME,
1751                                        TEXT(DEFAULT_STATUSBAR_TEXT),
1752                                        WS_CHILD | WS_VISIBLE,
1753                                        0, 0, 0, 0, /* status bar does these */
1754                                        NULL, NULL, fe->inst, NULL);
1755     } else
1756         fe->statusbar = NULL;
1757
1758     get_max_puzzle_size(fe, &x, &y);
1759     midend_size(fe->me, &x, &y, FALSE);
1760
1761     r.left = r.top = 0;
1762     r.right = x;
1763     r.bottom = y;
1764     AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1765
1766 #ifdef _WIN32_WCE
1767     if (fe->numpad)
1768         DestroyWindow(fe->numpad);
1769     if (fe->game->flags & REQUIRE_NUMPAD)
1770     {
1771         fe->numpad = CreateToolbarEx (fe->hwnd,
1772                                       WS_VISIBLE | WS_CHILD | CCS_NOPARENTALIGN | TBSTYLE_FLAT,
1773                                       0, 10, fe->inst, IDR_PADTOOLBAR,
1774                                       tbNumpadButtons, sizeof (tbNumpadButtons) / sizeof (TBBUTTON),
1775                                       0, 0, 14, 15, sizeof (TBBUTTON));
1776         GetWindowRect(fe->numpad, &rcTB);
1777         GetClientRect(fe->hwnd, &rcClient);
1778         MoveWindow(fe->numpad, 
1779                    0, 
1780                    rcClient.bottom - (rcTB.bottom - rcTB.top) - 1,
1781                    rcClient.right,
1782                    rcTB.bottom - rcTB.top,
1783                    FALSE);
1784         SendMessage(fe->numpad, TB_SETINDENT, (rcClient.right - (10 * 21)) / 2, 0);
1785     }
1786     else {
1787         fe->numpad = NULL;
1788     }
1789     MultiByteToWideChar (CP_ACP, 0, fe->game->name, -1, wGameName, 256);
1790     SetWindowText(fe->hwnd, wGameName);
1791 #else
1792     SetWindowText(fe->hwnd, fe->game->name);
1793 #endif
1794
1795     if (fe->statusbar)
1796         DestroyWindow(fe->statusbar);
1797     if (midend_wants_statusbar(fe->me)) {
1798         RECT sr;
1799         fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1800                                        WS_CHILD | WS_VISIBLE,
1801                                        0, 0, 0, 0, /* status bar does these */
1802                                        fe->hwnd, NULL, fe->inst, NULL);
1803 #ifdef _WIN32_WCE
1804         /* Flat status bar looks better on the Pocket PC */
1805         SendMessage(fe->statusbar, SB_SIMPLE, (WPARAM) TRUE, 0);
1806         SendMessage(fe->statusbar, SB_SETTEXT,
1807                                 (WPARAM) 255 | SBT_NOBORDERS,
1808                                 (LPARAM) L"");
1809 #endif
1810
1811         /*
1812          * Now resize the window to take account of the status bar.
1813          */
1814         GetWindowRect(fe->statusbar, &sr);
1815         GetWindowRect(fe->hwnd, &r);
1816 #ifndef _WIN32_WCE
1817         SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1818                      r.bottom - r.top + sr.bottom - sr.top,
1819                      SWP_NOMOVE | SWP_NOZORDER);
1820 #endif
1821     } else {
1822         fe->statusbar = NULL;
1823     }
1824
1825     {
1826         HMENU oldmenu = GetMenu(fe->hwnd);
1827
1828 #ifndef _WIN32_WCE
1829         HMENU bar = CreateMenu();
1830         HMENU menu = CreateMenu();
1831         RECT menusize;
1832
1833         AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "&Game");
1834 #else
1835         HMENU menu = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_GAME);
1836         DeleteMenu(menu, 0, MF_BYPOSITION);
1837 #endif
1838         fe->gamemenu = menu;
1839         AppendMenu(menu, MF_ENABLED, IDM_NEW, TEXT("&New"));
1840         AppendMenu(menu, MF_ENABLED, IDM_RESTART, TEXT("&Restart"));
1841 #ifndef _WIN32_WCE
1842         /* ...here I run out of sensible accelerator characters. */
1843         AppendMenu(menu, MF_ENABLED, IDM_DESC, TEXT("Speci&fic..."));
1844         AppendMenu(menu, MF_ENABLED, IDM_SEED, TEXT("Rando&m Seed..."));
1845 #endif
1846
1847         if (!fe->preset_menu) {
1848             int i;
1849             fe->preset_menu = midend_get_presets(
1850                 fe->me, &fe->n_preset_menuitems);
1851             fe->preset_menuitems = snewn(fe->n_preset_menuitems,
1852                                          struct preset_menuitemref);
1853             for (i = 0; i < fe->n_preset_menuitems; i++)
1854                 fe->preset_menuitems[i].which_menu = NULL;
1855         }
1856         if (fe->preset_menu->n_entries > 0 || fe->game->can_configure) {
1857 #ifndef _WIN32_WCE
1858             HMENU sub = CreateMenu();
1859
1860             AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "&Type");
1861 #else
1862             HMENU sub = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_TYPE);
1863             DeleteMenu(sub, 0, MF_BYPOSITION);
1864 #endif
1865
1866             populate_preset_menu(fe, fe->preset_menu, sub);
1867
1868             if (fe->game->can_configure) {
1869                 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, TEXT("&Custom..."));
1870             }
1871
1872             fe->typemenu = sub;
1873         } else {
1874             fe->typemenu = INVALID_HANDLE_VALUE;
1875         }
1876
1877 #ifdef COMBINED
1878 #ifdef _WIN32_WCE
1879 #error Windows CE does not support COMBINED build.
1880 #endif
1881         {
1882             HMENU games = CreateMenu();
1883             int i;
1884
1885             AppendMenu(menu, MF_SEPARATOR, 0, 0);
1886             AppendMenu(menu, MF_ENABLED|MF_POPUP, (UINT)games, "&Other");
1887             for (i = 0; i < gamecount; i++) {
1888                 if (strcmp(gamelist[i]->name, fe->game->name) != 0) {
1889                     /* only include those games that aren't the same as the
1890                      * game we're currently playing. */
1891                     AppendMenu(games, MF_ENABLED, IDM_GAMES + i, gamelist[i]->name);
1892                 }
1893             }
1894         }
1895 #endif
1896
1897         AppendMenu(menu, MF_SEPARATOR, 0, 0);
1898 #ifndef _WIN32_WCE
1899         AppendMenu(menu, MF_ENABLED, IDM_LOAD, TEXT("&Load..."));
1900         AppendMenu(menu, MF_ENABLED, IDM_SAVE, TEXT("&Save..."));
1901         AppendMenu(menu, MF_SEPARATOR, 0, 0);
1902         if (fe->game->can_print) {
1903             AppendMenu(menu, MF_ENABLED, IDM_PRINT, TEXT("&Print..."));
1904             AppendMenu(menu, MF_SEPARATOR, 0, 0);
1905         }
1906 #endif
1907         AppendMenu(menu, MF_ENABLED, IDM_UNDO, TEXT("Undo"));
1908         AppendMenu(menu, MF_ENABLED, IDM_REDO, TEXT("Redo"));
1909 #ifndef _WIN32_WCE
1910         if (fe->game->can_format_as_text_ever) {
1911             AppendMenu(menu, MF_SEPARATOR, 0, 0);
1912             AppendMenu(menu, MF_ENABLED, IDM_COPY, TEXT("&Copy"));
1913         }
1914 #endif
1915         if (fe->game->can_solve) {
1916             AppendMenu(menu, MF_SEPARATOR, 0, 0);
1917             AppendMenu(menu, MF_ENABLED, IDM_SOLVE, TEXT("Sol&ve"));
1918         }
1919         AppendMenu(menu, MF_SEPARATOR, 0, 0);
1920 #ifndef _WIN32_WCE
1921         AppendMenu(menu, MF_ENABLED, IDM_QUIT, TEXT("E&xit"));
1922         menu = CreateMenu();
1923         AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, TEXT("&Help"));
1924 #endif
1925         AppendMenu(menu, MF_ENABLED, IDM_ABOUT, TEXT("&About"));
1926 #ifndef _WIN32_WCE
1927         if (help_type != NONE) {
1928             char *item;
1929             AppendMenu(menu, MF_SEPARATOR, 0, 0);
1930             AppendMenu(menu, MF_ENABLED, IDM_HELPC, TEXT("&Contents"));
1931             assert(fe->game->name);
1932             item = snewn(10+strlen(fe->game->name), char); /*ick*/
1933             sprintf(item, "&Help on %s", fe->game->name);
1934             AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1935             sfree(item);
1936         }
1937         DestroyMenu(oldmenu);
1938         SetMenu(fe->hwnd, bar);
1939         get_menu_size(fe->hwnd, &menusize);
1940         fe->xmin = (menusize.right - menusize.left) + 25;
1941 #endif
1942     }
1943
1944     if (fe->bitmap) DeleteObject(fe->bitmap);
1945     fe->bitmap = NULL;
1946     new_game_size(fe, fe->puzz_scale); /* initialises fe->bitmap */
1947
1948     return 0;
1949 }
1950
1951 static void show_window(frontend *fe)
1952 {
1953     ShowWindow(fe->hwnd, SW_SHOWNORMAL);
1954     SetForegroundWindow(fe->hwnd);
1955
1956     update_type_menu_tick(fe);
1957     update_copy_menu_greying(fe);
1958
1959     midend_redraw(fe->me);
1960 }
1961
1962 #ifdef _WIN32_WCE
1963 static HFONT dialog_title_font()
1964 {
1965     static HFONT hf = NULL;
1966     LOGFONT lf;
1967
1968     if (hf)
1969         return hf;
1970
1971     memset (&lf, 0, sizeof(LOGFONT));
1972     lf.lfHeight = -11; /* - ((8 * GetDeviceCaps(hdc, LOGPIXELSY)) / 72) */
1973     lf.lfWeight = FW_BOLD;
1974     wcscpy(lf.lfFaceName, TEXT("Tahoma"));
1975
1976     return hf = CreateFontIndirect(&lf);
1977 }
1978
1979 static void make_dialog_full_screen(HWND hwnd)
1980 {
1981     SHINITDLGINFO shidi;
1982
1983     /* Make dialog full screen */
1984     shidi.dwMask = SHIDIM_FLAGS;
1985     shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIZEDLGFULLSCREEN |
1986                     SHIDIF_EMPTYMENU;
1987     shidi.hDlg = hwnd;
1988     SHInitDialog(&shidi);
1989 }
1990 #endif
1991
1992 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1993                                  WPARAM wParam, LPARAM lParam)
1994 {
1995     frontend *fe = (frontend *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
1996
1997     switch (msg) {
1998       case WM_INITDIALOG:
1999 #ifdef _WIN32_WCE
2000         {
2001             char title[256];
2002
2003             make_dialog_full_screen(hwnd);
2004
2005             sprintf(title, "About %.250s", fe->game->name);
2006             SetDlgItemTextA(hwnd, IDC_ABOUT_CAPTION, title);
2007
2008             SendDlgItemMessage(hwnd, IDC_ABOUT_CAPTION, WM_SETFONT,
2009                                (WPARAM) dialog_title_font(), 0);
2010
2011             SetDlgItemTextA(hwnd, IDC_ABOUT_GAME, fe->game->name);
2012             SetDlgItemTextA(hwnd, IDC_ABOUT_VERSION, ver);
2013         }
2014 #endif
2015         return TRUE;
2016
2017       case WM_COMMAND:
2018         if (LOWORD(wParam) == IDOK)
2019 #ifdef _WIN32_WCE
2020             EndDialog(hwnd, 1);
2021 #else
2022             fe->dlg_done = 1;
2023 #endif
2024         return 0;
2025
2026       case WM_CLOSE:
2027 #ifdef _WIN32_WCE
2028         EndDialog(hwnd, 1);
2029 #else
2030         fe->dlg_done = 1;
2031 #endif
2032         return 0;
2033     }
2034
2035     return 0;
2036 }
2037
2038 /*
2039  * Wrappers on midend_{get,set}_config, which extend the CFG_*
2040  * enumeration to add CFG_PRINT.
2041  */
2042 static config_item *frontend_get_config(frontend *fe, int which,
2043                                         char **wintitle)
2044 {
2045     if (which < CFG_FRONTEND_SPECIFIC) {
2046         return midend_get_config(fe->me, which, wintitle);
2047     } else if (which == CFG_PRINT) {
2048         config_item *ret;
2049         int i;
2050
2051         *wintitle = snewn(40 + strlen(fe->game->name), char);
2052         sprintf(*wintitle, "%s print setup", fe->game->name);
2053
2054         ret = snewn(8, config_item);
2055
2056         i = 0;
2057
2058         ret[i].name = "Number of puzzles to print";
2059         ret[i].type = C_STRING;
2060         ret[i].sval = dupstr("1");
2061         ret[i].ival = 0;
2062         i++;
2063
2064         ret[i].name = "Number of puzzles across the page";
2065         ret[i].type = C_STRING;
2066         ret[i].sval = dupstr("1");
2067         ret[i].ival = 0;
2068         i++;
2069
2070         ret[i].name = "Number of puzzles down the page";
2071         ret[i].type = C_STRING;
2072         ret[i].sval = dupstr("1");
2073         ret[i].ival = 0;
2074         i++;
2075
2076         ret[i].name = "Percentage of standard size";
2077         ret[i].type = C_STRING;
2078         ret[i].sval = dupstr("100.0");
2079         ret[i].ival = 0;
2080         i++;
2081
2082         ret[i].name = "Include currently shown puzzle";
2083         ret[i].type = C_BOOLEAN;
2084         ret[i].sval = NULL;
2085         ret[i].ival = TRUE;
2086         i++;
2087
2088         ret[i].name = "Print solutions";
2089         ret[i].type = C_BOOLEAN;
2090         ret[i].sval = NULL;
2091         ret[i].ival = FALSE;
2092         i++;
2093
2094         if (fe->game->can_print_in_colour) {
2095             ret[i].name = "Print in colour";
2096             ret[i].type = C_BOOLEAN;
2097             ret[i].sval = NULL;
2098             ret[i].ival = FALSE;
2099             i++;
2100         }
2101
2102         ret[i].name = NULL;
2103         ret[i].type = C_END;
2104         ret[i].sval = NULL;
2105         ret[i].ival = 0;
2106         i++;
2107
2108         return ret;
2109     } else {
2110         assert(!"We should never get here");
2111         return NULL;
2112     }
2113 }
2114
2115 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
2116 {
2117     if (which < CFG_FRONTEND_SPECIFIC) {
2118         return midend_set_config(fe->me, which, cfg);
2119     } else if (which == CFG_PRINT) {
2120         if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
2121             return "Number of puzzles to print should be at least one";
2122         if ((fe->printw = atoi(cfg[1].sval)) <= 0)
2123             return "Number of puzzles across the page should be at least one";
2124         if ((fe->printh = atoi(cfg[2].sval)) <= 0)
2125             return "Number of puzzles down the page should be at least one";
2126         if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
2127             return "Print size should be positive";
2128         fe->printcurr = cfg[4].ival;
2129         fe->printsolns = cfg[5].ival;
2130         fe->printcolour = fe->game->can_print_in_colour && cfg[6].ival;
2131         return NULL;
2132     } else {
2133         assert(!"We should never get here");
2134         return "Internal error";
2135     }
2136 }
2137
2138 #ifdef _WIN32_WCE
2139 /* Separate version of mkctrl function for the Pocket PC. */
2140 /* Control coordinates should be specified in dialog units. */
2141 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2142             LPCTSTR wclass, int wstyle,
2143             int exstyle, const char *wtext, int wid)
2144 {
2145     RECT rc;
2146     TCHAR wwtext[256];
2147
2148     /* Convert dialog units into pixels */
2149     rc.left = x1;  rc.right  = x2;
2150     rc.top  = y1;  rc.bottom = y2;
2151     MapDialogRect(fe->cfgbox, &rc);
2152
2153     MultiByteToWideChar (CP_ACP, 0, wtext, -1, wwtext, 256);
2154
2155     return CreateWindowEx(exstyle, wclass, wwtext,
2156                           wstyle | WS_CHILD | WS_VISIBLE,
2157                           rc.left, rc.top,
2158                           rc.right - rc.left, rc.bottom - rc.top,
2159                           fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2160 }
2161
2162 static void create_config_controls(frontend * fe)
2163 {
2164     int id, nctrls;
2165     int col1l, col1r, col2l, col2r, y;
2166     config_item *i;
2167     struct cfg_aux *j;
2168     HWND ctl;
2169
2170     /* Control placement done in dialog units */
2171     col1l = 4;   col1r = 96;   /* Label column */
2172     col2l = 100; col2r = 154;  /* Input column (edit boxes and combo boxes) */
2173
2174     /*
2175      * Count the controls so we can allocate cfgaux.
2176      */
2177     for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2178         nctrls++;
2179     fe->cfgaux = snewn(nctrls, struct cfg_aux);
2180
2181     id = 1000;
2182     y = 22; /* Leave some room for the dialog title */
2183     for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2184         switch (i->type) {
2185           case C_STRING:
2186             /*
2187              * Edit box with a label beside it.
2188              */
2189             mkctrl(fe, col1l, col1r, y + 1, y + 11,
2190                    TEXT("Static"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
2191             mkctrl(fe, col2l, col2r, y, y + 12,
2192                    TEXT("EDIT"), WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
2193                    0, "", (j->ctlid = id++));
2194             SetDlgItemTextA(fe->cfgbox, j->ctlid, i->sval);
2195             break;
2196
2197           case C_BOOLEAN:
2198             /*
2199              * Simple checkbox.
2200              */
2201             mkctrl(fe, col1l, col2r, y + 1, y + 11, TEXT("BUTTON"),
2202                    BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2203                    0, i->name, (j->ctlid = id++));
2204             CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2205             break;
2206
2207           case C_CHOICES:
2208             /*
2209              * Drop-down list with a label beside it.
2210              */
2211             mkctrl(fe, col1l, col1r, y + 1, y + 11,
2212                    TEXT("STATIC"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
2213             ctl = mkctrl(fe, col2l, col2r, y, y + 48,
2214                          TEXT("COMBOBOX"), WS_BORDER | WS_TABSTOP |
2215                          CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2216                          0, "", (j->ctlid = id++));
2217             {
2218                 char c, *p, *q, *str;
2219
2220                 p = i->sval;
2221                 c = *p++;
2222                 while (*p) {
2223                     q = p;
2224                     while (*q && *q != c) q++;
2225                     str = snewn(q-p+1, char);
2226                     strncpy(str, p, q-p);
2227                     str[q-p] = '\0';
2228                     {
2229                         TCHAR ws[50];
2230                         MultiByteToWideChar (CP_ACP, 0, str, -1, ws, 50);
2231                         SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)ws);
2232                     }
2233                     
2234                     sfree(str);
2235                     if (*q) q++;
2236                     p = q;
2237                 }
2238             }
2239             SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2240             break;
2241         }
2242
2243         y += 15;
2244     }
2245
2246 }
2247 #endif
2248
2249 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
2250                                   WPARAM wParam, LPARAM lParam)
2251 {
2252     frontend *fe = (frontend *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
2253     config_item *i;
2254     struct cfg_aux *j;
2255
2256     switch (msg) {
2257       case WM_INITDIALOG:
2258 #ifdef _WIN32_WCE
2259         {
2260             char *title;
2261
2262             fe = (frontend *) lParam;
2263             SetWindowLongPtr(hwnd, GWLP_USERDATA, lParam);
2264             fe->cfgbox = hwnd;
2265
2266             fe->cfg = frontend_get_config(fe, fe->cfg_which, &title);
2267
2268             make_dialog_full_screen(hwnd);
2269
2270             SetDlgItemTextA(hwnd, IDC_CONFIG_CAPTION, title);
2271             SendDlgItemMessage(hwnd, IDC_CONFIG_CAPTION, WM_SETFONT,
2272                                (WPARAM) dialog_title_font(), 0);
2273
2274             create_config_controls(fe);
2275         }
2276 #endif
2277         return TRUE;
2278
2279       case WM_COMMAND:
2280         /*
2281          * OK and Cancel are special cases.
2282          */
2283         if ((LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
2284             if (LOWORD(wParam) == IDOK) {
2285                 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
2286
2287                 if (err) {
2288                     MessageBox(hwnd, err, "Validation error",
2289                                MB_ICONERROR | MB_OK);
2290                 } else {
2291 #ifdef _WIN32_WCE
2292                     EndDialog(hwnd, 2);
2293 #else
2294                     fe->dlg_done = 2;
2295 #endif
2296                 }
2297             } else {
2298 #ifdef _WIN32_WCE
2299                 EndDialog(hwnd, 1);
2300 #else
2301                 fe->dlg_done = 1;
2302 #endif
2303             }
2304             return 0;
2305         }
2306
2307         /*
2308          * First find the control whose id this is.
2309          */
2310         for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2311             if (j->ctlid == LOWORD(wParam))
2312                 break;
2313         }
2314         if (i->type == C_END)
2315             return 0;                  /* not our problem */
2316
2317         if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
2318             char buffer[4096];
2319 #ifdef _WIN32_WCE
2320             TCHAR wBuffer[4096];
2321             GetDlgItemText(fe->cfgbox, j->ctlid, wBuffer, 4096);
2322             WideCharToMultiByte(CP_ACP, 0, wBuffer, -1, buffer, 4096, NULL, NULL);
2323 #else
2324             GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
2325 #endif
2326             buffer[lenof(buffer)-1] = '\0';
2327             sfree(i->sval);
2328             i->sval = dupstr(buffer);
2329         } else if (i->type == C_BOOLEAN && 
2330                    (HIWORD(wParam) == BN_CLICKED ||
2331                     HIWORD(wParam) == BN_DBLCLK)) {
2332             i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
2333         } else if (i->type == C_CHOICES &&
2334                    HIWORD(wParam) == CBN_SELCHANGE) {
2335             i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
2336                                          CB_GETCURSEL, 0, 0);
2337         }
2338
2339         return 0;
2340
2341       case WM_CLOSE:
2342         fe->dlg_done = 1;
2343         return 0;
2344     }
2345
2346     return 0;
2347 }
2348
2349 #ifndef _WIN32_WCE
2350 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2351             char *wclass, int wstyle,
2352             int exstyle, const char *wtext, int wid)
2353 {
2354     HWND ret;
2355     ret = CreateWindowEx(exstyle, wclass, wtext,
2356                          wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
2357                          fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2358     SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
2359     return ret;
2360 }
2361 #endif
2362
2363 static void about(frontend *fe)
2364 {
2365 #ifdef _WIN32_WCE
2366     DialogBox(fe->inst, MAKEINTRESOURCE(IDD_ABOUT), fe->hwnd, AboutDlgProc);
2367 #else
2368     int i;
2369     WNDCLASS wc;
2370     MSG msg;
2371     TEXTMETRIC tm;
2372     HDC hdc;
2373     HFONT oldfont;
2374     SIZE size;
2375     int gm, id;
2376     int winwidth, winheight, y;
2377     int height, width, maxwid;
2378     const char *strings[16];
2379     int lengths[16];
2380     int nstrings = 0;
2381     char titlebuf[512];
2382
2383     sprintf(titlebuf, "About %.250s", fe->game->name);
2384
2385     strings[nstrings++] = fe->game->name;
2386     strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
2387     strings[nstrings++] = ver;
2388
2389     wc.style = CS_DBLCLKS | CS_SAVEBITS;
2390     wc.lpfnWndProc = DefDlgProc;
2391     wc.cbClsExtra = 0;
2392     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2393     wc.hInstance = fe->inst;
2394     wc.hIcon = NULL;
2395     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2396     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2397     wc.lpszMenuName = NULL;
2398     wc.lpszClassName = "GameAboutBox";
2399     RegisterClass(&wc);
2400
2401     hdc = GetDC(fe->hwnd);
2402     SetMapMode(hdc, MM_TEXT);
2403
2404     fe->dlg_done = FALSE;
2405
2406     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2407                              0, 0, 0, 0,
2408                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2409                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2410                              DEFAULT_QUALITY,
2411                              FF_SWISS,
2412                              "MS Shell Dlg");
2413
2414     oldfont = SelectObject(hdc, fe->cfgfont);
2415     if (GetTextMetrics(hdc, &tm)) {
2416         height = tm.tmAscent + tm.tmDescent;
2417         width = tm.tmAveCharWidth;
2418     } else {
2419         height = width = 30;
2420     }
2421
2422     /*
2423      * Figure out the layout of the About box by measuring the
2424      * length of each piece of text.
2425      */
2426     maxwid = 0;
2427     winheight = height/2;
2428
2429     for (i = 0; i < nstrings; i++) {
2430         if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
2431             lengths[i] = size.cx;
2432         else
2433             lengths[i] = 0;            /* *shrug* */
2434         if (maxwid < lengths[i])
2435             maxwid = lengths[i];
2436         winheight += height * 3 / 2 + (height / 2);
2437     }
2438
2439     winheight += height + height * 7 / 4;      /* OK button */
2440     winwidth = maxwid + 4*width;
2441
2442     SelectObject(hdc, oldfont);
2443     ReleaseDC(fe->hwnd, hdc);
2444
2445     /*
2446      * Create the dialog, now that we know its size.
2447      */
2448     {
2449         RECT r, r2;
2450
2451         r.left = r.top = 0;
2452         r.right = winwidth;
2453         r.bottom = winheight;
2454
2455         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2456                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2457                                 WS_CAPTION | WS_SYSMENU*/) &~
2458                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2459                            FALSE, 0);
2460
2461         /*
2462          * Centre the dialog on its parent window.
2463          */
2464         r.right -= r.left;
2465         r.bottom -= r.top;
2466         GetWindowRect(fe->hwnd, &r2);
2467         r.left = (r2.left + r2.right - r.right) / 2;
2468         r.top = (r2.top + r2.bottom - r.bottom) / 2;
2469         r.right += r.left;
2470         r.bottom += r.top;
2471
2472         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
2473                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2474                                     WS_CAPTION | WS_SYSMENU,
2475                                     r.left, r.top,
2476                                     r.right-r.left, r.bottom-r.top,
2477                                     fe->hwnd, NULL, fe->inst, NULL);
2478     }
2479
2480     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2481
2482     SetWindowLongPtr(fe->cfgbox, GWLP_USERDATA, (LONG_PTR)fe);
2483     SetWindowLongPtr(fe->cfgbox, DWLP_DLGPROC, (LONG_PTR)AboutDlgProc);
2484
2485     id = 1000;
2486     y = height/2;
2487     for (i = 0; i < nstrings; i++) {
2488         int border = width*2 + (maxwid - lengths[i]) / 2;
2489         mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
2490                "Static", 0, 0, strings[i], id++);
2491         y += height*3/2;
2492
2493         assert(y < winheight);
2494         y += height/2;
2495     }
2496
2497     y += height/2;                     /* extra space before OK */
2498     mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
2499            BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2500            "OK", IDOK);
2501
2502     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2503
2504     EnableWindow(fe->hwnd, FALSE);
2505     ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2506     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2507         if (!IsDialogMessage(fe->cfgbox, &msg))
2508             DispatchMessage(&msg);
2509         if (fe->dlg_done)
2510             break;
2511     }
2512     EnableWindow(fe->hwnd, TRUE);
2513     SetForegroundWindow(fe->hwnd);
2514     DestroyWindow(fe->cfgbox);
2515     DeleteObject(fe->cfgfont);
2516 #endif
2517 }
2518
2519 static int get_config(frontend *fe, int which)
2520 {
2521 #ifdef _WIN32_WCE
2522     fe->cfg_which = which;
2523
2524     return DialogBoxParam(fe->inst,
2525                           MAKEINTRESOURCE(IDD_CONFIG),
2526                           fe->hwnd, ConfigDlgProc,
2527                           (LPARAM) fe) == 2;
2528 #else
2529     config_item *i;
2530     struct cfg_aux *j;
2531     char *title;
2532     WNDCLASS wc;
2533     MSG msg;
2534     TEXTMETRIC tm;
2535     HDC hdc;
2536     HFONT oldfont;
2537     SIZE size;
2538     HWND ctl;
2539     int gm, id, nctrls;
2540     int winwidth, winheight, col1l, col1r, col2l, col2r, y;
2541     int height, width, maxlabel, maxcheckbox;
2542
2543     wc.style = CS_DBLCLKS | CS_SAVEBITS;
2544     wc.lpfnWndProc = DefDlgProc;
2545     wc.cbClsExtra = 0;
2546     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2547     wc.hInstance = fe->inst;
2548     wc.hIcon = NULL;
2549     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2550     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2551     wc.lpszMenuName = NULL;
2552     wc.lpszClassName = "GameConfigBox";
2553     RegisterClass(&wc);
2554
2555     hdc = GetDC(fe->hwnd);
2556     SetMapMode(hdc, MM_TEXT);
2557
2558     fe->dlg_done = FALSE;
2559
2560     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2561                              0, 0, 0, 0,
2562                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2563                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2564                              DEFAULT_QUALITY,
2565                              FF_SWISS,
2566                              "MS Shell Dlg");
2567
2568     oldfont = SelectObject(hdc, fe->cfgfont);
2569     if (GetTextMetrics(hdc, &tm)) {
2570         height = tm.tmAscent + tm.tmDescent;
2571         width = tm.tmAveCharWidth;
2572     } else {
2573         height = width = 30;
2574     }
2575
2576     fe->cfg = frontend_get_config(fe, which, &title);
2577     fe->cfg_which = which;
2578
2579     /*
2580      * Figure out the layout of the config box by measuring the
2581      * length of each piece of text.
2582      */
2583     maxlabel = maxcheckbox = 0;
2584     winheight = height/2;
2585
2586     for (i = fe->cfg; i->type != C_END; i++) {
2587         switch (i->type) {
2588           case C_STRING:
2589           case C_CHOICES:
2590             /*
2591              * Both these control types have a label filling only
2592              * the left-hand column of the box.
2593              */
2594             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2595                 maxlabel < size.cx)
2596                 maxlabel = size.cx;
2597             winheight += height * 3 / 2 + (height / 2);
2598             break;
2599
2600           case C_BOOLEAN:
2601             /*
2602              * Checkboxes take up the whole of the box width.
2603              */
2604             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2605                 maxcheckbox < size.cx)
2606                 maxcheckbox = size.cx;
2607             winheight += height + (height / 2);
2608             break;
2609         }
2610     }
2611
2612     winheight += height + height * 7 / 4;      /* OK / Cancel buttons */
2613
2614     col1l = 2*width;
2615     col1r = col1l + maxlabel;
2616     col2l = col1r + 2*width;
2617     col2r = col2l + 30*width;
2618     if (col2r < col1l+2*height+maxcheckbox)
2619         col2r = col1l+2*height+maxcheckbox;
2620     winwidth = col2r + 2*width;
2621
2622     SelectObject(hdc, oldfont);
2623     ReleaseDC(fe->hwnd, hdc);
2624
2625     /*
2626      * Create the dialog, now that we know its size.
2627      */
2628     {
2629         RECT r, r2;
2630
2631         r.left = r.top = 0;
2632         r.right = winwidth;
2633         r.bottom = winheight;
2634
2635         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2636                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2637                                 WS_CAPTION | WS_SYSMENU*/) &~
2638                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2639                            FALSE, 0);
2640
2641         /*
2642          * Centre the dialog on its parent window.
2643          */
2644         r.right -= r.left;
2645         r.bottom -= r.top;
2646         GetWindowRect(fe->hwnd, &r2);
2647         r.left = (r2.left + r2.right - r.right) / 2;
2648         r.top = (r2.top + r2.bottom - r.bottom) / 2;
2649         r.right += r.left;
2650         r.bottom += r.top;
2651
2652         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
2653                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2654                                     WS_CAPTION | WS_SYSMENU,
2655                                     r.left, r.top,
2656                                     r.right-r.left, r.bottom-r.top,
2657                                     fe->hwnd, NULL, fe->inst, NULL);
2658         sfree(title);
2659     }
2660
2661     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2662
2663     SetWindowLongPtr(fe->cfgbox, GWLP_USERDATA, (LONG_PTR)fe);
2664     SetWindowLongPtr(fe->cfgbox, DWLP_DLGPROC, (LONG_PTR)ConfigDlgProc);
2665
2666     /*
2667      * Count the controls so we can allocate cfgaux.
2668      */
2669     for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2670         nctrls++;
2671     fe->cfgaux = snewn(nctrls, struct cfg_aux);
2672
2673     id = 1000;
2674     y = height/2;
2675     for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2676         switch (i->type) {
2677           case C_STRING:
2678             /*
2679              * Edit box with a label beside it.
2680              */
2681             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2682                    "Static", 0, 0, i->name, id++);
2683             ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
2684                          "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
2685                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2686             SetWindowText(ctl, i->sval);
2687             y += height*3/2;
2688             break;
2689
2690           case C_BOOLEAN:
2691             /*
2692              * Simple checkbox.
2693              */
2694             mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
2695                    BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2696                    0, i->name, (j->ctlid = id++));
2697             CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2698             y += height;
2699             break;
2700
2701           case C_CHOICES:
2702             /*
2703              * Drop-down list with a label beside it.
2704              */
2705             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2706                    "STATIC", 0, 0, i->name, id++);
2707             ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
2708                          "COMBOBOX", WS_TABSTOP |
2709                          CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2710                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2711             {
2712                 char c, *p, *q, *str;
2713
2714                 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
2715                 p = i->sval;
2716                 c = *p++;
2717                 while (*p) {
2718                     q = p;
2719                     while (*q && *q != c) q++;
2720                     str = snewn(q-p+1, char);
2721                     strncpy(str, p, q-p);
2722                     str[q-p] = '\0';
2723                     SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
2724                     sfree(str);
2725                     if (*q) q++;
2726                     p = q;
2727                 }
2728             }
2729
2730             SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2731
2732             y += height*3/2;
2733             break;
2734         }
2735
2736         assert(y < winheight);
2737         y += height/2;
2738     }
2739
2740     y += height/2;                     /* extra space before OK and Cancel */
2741     mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
2742            BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2743            "OK", IDOK);
2744     mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
2745            BS_PUSHBUTTON | WS_TABSTOP, 0, "Cancel", IDCANCEL);
2746
2747     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2748
2749     EnableWindow(fe->hwnd, FALSE);
2750     ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2751     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2752         if (!IsDialogMessage(fe->cfgbox, &msg))
2753             DispatchMessage(&msg);
2754         if (fe->dlg_done)
2755             break;
2756     }
2757     EnableWindow(fe->hwnd, TRUE);
2758     SetForegroundWindow(fe->hwnd);
2759     DestroyWindow(fe->cfgbox);
2760     DeleteObject(fe->cfgfont);
2761
2762     free_cfg(fe->cfg);
2763     sfree(fe->cfgaux);
2764
2765     return (fe->dlg_done == 2);
2766 #endif
2767 }
2768
2769 #ifdef _WIN32_WCE
2770 static void calculate_bitmap_position(frontend *fe, int x, int y)
2771 {
2772     /* Pocket PC - center the game in the full screen window */
2773     int yMargin;
2774     RECT rcClient;
2775
2776     GetClientRect(fe->hwnd, &rcClient);
2777     fe->bitmapPosition.left = (rcClient.right  - x) / 2;
2778     yMargin = rcClient.bottom - y;
2779
2780     if (fe->numpad != NULL) {
2781         RECT rcPad;
2782         GetWindowRect(fe->numpad, &rcPad);
2783         yMargin -= rcPad.bottom - rcPad.top;
2784     }
2785
2786     if (fe->statusbar != NULL) {
2787         RECT rcStatus;
2788         GetWindowRect(fe->statusbar, &rcStatus);
2789         yMargin -= rcStatus.bottom - rcStatus.top;
2790     }
2791
2792     fe->bitmapPosition.top = yMargin / 2;
2793
2794     fe->bitmapPosition.right  = fe->bitmapPosition.left + x;
2795     fe->bitmapPosition.bottom = fe->bitmapPosition.top  + y;
2796 }
2797 #else
2798 static void calculate_bitmap_position(frontend *fe, int x, int y)
2799 {
2800     /* Plain Windows - position the game in the upper-left corner */
2801     fe->bitmapPosition.left = 0;
2802     fe->bitmapPosition.top = 0;
2803     fe->bitmapPosition.right  = fe->bitmapPosition.left + x;
2804     fe->bitmapPosition.bottom = fe->bitmapPosition.top  + y;
2805 }
2806 #endif
2807
2808 static void new_bitmap(frontend *fe, int x, int y)
2809 {
2810     HDC hdc;
2811
2812     if (fe->bitmap) DeleteObject(fe->bitmap);
2813
2814     hdc = GetDC(fe->hwnd);
2815     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2816     calculate_bitmap_position(fe, x, y);
2817     ReleaseDC(fe->hwnd, hdc);
2818 }
2819
2820 static void new_game_size(frontend *fe, float scale)
2821 {
2822     RECT r, sr;
2823     int x, y;
2824
2825     get_max_puzzle_size(fe, &x, &y);
2826     midend_size(fe->me, &x, &y, FALSE);
2827
2828     if (scale != 1.0) {
2829       x = (int)((float)x * fe->puzz_scale);
2830       y = (int)((float)y * fe->puzz_scale);
2831       midend_size(fe->me, &x, &y, TRUE);
2832     }
2833     fe->ymin = (fe->xmin * y) / x;
2834
2835     r.left = r.top = 0;
2836     r.right = x;
2837     r.bottom = y;
2838     AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2839
2840     if (fe->statusbar != NULL) {
2841         GetWindowRect(fe->statusbar, &sr);
2842     } else {
2843         sr.left = sr.right = sr.top = sr.bottom = 0;
2844     }
2845 #ifndef _WIN32_WCE
2846     SetWindowPos(fe->hwnd, NULL, 0, 0,
2847                  r.right - r.left,
2848                  r.bottom - r.top + sr.bottom - sr.top,
2849                  SWP_NOMOVE | SWP_NOZORDER);
2850 #endif
2851
2852     check_window_size(fe, &x, &y);
2853
2854 #ifndef _WIN32_WCE
2855     if (fe->statusbar != NULL)
2856         SetWindowPos(fe->statusbar, NULL, 0, y, x,
2857                      sr.bottom - sr.top, SWP_NOZORDER);
2858 #endif
2859
2860     new_bitmap(fe, x, y);
2861
2862 #ifdef _WIN32_WCE
2863     InvalidateRect(fe->hwnd, NULL, TRUE);
2864 #endif
2865     midend_redraw(fe->me);
2866 }
2867
2868 /*
2869  * Given a proposed new window rect, work out the resulting
2870  * difference in client size (from current), and use to try
2871  * and resize the puzzle, returning (wx,wy) as the actual
2872  * new window size.
2873  */
2874
2875 static void adjust_game_size(frontend *fe, RECT *proposed, int isedge,
2876                              int *wx_r, int *wy_r)
2877 {
2878     RECT cr, wr;
2879     int nx, ny, xdiff, ydiff, wx, wy;
2880
2881     /* Work out the current window sizing, and thus the
2882      * difference in size we're asking for. */
2883     GetClientRect(fe->hwnd, &cr);
2884     wr = cr;
2885     AdjustWindowRectEx(&wr, WINFLAGS, TRUE, 0);
2886
2887     xdiff = (proposed->right - proposed->left) - (wr.right - wr.left);
2888     ydiff = (proposed->bottom - proposed->top) - (wr.bottom - wr.top);
2889
2890     if (isedge) {
2891       /* These next four lines work around the fact that midend_size
2892        * is happy to shrink _but not grow_ if you change one dimension
2893        * but not the other. */
2894       if (xdiff > 0 && ydiff == 0)
2895         ydiff = (xdiff * (wr.right - wr.left)) / (wr.bottom - wr.top);
2896       if (xdiff == 0 && ydiff > 0)
2897         xdiff = (ydiff * (wr.bottom - wr.top)) / (wr.right - wr.left);
2898     }
2899
2900     if (check_window_resize(fe,
2901                             (cr.right - cr.left) + xdiff,
2902                             (cr.bottom - cr.top) + ydiff,
2903                             &nx, &ny, &wx, &wy)) {
2904         new_bitmap(fe, nx, ny);
2905         midend_force_redraw(fe->me);
2906     } else {
2907         /* reset size to current window size */
2908         wx = wr.right - wr.left;
2909         wy = wr.bottom - wr.top;
2910     }
2911     /* Re-fetch rectangle; size limits mean we might not have
2912      * taken it quite to the mouse drag positions. */
2913     GetClientRect(fe->hwnd, &cr);
2914     adjust_statusbar(fe, &cr);
2915
2916     *wx_r = wx; *wy_r = wy;
2917 }
2918
2919 static void update_type_menu_tick(frontend *fe)
2920 {
2921     int total, n, i;
2922
2923     if (fe->typemenu == INVALID_HANDLE_VALUE)
2924         return;
2925
2926     n = midend_which_preset(fe->me);
2927
2928     for (i = 0; i < fe->n_preset_menuitems; i++) {
2929         if (fe->preset_menuitems[i].which_menu) {
2930             int flag = (i == n ? MF_CHECKED : MF_UNCHECKED);
2931             CheckMenuItem(fe->preset_menuitems[i].which_menu,
2932                           fe->preset_menuitems[i].item_index,
2933                           MF_BYPOSITION | flag);
2934         }
2935     }
2936
2937     if (fe->game->can_configure) {
2938         int flag = (n < 0 ? MF_CHECKED : MF_UNCHECKED);
2939         /* "Custom" menu item is at the bottom of the top-level Type menu */
2940         total = GetMenuItemCount(fe->typemenu);
2941         CheckMenuItem(fe->typemenu, total - 1, MF_BYPOSITION | flag);
2942     }
2943
2944     DrawMenuBar(fe->hwnd);
2945 }
2946
2947 static void update_copy_menu_greying(frontend *fe)
2948 {
2949     UINT enable = (midend_can_format_as_text_now(fe->me) ?
2950                    MF_ENABLED : MF_GRAYED);
2951     EnableMenuItem(fe->gamemenu, IDM_COPY, MF_BYCOMMAND | enable);
2952 }
2953
2954 static void new_game_type(frontend *fe)
2955 {
2956     midend_new_game(fe->me);
2957     new_game_size(fe, 1.0);
2958     update_type_menu_tick(fe);
2959     update_copy_menu_greying(fe);
2960 }
2961
2962 static int is_alt_pressed(void)
2963 {
2964     BYTE keystate[256];
2965     int r = GetKeyboardState(keystate);
2966     if (!r)
2967         return FALSE;
2968     if (keystate[VK_MENU] & 0x80)
2969         return TRUE;
2970     if (keystate[VK_RMENU] & 0x80)
2971         return TRUE;
2972     return FALSE;
2973 }
2974
2975 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2976                                 WPARAM wParam, LPARAM lParam)
2977 {
2978     frontend *fe = (frontend *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
2979     int cmd;
2980
2981     switch (message) {
2982       case WM_CLOSE:
2983         DestroyWindow(hwnd);
2984         return 0;
2985       case WM_COMMAND:
2986 #ifdef _WIN32_WCE
2987         /* Numeric pad sends WM_COMMAND messages */
2988         if ((wParam >= IDM_KEYEMUL) && (wParam < IDM_KEYEMUL + 256))
2989         {
2990             midend_process_key(fe->me, 0, 0, wParam - IDM_KEYEMUL);
2991         }
2992 #endif
2993         cmd = wParam & ~0xF;           /* low 4 bits reserved to Windows */
2994         switch (cmd) {
2995           case IDM_NEW:
2996             if (!midend_process_key(fe->me, 0, 0, UI_NEWGAME))
2997                 PostQuitMessage(0);
2998             break;
2999           case IDM_RESTART:
3000             midend_restart_game(fe->me);
3001             break;
3002           case IDM_UNDO:
3003             if (!midend_process_key(fe->me, 0, 0, UI_UNDO))
3004                 PostQuitMessage(0);
3005             break;
3006           case IDM_REDO:
3007             if (!midend_process_key(fe->me, 0, 0, UI_REDO))
3008                 PostQuitMessage(0);
3009             break;
3010           case IDM_COPY:
3011             {
3012                 char *text = midend_text_format(fe->me);
3013                 if (text)
3014                     write_clip(hwnd, text);
3015                 else
3016                     MessageBeep(MB_ICONWARNING);
3017                 sfree(text);
3018             }
3019             break;
3020           case IDM_SOLVE:
3021             {
3022                 char *msg = midend_solve(fe->me);
3023                 if (msg)
3024                     MessageBox(hwnd, msg, "Unable to solve",
3025                                MB_ICONERROR | MB_OK);
3026             }
3027             break;
3028           case IDM_QUIT:
3029             if (!midend_process_key(fe->me, 0, 0, UI_QUIT))
3030                 PostQuitMessage(0);
3031             break;
3032           case IDM_CONFIG:
3033             if (get_config(fe, CFG_SETTINGS))
3034                 new_game_type(fe);
3035             break;
3036           case IDM_SEED:
3037             if (get_config(fe, CFG_SEED))
3038                 new_game_type(fe);
3039             break;
3040           case IDM_DESC:
3041             if (get_config(fe, CFG_DESC))
3042                 new_game_type(fe);
3043             break;
3044           case IDM_PRINT:
3045             if (get_config(fe, CFG_PRINT))
3046                 print(fe);
3047             break;
3048           case IDM_ABOUT:
3049             about(fe);
3050             break;
3051           case IDM_LOAD:
3052           case IDM_SAVE:
3053             {
3054                 OPENFILENAME of;
3055                 char filename[FILENAME_MAX];
3056                 int ret;
3057
3058                 memset(&of, 0, sizeof(of));
3059                 of.hwndOwner = hwnd;
3060                 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
3061                 of.lpstrCustomFilter = NULL;
3062                 of.nFilterIndex = 1;
3063                 of.lpstrFile = filename;
3064                 filename[0] = '\0';
3065                 of.nMaxFile = lenof(filename);
3066                 of.lpstrFileTitle = NULL;
3067                 of.lpstrTitle = (cmd == IDM_SAVE ?
3068                                  "Enter name of game file to save" :
3069                                  "Enter name of saved game file to load");
3070                 of.Flags = 0;
3071 #ifdef OPENFILENAME_SIZE_VERSION_400
3072                 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
3073 #else
3074                 of.lStructSize = sizeof(of);
3075 #endif
3076                 of.lpstrInitialDir = NULL;
3077
3078                 if (cmd == IDM_SAVE)
3079                     ret = GetSaveFileName(&of);
3080                 else
3081                     ret = GetOpenFileName(&of);
3082
3083                 if (ret) {
3084                     if (cmd == IDM_SAVE) {
3085                         FILE *fp;
3086
3087                         if ((fp = fopen(filename, "r")) != NULL) {
3088                             char buf[256 + FILENAME_MAX];
3089                             fclose(fp);
3090                             /* file exists */
3091
3092                             sprintf(buf, "Are you sure you want to overwrite"
3093                                     " the file \"%.*s\"?",
3094                                     FILENAME_MAX, filename);
3095                             if (MessageBox(hwnd, buf, "Question",
3096                                            MB_YESNO | MB_ICONQUESTION)
3097                                 != IDYES)
3098                                 break;
3099                         }
3100
3101                         fp = fopen(filename, "w");
3102
3103                         if (!fp) {
3104                             MessageBox(hwnd, "Unable to open save file",
3105                                        "Error", MB_ICONERROR | MB_OK);
3106                             break;
3107                         }
3108
3109                         midend_serialise(fe->me, savefile_write, fp);
3110
3111                         fclose(fp);
3112                     } else {
3113                         FILE *fp = fopen(filename, "r");
3114                         char *err = NULL;
3115                         midend *me = fe->me;
3116 #ifdef COMBINED
3117                         char *id_name;
3118 #endif
3119
3120                         if (!fp) {
3121                             MessageBox(hwnd, "Unable to open saved game file",
3122                                        "Error", MB_ICONERROR | MB_OK);
3123                             break;
3124                         }
3125
3126 #ifdef COMBINED
3127                         /*
3128                          * This save file might be from a different
3129                          * game.
3130                          */
3131                         err = identify_game(&id_name, savefile_read, fp);
3132                         if (!err) {
3133                             int i;
3134                             for (i = 0; i < gamecount; i++)
3135                                 if (!strcmp(id_name, gamelist[i]->name))
3136                                     break;
3137                             if (i == gamecount) {
3138                                 err = "Save file is for a game not "
3139                                     "supported by this program";
3140                             } else {
3141                                 me = midend_for_new_game(fe, gamelist[i], NULL,
3142                                                          FALSE, FALSE, &err);
3143                                 rewind(fp); /* for the actual load */
3144                             }
3145                             sfree(id_name);
3146                         }
3147 #endif
3148                         if (!err)
3149                             err = midend_deserialise(me, savefile_read, fp);
3150
3151                         fclose(fp);
3152
3153                         if (err) {
3154                             MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
3155                             break;
3156                         }
3157
3158                         if (fe->me != me)
3159                             fe_set_midend(fe, me);
3160                         new_game_size(fe, 1.0);
3161                     }
3162                 }
3163             }
3164
3165             break;
3166 #ifndef _WIN32_WCE
3167           case IDM_HELPC:
3168             start_help(fe, NULL);
3169             break;
3170           case IDM_GAMEHELP:
3171             assert(help_type != NONE);
3172             start_help(fe, help_type == CHM ?
3173                        fe->game->htmlhelp_topic : fe->game->winhelp_topic);
3174             break;
3175 #endif
3176           default:
3177 #ifdef COMBINED
3178             if (wParam >= IDM_GAMES && wParam < (IDM_GAMES + (WPARAM)gamecount)) {
3179                 int p = wParam - IDM_GAMES;
3180                 char *error = NULL;
3181                 fe_set_midend(fe, midend_for_new_game(fe, gamelist[p], NULL,
3182                                                       FALSE, FALSE, &error));
3183                 sfree(error);
3184             } else
3185 #endif
3186             {
3187                 game_params *preset = preset_menu_lookup_by_id(
3188                     fe->preset_menu,
3189                     ((wParam &~ 0xF) - IDM_PRESETS) / 0x10);
3190
3191                 if (preset) {
3192                     midend_set_params(fe->me, preset);
3193                     new_game_type(fe);
3194                 }
3195             }
3196             break;
3197         }
3198         break;
3199       case WM_DESTROY:
3200 #ifndef _WIN32_WCE
3201         stop_help(fe);
3202 #endif
3203         frontend_free(fe);
3204         PostQuitMessage(0);
3205         return 0;
3206       case WM_PAINT:
3207         {
3208             PAINTSTRUCT p;
3209             HDC hdc, hdc2;
3210             HBITMAP prevbm;
3211             RECT rcDest;
3212
3213             hdc = BeginPaint(hwnd, &p);
3214             hdc2 = CreateCompatibleDC(hdc);
3215             prevbm = SelectObject(hdc2, fe->bitmap);
3216 #ifdef _WIN32_WCE
3217             FillRect(hdc, &(p.rcPaint), (HBRUSH) GetStockObject(WHITE_BRUSH));
3218 #endif
3219             IntersectRect(&rcDest, &(fe->bitmapPosition), &(p.rcPaint));
3220             BitBlt(hdc,
3221                    rcDest.left, rcDest.top,
3222                    rcDest.right - rcDest.left,
3223                    rcDest.bottom - rcDest.top,
3224                    hdc2,
3225                    rcDest.left - fe->bitmapPosition.left,
3226                    rcDest.top - fe->bitmapPosition.top,
3227                    SRCCOPY);
3228             SelectObject(hdc2, prevbm);
3229             DeleteDC(hdc2);
3230             EndPaint(hwnd, &p);
3231         }
3232         return 0;
3233       case WM_KEYDOWN:
3234         {
3235             int key = -1;
3236             BYTE keystate[256];
3237             int r = GetKeyboardState(keystate);
3238             int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
3239             int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
3240
3241             switch (wParam) {
3242               case VK_LEFT:
3243                 if (!(lParam & 0x01000000))
3244                     key = MOD_NUM_KEYPAD | '4';
3245                 else
3246                     key = shift | ctrl | CURSOR_LEFT;
3247                 break;
3248               case VK_RIGHT:
3249                 if (!(lParam & 0x01000000))
3250                     key = MOD_NUM_KEYPAD | '6';
3251                 else
3252                     key = shift | ctrl | CURSOR_RIGHT;
3253                 break;
3254               case VK_UP:
3255                 if (!(lParam & 0x01000000))
3256                     key = MOD_NUM_KEYPAD | '8';
3257                 else
3258                     key = shift | ctrl | CURSOR_UP;
3259                 break;
3260               case VK_DOWN:
3261                 if (!(lParam & 0x01000000))
3262                     key = MOD_NUM_KEYPAD | '2';
3263                 else
3264                     key = shift | ctrl | CURSOR_DOWN;
3265                 break;
3266                 /*
3267                  * Diagonal keys on the numeric keypad.
3268                  */
3269               case VK_PRIOR:
3270                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
3271                 break;
3272               case VK_NEXT:
3273                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
3274                 break;
3275               case VK_HOME:
3276                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
3277                 break;
3278               case VK_END:
3279                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
3280                 break;
3281               case VK_INSERT:
3282                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
3283                 break;
3284               case VK_CLEAR:
3285                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
3286                 break;
3287                 /*
3288                  * Numeric keypad keys with Num Lock on.
3289                  */
3290               case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
3291               case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
3292               case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
3293               case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
3294               case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
3295               case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
3296               case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
3297               case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
3298               case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
3299               case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
3300             }
3301
3302             if (key != -1) {
3303                 if (!midend_process_key(fe->me, 0, 0, key))
3304                     PostQuitMessage(0);
3305             } else {
3306                 MSG m;
3307                 m.hwnd = hwnd;
3308                 m.message = WM_KEYDOWN;
3309                 m.wParam = wParam;
3310                 m.lParam = lParam & 0xdfff;
3311                 TranslateMessage(&m);
3312             }
3313         }
3314         break;
3315       case WM_LBUTTONDOWN:
3316       case WM_RBUTTONDOWN:
3317       case WM_MBUTTONDOWN:
3318         {
3319             int button;
3320
3321             /*
3322              * Shift-clicks count as middle-clicks, since otherwise
3323              * two-button Windows users won't have any kind of
3324              * middle click to use.
3325              */
3326             if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
3327                 button = MIDDLE_BUTTON;
3328             else if (message == WM_RBUTTONDOWN || is_alt_pressed())
3329                 button = RIGHT_BUTTON;
3330             else
3331 #ifndef _WIN32_WCE
3332                 button = LEFT_BUTTON;
3333 #else
3334                 if ((fe->game->flags & REQUIRE_RBUTTON) == 0)
3335                     button = LEFT_BUTTON;
3336                 else
3337                 {
3338                     SHRGINFO shrgi;
3339
3340                     shrgi.cbSize     = sizeof(SHRGINFO);
3341                     shrgi.hwndClient = hwnd;
3342                     shrgi.ptDown.x   = (signed short)LOWORD(lParam);
3343                     shrgi.ptDown.y   = (signed short)HIWORD(lParam);
3344                     shrgi.dwFlags    = SHRG_RETURNCMD;
3345
3346                     if (GN_CONTEXTMENU == SHRecognizeGesture(&shrgi))
3347                         button = RIGHT_BUTTON;
3348                     else
3349                         button = LEFT_BUTTON;
3350                 }
3351 #endif
3352
3353             if (!midend_process_key(fe->me,
3354                                     (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3355                                     (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3356                                     button))
3357                 PostQuitMessage(0);
3358
3359             SetCapture(hwnd);
3360         }
3361         break;
3362       case WM_LBUTTONUP:
3363       case WM_RBUTTONUP:
3364       case WM_MBUTTONUP:
3365         {
3366             int button;
3367
3368             /*
3369              * Shift-clicks count as middle-clicks, since otherwise
3370              * two-button Windows users won't have any kind of
3371              * middle click to use.
3372              */
3373             if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
3374                 button = MIDDLE_RELEASE;
3375             else if (message == WM_RBUTTONUP || is_alt_pressed())
3376                 button = RIGHT_RELEASE;
3377             else
3378                 button = LEFT_RELEASE;
3379
3380             if (!midend_process_key(fe->me,
3381                                     (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3382                                     (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3383                                     button))
3384                 PostQuitMessage(0);
3385
3386             ReleaseCapture();
3387         }
3388         break;
3389       case WM_MOUSEMOVE:
3390         {
3391             int button;
3392
3393             if (wParam & (MK_MBUTTON | MK_SHIFT))
3394                 button = MIDDLE_DRAG;
3395             else if (wParam & MK_RBUTTON || is_alt_pressed())
3396                 button = RIGHT_DRAG;
3397             else
3398                 button = LEFT_DRAG;
3399             
3400             if (!midend_process_key(fe->me,
3401                                     (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3402                                     (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3403                                     button))
3404                 PostQuitMessage(0);
3405         }
3406         break;
3407       case WM_CHAR:
3408         {
3409             int key = (unsigned char)wParam;
3410             if (key == '\x1A') {
3411                 BYTE keystate[256];
3412                 if (GetKeyboardState(keystate) &&
3413                     (keystate[VK_SHIFT] & 0x80) &&
3414                     (keystate[VK_CONTROL] & 0x80))
3415                     key = UI_REDO;
3416             }
3417             if (!midend_process_key(fe->me, 0, 0, key))
3418                 PostQuitMessage(0);
3419         }
3420         return 0;
3421       case WM_TIMER:
3422         if (fe->timer) {
3423             DWORD now = GetTickCount();
3424             float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
3425             midend_timer(fe->me, elapsed);
3426             fe->timer_last_tickcount = now;
3427         }
3428         return 0;
3429 #ifndef _WIN32_WCE
3430       case WM_SIZING:
3431         {
3432             RECT *sr = (RECT *)lParam;
3433             int wx, wy, isedge = 0;
3434
3435             if (wParam == WMSZ_TOP ||
3436                 wParam == WMSZ_RIGHT ||
3437                 wParam == WMSZ_BOTTOM ||
3438                 wParam == WMSZ_LEFT) isedge = 1;
3439             adjust_game_size(fe, sr, isedge, &wx, &wy);
3440
3441             /* Given the window size the puzzles constrain
3442              * us to, work out which edge we should be moving. */
3443             if (wParam == WMSZ_TOP ||
3444                 wParam == WMSZ_TOPLEFT ||
3445                 wParam == WMSZ_TOPRIGHT) {
3446                 sr->top = sr->bottom - wy;
3447             } else {
3448                 sr->bottom = sr->top + wy;
3449             }
3450             if (wParam == WMSZ_LEFT ||
3451                 wParam == WMSZ_TOPLEFT ||
3452                 wParam == WMSZ_BOTTOMLEFT) {
3453                 sr->left = sr->right - wx;
3454             } else {
3455                 sr->right = sr->left + wx;
3456             }
3457             return TRUE;
3458         }
3459         break;
3460 #endif
3461     }
3462
3463     return DefWindowProc(hwnd, message, wParam, lParam);
3464 }
3465
3466 #ifdef _WIN32_WCE
3467 static int FindPreviousInstance()
3468 {
3469     /* Check if application is running. If it's running then focus on the window */
3470     HWND hOtherWnd = NULL;
3471
3472     hOtherWnd = FindWindow (wGameName, wGameName);
3473     if (hOtherWnd)
3474     {
3475         SetForegroundWindow (hOtherWnd);
3476         return TRUE;
3477     }
3478
3479     return FALSE;
3480 }
3481 #endif
3482
3483 /*
3484  * Split a complete command line into argc/argv, attempting to do it
3485  * exactly the same way the Visual Studio C library would do it (so
3486  * that our console utilities, which receive argc and argv already
3487  * broken apart by the C library, will have their command lines
3488  * processed in the same way as the GUI utilities which get a whole
3489  * command line and must call this function).
3490  * 
3491  * Does not modify the input command line.
3492  * 
3493  * The final parameter (argstart) is used to return a second array
3494  * of char * pointers, the same length as argv, each one pointing
3495  * at the start of the corresponding element of argv in the
3496  * original command line. So if you get half way through processing
3497  * your command line in argc/argv form and then decide you want to
3498  * treat the rest as a raw string, you can. If you don't want to,
3499  * `argstart' can be safely left NULL.
3500  */
3501 void split_into_argv(char *cmdline, int *argc, char ***argv,
3502                      char ***argstart)
3503 {
3504     char *p;
3505     char *outputline, *q;
3506     char **outputargv, **outputargstart;
3507     int outputargc;
3508
3509     /*
3510      * These argument-breaking rules apply to Visual Studio 7, which
3511      * is currently the compiler expected to be used for the Windows
3512      * port of my puzzles. Visual Studio 10 has different rules,
3513      * lacking the curious mod 3 behaviour of consecutive quotes
3514      * described below; I presume they fixed a bug. As and when we
3515      * migrate to a newer compiler, we'll have to adjust this to
3516      * match; however, for the moment we faithfully imitate in our GUI
3517      * utilities what our CLI utilities can't be prevented from doing.
3518      *
3519      * When I investigated this, at first glance the rules appeared to
3520      * be:
3521      *
3522      *  - Single quotes are not special characters.
3523      *
3524      *  - Double quotes are removed, but within them spaces cease
3525      *    to be special.
3526      *
3527      *  - Backslashes are _only_ special when a sequence of them
3528      *    appear just before a double quote. In this situation,
3529      *    they are treated like C backslashes: so \" just gives a
3530      *    literal quote, \\" gives a literal backslash and then
3531      *    opens or closes a double-quoted segment, \\\" gives a
3532      *    literal backslash and then a literal quote, \\\\" gives
3533      *    two literal backslashes and then opens/closes a
3534      *    double-quoted segment, and so forth. Note that this
3535      *    behaviour is identical inside and outside double quotes.
3536      *
3537      *  - Two successive double quotes become one literal double
3538      *    quote, but only _inside_ a double-quoted segment.
3539      *    Outside, they just form an empty double-quoted segment
3540      *    (which may cause an empty argument word).
3541      *
3542      *  - That only leaves the interesting question of what happens
3543      *    when one or more backslashes precedes two or more double
3544      *    quotes, starting inside a double-quoted string. And the
3545      *    answer to that appears somewhat bizarre. Here I tabulate
3546      *    number of backslashes (across the top) against number of
3547      *    quotes (down the left), and indicate how many backslashes
3548      *    are output, how many quotes are output, and whether a
3549      *    quoted segment is open at the end of the sequence:
3550      * 
3551      *                      backslashes
3552      * 
3553      *               0         1      2      3      4
3554      * 
3555      *         0   0,0,y  |  1,0,y  2,0,y  3,0,y  4,0,y
3556      *            --------+-----------------------------
3557      *         1   0,0,n  |  0,1,y  1,0,n  1,1,y  2,0,n
3558      *    q    2   0,1,n  |  0,1,n  1,1,n  1,1,n  2,1,n
3559      *    u    3   0,1,y  |  0,2,n  1,1,y  1,2,n  2,1,y
3560      *    o    4   0,1,n  |  0,2,y  1,1,n  1,2,y  2,1,n
3561      *    t    5   0,2,n  |  0,2,n  1,2,n  1,2,n  2,2,n
3562      *    e    6   0,2,y  |  0,3,n  1,2,y  1,3,n  2,2,y
3563      *    s    7   0,2,n  |  0,3,y  1,2,n  1,3,y  2,2,n
3564      *         8   0,3,n  |  0,3,n  1,3,n  1,3,n  2,3,n
3565      *         9   0,3,y  |  0,4,n  1,3,y  1,4,n  2,3,y
3566      *        10   0,3,n  |  0,4,y  1,3,n  1,4,y  2,3,n
3567      *        11   0,4,n  |  0,4,n  1,4,n  1,4,n  2,4,n
3568      * 
3569      * 
3570      *      [Test fragment was of the form "a\\\"""b c" d.]
3571      * 
3572      * There is very weird mod-3 behaviour going on here in the
3573      * number of quotes, and it even applies when there aren't any
3574      * backslashes! How ghastly.
3575      * 
3576      * With a bit of thought, this extremely odd diagram suddenly
3577      * coalesced itself into a coherent, if still ghastly, model of
3578      * how things work:
3579      * 
3580      *  - As before, backslashes are only special when one or more
3581      *    of them appear contiguously before at least one double
3582      *    quote. In this situation the backslashes do exactly what
3583      *    you'd expect: each one quotes the next thing in front of
3584      *    it, so you end up with n/2 literal backslashes (if n is
3585      *    even) or (n-1)/2 literal backslashes and a literal quote
3586      *    (if n is odd). In the latter case the double quote
3587      *    character right after the backslashes is used up.
3588      * 
3589      *  - After that, any remaining double quotes are processed. A
3590      *    string of contiguous unescaped double quotes has a mod-3
3591      *    behaviour:
3592      * 
3593      *     * inside a quoted segment, a quote ends the segment.
3594      *     * _immediately_ after ending a quoted segment, a quote
3595      *       simply produces a literal quote.
3596      *     * otherwise, outside a quoted segment, a quote begins a
3597      *       quoted segment.
3598      * 
3599      *    So, for example, if we started inside a quoted segment
3600      *    then two contiguous quotes would close the segment and
3601      *    produce a literal quote; three would close the segment,
3602      *    produce a literal quote, and open a new segment. If we
3603      *    started outside a quoted segment, then two contiguous
3604      *    quotes would open and then close a segment, producing no
3605      *    output (but potentially creating a zero-length argument);
3606      *    but three quotes would open and close a segment and then
3607      *    produce a literal quote.
3608      */
3609
3610     /*
3611      * First deal with the simplest of all special cases: if there
3612      * aren't any arguments, return 0,NULL,NULL.
3613      */
3614     while (*cmdline && isspace(*cmdline)) cmdline++;
3615     if (!*cmdline) {
3616         if (argc) *argc = 0;
3617         if (argv) *argv = NULL;
3618         if (argstart) *argstart = NULL;
3619         return;
3620     }
3621
3622     /*
3623      * This will guaranteeably be big enough; we can realloc it
3624      * down later.
3625      */
3626     outputline = snewn(1+strlen(cmdline), char);
3627     outputargv = snewn(strlen(cmdline)+1 / 2, char *);
3628     outputargstart = snewn(strlen(cmdline)+1 / 2, char *);
3629
3630     p = cmdline; q = outputline; outputargc = 0;
3631
3632     while (*p) {
3633         int quote;
3634
3635         /* Skip whitespace searching for start of argument. */
3636         while (*p && isspace(*p)) p++;
3637         if (!*p) break;
3638
3639         /* We have an argument; start it. */
3640         outputargv[outputargc] = q;
3641         outputargstart[outputargc] = p;
3642         outputargc++;
3643         quote = 0;
3644
3645         /* Copy data into the argument until it's finished. */
3646         while (*p) {
3647             if (!quote && isspace(*p))
3648                 break;                 /* argument is finished */
3649
3650             if (*p == '"' || *p == '\\') {
3651                 /*
3652                  * We have a sequence of zero or more backslashes
3653                  * followed by a sequence of zero or more quotes.
3654                  * Count up how many of each, and then deal with
3655                  * them as appropriate.
3656                  */
3657                 int i, slashes = 0, quotes = 0;
3658                 while (*p == '\\') slashes++, p++;
3659                 while (*p == '"') quotes++, p++;
3660
3661                 if (!quotes) {
3662                     /*
3663                      * Special case: if there are no quotes,
3664                      * slashes are not special at all, so just copy
3665                      * n slashes to the output string.
3666                      */
3667                     while (slashes--) *q++ = '\\';
3668                 } else {
3669                     /* Slashes annihilate in pairs. */
3670                     while (slashes >= 2) slashes -= 2, *q++ = '\\';
3671
3672                     /* One remaining slash takes out the first quote. */
3673                     if (slashes) quotes--, *q++ = '"';
3674
3675                     if (quotes > 0) {
3676                         /* Outside a quote segment, a quote starts one. */
3677                         if (!quote) quotes--, quote = 1;
3678
3679                         /* Now we produce (n+1)/3 literal quotes... */
3680                         for (i = 3; i <= quotes+1; i += 3) *q++ = '"';
3681
3682                         /* ... and end in a quote segment iff 3 divides n. */
3683                         quote = (quotes % 3 == 0);
3684                     }
3685                 }
3686             } else {
3687                 *q++ = *p++;
3688             }
3689         }
3690
3691         /* At the end of an argument, just append a trailing NUL. */
3692         *q++ = '\0';
3693     }
3694
3695     outputargv = sresize(outputargv, outputargc, char *);
3696     outputargstart = sresize(outputargstart, outputargc, char *);
3697
3698     if (argc) *argc = outputargc;
3699     if (argv) *argv = outputargv; else sfree(outputargv);
3700     if (argstart) *argstart = outputargstart; else sfree(outputargstart);
3701 }
3702
3703 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
3704 {
3705     MSG msg;
3706     char *error = NULL;
3707     const game *gg;
3708     frontend *fe;
3709     midend *me;
3710     int argc;
3711     char **argv;
3712
3713     split_into_argv(cmdline, &argc, &argv, NULL);
3714
3715 #ifdef _WIN32_WCE
3716     MultiByteToWideChar (CP_ACP, 0, CLASSNAME, -1, wClassName, 256);
3717     if (FindPreviousInstance ())
3718         return 0;
3719 #endif
3720
3721     InitCommonControls();
3722
3723     if (!prev) {
3724         WNDCLASS wndclass;
3725
3726         wndclass.style = 0;
3727         wndclass.lpfnWndProc = WndProc;
3728         wndclass.cbClsExtra = 0;
3729         wndclass.cbWndExtra = 0;
3730         wndclass.hInstance = inst;
3731         wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
3732 #ifndef _WIN32_WCE
3733         if (!wndclass.hIcon)           /* in case resource file is absent */
3734             wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
3735 #endif
3736         wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
3737         wndclass.hbrBackground = NULL;
3738         wndclass.lpszMenuName = NULL;
3739 #ifdef _WIN32_WCE
3740         wndclass.lpszClassName = wClassName;
3741 #else
3742         wndclass.lpszClassName = CLASSNAME;
3743 #endif
3744
3745         RegisterClass(&wndclass);
3746     }
3747
3748     while (*cmdline && isspace((unsigned char)*cmdline))
3749         cmdline++;
3750
3751     init_help();
3752
3753 #ifdef COMBINED
3754     gg = gamelist[0];
3755     if (argc > 0) {
3756         int i;
3757         for (i = 0; i < gamecount; i++) {
3758             const char *p = gamelist[i]->name;
3759             char *q = argv[0];
3760             while (*p && *q) {
3761                 if (isspace((unsigned char)*p)) {
3762                     while (*q && isspace((unsigned char)*q))
3763                         q++;
3764                 } else {
3765                     if (tolower((unsigned char)*p) !=
3766                         tolower((unsigned char)*q))
3767                         break;
3768                     q++;
3769                 }
3770                 p++;
3771             }
3772             if (!*p) {
3773                 gg = gamelist[i];
3774                 --argc;
3775                 ++argv;
3776                 break;
3777             }
3778         }
3779     }
3780 #else
3781     gg = &thegame;
3782 #endif
3783
3784     fe = frontend_new(inst);
3785     me = midend_for_new_game(fe, gg, argc > 0 ? argv[0] : NULL,
3786                              TRUE, TRUE, &error);
3787     if (!me) {
3788         char buf[128];
3789 #ifdef COMBINED
3790         sprintf(buf, "Puzzles Error");
3791 #else
3792         sprintf(buf, "%.100s Error", gg->name);
3793 #endif
3794         MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
3795         sfree(error);
3796         return 1;
3797     }
3798     fe_set_midend(fe, me);
3799     show_window(fe);
3800
3801     while (GetMessage(&msg, NULL, 0, 0)) {
3802         DispatchMessage(&msg);
3803     }
3804
3805     DestroyWindow(fe->hwnd);
3806     cleanup_help();
3807
3808     return msg.wParam;
3809 }
3810 /* vim: set shiftwidth=4 tabstop=8: */