chiark / gitweb /
84cf5ec96d5baaff8d62b6cb840bf80c97e4a7a4
[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     const 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         const 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].u.string.sval = dupstr("1");
2061         i++;
2062
2063         ret[i].name = "Number of puzzles across the page";
2064         ret[i].type = C_STRING;
2065         ret[i].u.string.sval = dupstr("1");
2066         i++;
2067
2068         ret[i].name = "Number of puzzles down the page";
2069         ret[i].type = C_STRING;
2070         ret[i].u.string.sval = dupstr("1");
2071         i++;
2072
2073         ret[i].name = "Percentage of standard size";
2074         ret[i].type = C_STRING;
2075         ret[i].u.string.sval = dupstr("100.0");
2076         i++;
2077
2078         ret[i].name = "Include currently shown puzzle";
2079         ret[i].type = C_BOOLEAN;
2080         ret[i].u.boolean.bval = TRUE;
2081         i++;
2082
2083         ret[i].name = "Print solutions";
2084         ret[i].type = C_BOOLEAN;
2085         ret[i].u.boolean.bval = FALSE;
2086         i++;
2087
2088         if (fe->game->can_print_in_colour) {
2089             ret[i].name = "Print in colour";
2090             ret[i].type = C_BOOLEAN;
2091             ret[i].u.boolean.bval = FALSE;
2092             i++;
2093         }
2094
2095         ret[i].name = NULL;
2096         ret[i].type = C_END;
2097         i++;
2098
2099         return ret;
2100     } else {
2101         assert(!"We should never get here");
2102         return NULL;
2103     }
2104 }
2105
2106 static const char *frontend_set_config(
2107     frontend *fe, int which, config_item *cfg)
2108 {
2109     if (which < CFG_FRONTEND_SPECIFIC) {
2110         return midend_set_config(fe->me, which, cfg);
2111     } else if (which == CFG_PRINT) {
2112         if ((fe->printcount = atoi(cfg[0].u.string.sval)) <= 0)
2113             return "Number of puzzles to print should be at least one";
2114         if ((fe->printw = atoi(cfg[1].u.string.sval)) <= 0)
2115             return "Number of puzzles across the page should be at least one";
2116         if ((fe->printh = atoi(cfg[2].u.string.sval)) <= 0)
2117             return "Number of puzzles down the page should be at least one";
2118         if ((fe->printscale = (float)atof(cfg[3].u.string.sval)) <= 0)
2119             return "Print size should be positive";
2120         fe->printcurr = cfg[4].u.boolean.bval;
2121         fe->printsolns = cfg[5].u.boolean.bval;
2122         fe->printcolour = fe->game->can_print_in_colour &&
2123             cfg[6].u.boolean.bval;
2124         return NULL;
2125     } else {
2126         assert(!"We should never get here");
2127         return "Internal error";
2128     }
2129 }
2130
2131 #ifdef _WIN32_WCE
2132 /* Separate version of mkctrl function for the Pocket PC. */
2133 /* Control coordinates should be specified in dialog units. */
2134 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2135             LPCTSTR wclass, int wstyle,
2136             int exstyle, const char *wtext, INT_PTR wid)
2137 {
2138     RECT rc;
2139     TCHAR wwtext[256];
2140
2141     /* Convert dialog units into pixels */
2142     rc.left = x1;  rc.right  = x2;
2143     rc.top  = y1;  rc.bottom = y2;
2144     MapDialogRect(fe->cfgbox, &rc);
2145
2146     MultiByteToWideChar (CP_ACP, 0, wtext, -1, wwtext, 256);
2147
2148     return CreateWindowEx(exstyle, wclass, wwtext,
2149                           wstyle | WS_CHILD | WS_VISIBLE,
2150                           rc.left, rc.top,
2151                           rc.right - rc.left, rc.bottom - rc.top,
2152                           fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2153 }
2154
2155 static void create_config_controls(frontend * fe)
2156 {
2157     int id, nctrls;
2158     int col1l, col1r, col2l, col2r, y;
2159     config_item *i;
2160     struct cfg_aux *j;
2161     HWND ctl;
2162
2163     /* Control placement done in dialog units */
2164     col1l = 4;   col1r = 96;   /* Label column */
2165     col2l = 100; col2r = 154;  /* Input column (edit boxes and combo boxes) */
2166
2167     /*
2168      * Count the controls so we can allocate cfgaux.
2169      */
2170     for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2171         nctrls++;
2172     fe->cfgaux = snewn(nctrls, struct cfg_aux);
2173
2174     id = 1000;
2175     y = 22; /* Leave some room for the dialog title */
2176     for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2177         switch (i->type) {
2178           case C_STRING:
2179             /*
2180              * Edit box with a label beside it.
2181              */
2182             mkctrl(fe, col1l, col1r, y + 1, y + 11,
2183                    TEXT("Static"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
2184             mkctrl(fe, col2l, col2r, y, y + 12,
2185                    TEXT("EDIT"), WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
2186                    0, "", (j->ctlid = id++));
2187             SetDlgItemTextA(fe->cfgbox, j->ctlid, i->u.string.sval);
2188             break;
2189
2190           case C_BOOLEAN:
2191             /*
2192              * Simple checkbox.
2193              */
2194             mkctrl(fe, col1l, col2r, y + 1, y + 11, TEXT("BUTTON"),
2195                    BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2196                    0, i->name, (j->ctlid = id++));
2197             CheckDlgButton(fe->cfgbox, j->ctlid, (i->u.boolean.bval != 0));
2198             break;
2199
2200           case C_CHOICES:
2201             /*
2202              * Drop-down list with a label beside it.
2203              */
2204             mkctrl(fe, col1l, col1r, y + 1, y + 11,
2205                    TEXT("STATIC"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
2206             ctl = mkctrl(fe, col2l, col2r, y, y + 48,
2207                          TEXT("COMBOBOX"), WS_BORDER | WS_TABSTOP |
2208                          CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2209                          0, "", (j->ctlid = id++));
2210             {
2211                 char c;
2212                 const char *p, *q;
2213                 char *str;
2214
2215                 p = i->u.choices.choicenames;
2216                 c = *p++;
2217                 while (*p) {
2218                     q = p;
2219                     while (*q && *q != c) q++;
2220                     str = snewn(q-p+1, char);
2221                     strncpy(str, p, q-p);
2222                     str[q-p] = '\0';
2223                     {
2224                         TCHAR ws[50];
2225                         MultiByteToWideChar (CP_ACP, 0, str, -1, ws, 50);
2226                         SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)ws);
2227                     }
2228                     
2229                     sfree(str);
2230                     if (*q) q++;
2231                     p = q;
2232                 }
2233             }
2234             SendMessage(ctl, CB_SETCURSEL, i->u.choices.selected, 0);
2235             break;
2236         }
2237
2238         y += 15;
2239     }
2240
2241 }
2242 #endif
2243
2244 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
2245                                   WPARAM wParam, LPARAM lParam)
2246 {
2247     frontend *fe = (frontend *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
2248     config_item *i;
2249     struct cfg_aux *j;
2250
2251     switch (msg) {
2252       case WM_INITDIALOG:
2253 #ifdef _WIN32_WCE
2254         {
2255             char *title;
2256
2257             fe = (frontend *) lParam;
2258             SetWindowLongPtr(hwnd, GWLP_USERDATA, lParam);
2259             fe->cfgbox = hwnd;
2260
2261             fe->cfg = frontend_get_config(fe, fe->cfg_which, &title);
2262
2263             make_dialog_full_screen(hwnd);
2264
2265             SetDlgItemTextA(hwnd, IDC_CONFIG_CAPTION, title);
2266             SendDlgItemMessage(hwnd, IDC_CONFIG_CAPTION, WM_SETFONT,
2267                                (WPARAM) dialog_title_font(), 0);
2268
2269             create_config_controls(fe);
2270         }
2271 #endif
2272         return TRUE;
2273
2274       case WM_COMMAND:
2275         /*
2276          * OK and Cancel are special cases.
2277          */
2278         if ((LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
2279             if (LOWORD(wParam) == IDOK) {
2280                 const char *err = frontend_set_config(
2281                     fe, fe->cfg_which, fe->cfg);
2282
2283                 if (err) {
2284                     MessageBox(hwnd, err, "Validation error",
2285                                MB_ICONERROR | MB_OK);
2286                 } else {
2287 #ifdef _WIN32_WCE
2288                     EndDialog(hwnd, 2);
2289 #else
2290                     fe->dlg_done = 2;
2291 #endif
2292                 }
2293             } else {
2294 #ifdef _WIN32_WCE
2295                 EndDialog(hwnd, 1);
2296 #else
2297                 fe->dlg_done = 1;
2298 #endif
2299             }
2300             return 0;
2301         }
2302
2303         /*
2304          * First find the control whose id this is.
2305          */
2306         for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2307             if (j->ctlid == LOWORD(wParam))
2308                 break;
2309         }
2310         if (i->type == C_END)
2311             return 0;                  /* not our problem */
2312
2313         if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
2314             char buffer[4096];
2315 #ifdef _WIN32_WCE
2316             TCHAR wBuffer[4096];
2317             GetDlgItemText(fe->cfgbox, j->ctlid, wBuffer, 4096);
2318             WideCharToMultiByte(CP_ACP, 0, wBuffer, -1, buffer, 4096, NULL, NULL);
2319 #else
2320             GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
2321 #endif
2322             buffer[lenof(buffer)-1] = '\0';
2323             sfree(i->u.string.sval);
2324             i->u.string.sval = dupstr(buffer);
2325         } else if (i->type == C_BOOLEAN && 
2326                    (HIWORD(wParam) == BN_CLICKED ||
2327                     HIWORD(wParam) == BN_DBLCLK)) {
2328             i->u.boolean.bval = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
2329         } else if (i->type == C_CHOICES &&
2330                    HIWORD(wParam) == CBN_SELCHANGE) {
2331             i->u.choices.selected = SendDlgItemMessage(fe->cfgbox, j->ctlid,
2332                                                        CB_GETCURSEL, 0, 0);
2333         }
2334
2335         return 0;
2336
2337       case WM_CLOSE:
2338         fe->dlg_done = 1;
2339         return 0;
2340     }
2341
2342     return 0;
2343 }
2344
2345 #ifndef _WIN32_WCE
2346 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2347             char *wclass, int wstyle,
2348             int exstyle, const char *wtext, INT_PTR wid)
2349 {
2350     HWND ret;
2351     ret = CreateWindowEx(exstyle, wclass, wtext,
2352                          wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
2353                          fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2354     SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
2355     return ret;
2356 }
2357 #endif
2358
2359 static void about(frontend *fe)
2360 {
2361 #ifdef _WIN32_WCE
2362     DialogBox(fe->inst, MAKEINTRESOURCE(IDD_ABOUT), fe->hwnd, AboutDlgProc);
2363 #else
2364     int i;
2365     WNDCLASS wc;
2366     MSG msg;
2367     TEXTMETRIC tm;
2368     HDC hdc;
2369     HFONT oldfont;
2370     SIZE size;
2371     int gm, id;
2372     int winwidth, winheight, y;
2373     int height, width, maxwid;
2374     const char *strings[16];
2375     int lengths[16];
2376     int nstrings = 0;
2377     char titlebuf[512];
2378
2379     sprintf(titlebuf, "About %.250s", fe->game->name);
2380
2381     strings[nstrings++] = fe->game->name;
2382     strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
2383     strings[nstrings++] = ver;
2384
2385     wc.style = CS_DBLCLKS | CS_SAVEBITS;
2386     wc.lpfnWndProc = DefDlgProc;
2387     wc.cbClsExtra = 0;
2388     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2389     wc.hInstance = fe->inst;
2390     wc.hIcon = NULL;
2391     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2392     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2393     wc.lpszMenuName = NULL;
2394     wc.lpszClassName = "GameAboutBox";
2395     RegisterClass(&wc);
2396
2397     hdc = GetDC(fe->hwnd);
2398     SetMapMode(hdc, MM_TEXT);
2399
2400     fe->dlg_done = FALSE;
2401
2402     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2403                              0, 0, 0, 0,
2404                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2405                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2406                              DEFAULT_QUALITY,
2407                              FF_SWISS,
2408                              "MS Shell Dlg");
2409
2410     oldfont = SelectObject(hdc, fe->cfgfont);
2411     if (GetTextMetrics(hdc, &tm)) {
2412         height = tm.tmAscent + tm.tmDescent;
2413         width = tm.tmAveCharWidth;
2414     } else {
2415         height = width = 30;
2416     }
2417
2418     /*
2419      * Figure out the layout of the About box by measuring the
2420      * length of each piece of text.
2421      */
2422     maxwid = 0;
2423     winheight = height/2;
2424
2425     for (i = 0; i < nstrings; i++) {
2426         if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
2427             lengths[i] = size.cx;
2428         else
2429             lengths[i] = 0;            /* *shrug* */
2430         if (maxwid < lengths[i])
2431             maxwid = lengths[i];
2432         winheight += height * 3 / 2 + (height / 2);
2433     }
2434
2435     winheight += height + height * 7 / 4;      /* OK button */
2436     winwidth = maxwid + 4*width;
2437
2438     SelectObject(hdc, oldfont);
2439     ReleaseDC(fe->hwnd, hdc);
2440
2441     /*
2442      * Create the dialog, now that we know its size.
2443      */
2444     {
2445         RECT r, r2;
2446
2447         r.left = r.top = 0;
2448         r.right = winwidth;
2449         r.bottom = winheight;
2450
2451         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2452                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2453                                 WS_CAPTION | WS_SYSMENU*/) &~
2454                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2455                            FALSE, 0);
2456
2457         /*
2458          * Centre the dialog on its parent window.
2459          */
2460         r.right -= r.left;
2461         r.bottom -= r.top;
2462         GetWindowRect(fe->hwnd, &r2);
2463         r.left = (r2.left + r2.right - r.right) / 2;
2464         r.top = (r2.top + r2.bottom - r.bottom) / 2;
2465         r.right += r.left;
2466         r.bottom += r.top;
2467
2468         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
2469                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2470                                     WS_CAPTION | WS_SYSMENU,
2471                                     r.left, r.top,
2472                                     r.right-r.left, r.bottom-r.top,
2473                                     fe->hwnd, NULL, fe->inst, NULL);
2474     }
2475
2476     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2477
2478     SetWindowLongPtr(fe->cfgbox, GWLP_USERDATA, (LONG_PTR)fe);
2479     SetWindowLongPtr(fe->cfgbox, DWLP_DLGPROC, (LONG_PTR)AboutDlgProc);
2480
2481     id = 1000;
2482     y = height/2;
2483     for (i = 0; i < nstrings; i++) {
2484         int border = width*2 + (maxwid - lengths[i]) / 2;
2485         mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
2486                "Static", 0, 0, strings[i], id++);
2487         y += height*3/2;
2488
2489         assert(y < winheight);
2490         y += height/2;
2491     }
2492
2493     y += height/2;                     /* extra space before OK */
2494     mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
2495            BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2496            "OK", IDOK);
2497
2498     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2499
2500     EnableWindow(fe->hwnd, FALSE);
2501     ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2502     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2503         if (!IsDialogMessage(fe->cfgbox, &msg))
2504             DispatchMessage(&msg);
2505         if (fe->dlg_done)
2506             break;
2507     }
2508     EnableWindow(fe->hwnd, TRUE);
2509     SetForegroundWindow(fe->hwnd);
2510     DestroyWindow(fe->cfgbox);
2511     DeleteObject(fe->cfgfont);
2512 #endif
2513 }
2514
2515 static int get_config(frontend *fe, int which)
2516 {
2517 #ifdef _WIN32_WCE
2518     fe->cfg_which = which;
2519
2520     return DialogBoxParam(fe->inst,
2521                           MAKEINTRESOURCE(IDD_CONFIG),
2522                           fe->hwnd, ConfigDlgProc,
2523                           (LPARAM) fe) == 2;
2524 #else
2525     config_item *i;
2526     struct cfg_aux *j;
2527     char *title;
2528     WNDCLASS wc;
2529     MSG msg;
2530     TEXTMETRIC tm;
2531     HDC hdc;
2532     HFONT oldfont;
2533     SIZE size;
2534     HWND ctl;
2535     int gm, id, nctrls;
2536     int winwidth, winheight, col1l, col1r, col2l, col2r, y;
2537     int height, width, maxlabel, maxcheckbox;
2538
2539     wc.style = CS_DBLCLKS | CS_SAVEBITS;
2540     wc.lpfnWndProc = DefDlgProc;
2541     wc.cbClsExtra = 0;
2542     wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2543     wc.hInstance = fe->inst;
2544     wc.hIcon = NULL;
2545     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2546     wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2547     wc.lpszMenuName = NULL;
2548     wc.lpszClassName = "GameConfigBox";
2549     RegisterClass(&wc);
2550
2551     hdc = GetDC(fe->hwnd);
2552     SetMapMode(hdc, MM_TEXT);
2553
2554     fe->dlg_done = FALSE;
2555
2556     fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2557                              0, 0, 0, 0,
2558                              FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2559                              OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2560                              DEFAULT_QUALITY,
2561                              FF_SWISS,
2562                              "MS Shell Dlg");
2563
2564     oldfont = SelectObject(hdc, fe->cfgfont);
2565     if (GetTextMetrics(hdc, &tm)) {
2566         height = tm.tmAscent + tm.tmDescent;
2567         width = tm.tmAveCharWidth;
2568     } else {
2569         height = width = 30;
2570     }
2571
2572     fe->cfg = frontend_get_config(fe, which, &title);
2573     fe->cfg_which = which;
2574
2575     /*
2576      * Figure out the layout of the config box by measuring the
2577      * length of each piece of text.
2578      */
2579     maxlabel = maxcheckbox = 0;
2580     winheight = height/2;
2581
2582     for (i = fe->cfg; i->type != C_END; i++) {
2583         switch (i->type) {
2584           case C_STRING:
2585           case C_CHOICES:
2586             /*
2587              * Both these control types have a label filling only
2588              * the left-hand column of the box.
2589              */
2590             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2591                 maxlabel < size.cx)
2592                 maxlabel = size.cx;
2593             winheight += height * 3 / 2 + (height / 2);
2594             break;
2595
2596           case C_BOOLEAN:
2597             /*
2598              * Checkboxes take up the whole of the box width.
2599              */
2600             if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2601                 maxcheckbox < size.cx)
2602                 maxcheckbox = size.cx;
2603             winheight += height + (height / 2);
2604             break;
2605         }
2606     }
2607
2608     winheight += height + height * 7 / 4;      /* OK / Cancel buttons */
2609
2610     col1l = 2*width;
2611     col1r = col1l + maxlabel;
2612     col2l = col1r + 2*width;
2613     col2r = col2l + 30*width;
2614     if (col2r < col1l+2*height+maxcheckbox)
2615         col2r = col1l+2*height+maxcheckbox;
2616     winwidth = col2r + 2*width;
2617
2618     SelectObject(hdc, oldfont);
2619     ReleaseDC(fe->hwnd, hdc);
2620
2621     /*
2622      * Create the dialog, now that we know its size.
2623      */
2624     {
2625         RECT r, r2;
2626
2627         r.left = r.top = 0;
2628         r.right = winwidth;
2629         r.bottom = winheight;
2630
2631         AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2632                                 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2633                                 WS_CAPTION | WS_SYSMENU*/) &~
2634                            (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2635                            FALSE, 0);
2636
2637         /*
2638          * Centre the dialog on its parent window.
2639          */
2640         r.right -= r.left;
2641         r.bottom -= r.top;
2642         GetWindowRect(fe->hwnd, &r2);
2643         r.left = (r2.left + r2.right - r.right) / 2;
2644         r.top = (r2.top + r2.bottom - r.bottom) / 2;
2645         r.right += r.left;
2646         r.bottom += r.top;
2647
2648         fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
2649                                     DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2650                                     WS_CAPTION | WS_SYSMENU,
2651                                     r.left, r.top,
2652                                     r.right-r.left, r.bottom-r.top,
2653                                     fe->hwnd, NULL, fe->inst, NULL);
2654         sfree(title);
2655     }
2656
2657     SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2658
2659     SetWindowLongPtr(fe->cfgbox, GWLP_USERDATA, (LONG_PTR)fe);
2660     SetWindowLongPtr(fe->cfgbox, DWLP_DLGPROC, (LONG_PTR)ConfigDlgProc);
2661
2662     /*
2663      * Count the controls so we can allocate cfgaux.
2664      */
2665     for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2666         nctrls++;
2667     fe->cfgaux = snewn(nctrls, struct cfg_aux);
2668
2669     id = 1000;
2670     y = height/2;
2671     for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2672         switch (i->type) {
2673           case C_STRING:
2674             /*
2675              * Edit box with a label beside it.
2676              */
2677             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2678                    "Static", 0, 0, i->name, id++);
2679             ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
2680                          "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
2681                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2682             SetWindowText(ctl, i->u.string.sval);
2683             y += height*3/2;
2684             break;
2685
2686           case C_BOOLEAN:
2687             /*
2688              * Simple checkbox.
2689              */
2690             mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
2691                    BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2692                    0, i->name, (j->ctlid = id++));
2693             CheckDlgButton(fe->cfgbox, j->ctlid, (i->u.boolean.bval != 0));
2694             y += height;
2695             break;
2696
2697           case C_CHOICES:
2698             /*
2699              * Drop-down list with a label beside it.
2700              */
2701             mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2702                    "STATIC", 0, 0, i->name, id++);
2703             ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
2704                          "COMBOBOX", WS_TABSTOP |
2705                          CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2706                          WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2707             {
2708                 char c;
2709                 const char *p, *q;
2710                 char *str;
2711
2712                 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
2713                 p = i->u.choices.choicenames;
2714                 c = *p++;
2715                 while (*p) {
2716                     q = p;
2717                     while (*q && *q != c) q++;
2718                     str = snewn(q-p+1, char);
2719                     strncpy(str, p, q-p);
2720                     str[q-p] = '\0';
2721                     SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
2722                     sfree(str);
2723                     if (*q) q++;
2724                     p = q;
2725                 }
2726             }
2727
2728             SendMessage(ctl, CB_SETCURSEL, i->u.choices.selected, 0);
2729
2730             y += height*3/2;
2731             break;
2732         }
2733
2734         assert(y < winheight);
2735         y += height/2;
2736     }
2737
2738     y += height/2;                     /* extra space before OK and Cancel */
2739     mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
2740            BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2741            "OK", IDOK);
2742     mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
2743            BS_PUSHBUTTON | WS_TABSTOP, 0, "Cancel", IDCANCEL);
2744
2745     SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2746
2747     EnableWindow(fe->hwnd, FALSE);
2748     ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2749     while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2750         if (!IsDialogMessage(fe->cfgbox, &msg))
2751             DispatchMessage(&msg);
2752         if (fe->dlg_done)
2753             break;
2754     }
2755     EnableWindow(fe->hwnd, TRUE);
2756     SetForegroundWindow(fe->hwnd);
2757     DestroyWindow(fe->cfgbox);
2758     DeleteObject(fe->cfgfont);
2759
2760     free_cfg(fe->cfg);
2761     sfree(fe->cfgaux);
2762
2763     return (fe->dlg_done == 2);
2764 #endif
2765 }
2766
2767 #ifdef _WIN32_WCE
2768 static void calculate_bitmap_position(frontend *fe, int x, int y)
2769 {
2770     /* Pocket PC - center the game in the full screen window */
2771     int yMargin;
2772     RECT rcClient;
2773
2774     GetClientRect(fe->hwnd, &rcClient);
2775     fe->bitmapPosition.left = (rcClient.right  - x) / 2;
2776     yMargin = rcClient.bottom - y;
2777
2778     if (fe->numpad != NULL) {
2779         RECT rcPad;
2780         GetWindowRect(fe->numpad, &rcPad);
2781         yMargin -= rcPad.bottom - rcPad.top;
2782     }
2783
2784     if (fe->statusbar != NULL) {
2785         RECT rcStatus;
2786         GetWindowRect(fe->statusbar, &rcStatus);
2787         yMargin -= rcStatus.bottom - rcStatus.top;
2788     }
2789
2790     fe->bitmapPosition.top = yMargin / 2;
2791
2792     fe->bitmapPosition.right  = fe->bitmapPosition.left + x;
2793     fe->bitmapPosition.bottom = fe->bitmapPosition.top  + y;
2794 }
2795 #else
2796 static void calculate_bitmap_position(frontend *fe, int x, int y)
2797 {
2798     /* Plain Windows - position the game in the upper-left corner */
2799     fe->bitmapPosition.left = 0;
2800     fe->bitmapPosition.top = 0;
2801     fe->bitmapPosition.right  = fe->bitmapPosition.left + x;
2802     fe->bitmapPosition.bottom = fe->bitmapPosition.top  + y;
2803 }
2804 #endif
2805
2806 static void new_bitmap(frontend *fe, int x, int y)
2807 {
2808     HDC hdc;
2809
2810     if (fe->bitmap) DeleteObject(fe->bitmap);
2811
2812     hdc = GetDC(fe->hwnd);
2813     fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2814     calculate_bitmap_position(fe, x, y);
2815     ReleaseDC(fe->hwnd, hdc);
2816 }
2817
2818 static void new_game_size(frontend *fe, float scale)
2819 {
2820     RECT r, sr;
2821     int x, y;
2822
2823     get_max_puzzle_size(fe, &x, &y);
2824     midend_size(fe->me, &x, &y, FALSE);
2825
2826     if (scale != 1.0) {
2827       x = (int)((float)x * fe->puzz_scale);
2828       y = (int)((float)y * fe->puzz_scale);
2829       midend_size(fe->me, &x, &y, TRUE);
2830     }
2831     fe->ymin = (fe->xmin * y) / x;
2832
2833     r.left = r.top = 0;
2834     r.right = x;
2835     r.bottom = y;
2836     AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2837
2838     if (fe->statusbar != NULL) {
2839         GetWindowRect(fe->statusbar, &sr);
2840     } else {
2841         sr.left = sr.right = sr.top = sr.bottom = 0;
2842     }
2843 #ifndef _WIN32_WCE
2844     SetWindowPos(fe->hwnd, NULL, 0, 0,
2845                  r.right - r.left,
2846                  r.bottom - r.top + sr.bottom - sr.top,
2847                  SWP_NOMOVE | SWP_NOZORDER);
2848 #endif
2849
2850     check_window_size(fe, &x, &y);
2851
2852 #ifndef _WIN32_WCE
2853     if (fe->statusbar != NULL)
2854         SetWindowPos(fe->statusbar, NULL, 0, y, x,
2855                      sr.bottom - sr.top, SWP_NOZORDER);
2856 #endif
2857
2858     new_bitmap(fe, x, y);
2859
2860 #ifdef _WIN32_WCE
2861     InvalidateRect(fe->hwnd, NULL, TRUE);
2862 #endif
2863     midend_redraw(fe->me);
2864 }
2865
2866 /*
2867  * Given a proposed new window rect, work out the resulting
2868  * difference in client size (from current), and use to try
2869  * and resize the puzzle, returning (wx,wy) as the actual
2870  * new window size.
2871  */
2872
2873 static void adjust_game_size(frontend *fe, RECT *proposed, int isedge,
2874                              int *wx_r, int *wy_r)
2875 {
2876     RECT cr, wr;
2877     int nx, ny, xdiff, ydiff, wx, wy;
2878
2879     /* Work out the current window sizing, and thus the
2880      * difference in size we're asking for. */
2881     GetClientRect(fe->hwnd, &cr);
2882     wr = cr;
2883     AdjustWindowRectEx(&wr, WINFLAGS, TRUE, 0);
2884
2885     xdiff = (proposed->right - proposed->left) - (wr.right - wr.left);
2886     ydiff = (proposed->bottom - proposed->top) - (wr.bottom - wr.top);
2887
2888     if (isedge) {
2889       /* These next four lines work around the fact that midend_size
2890        * is happy to shrink _but not grow_ if you change one dimension
2891        * but not the other. */
2892       if (xdiff > 0 && ydiff == 0)
2893         ydiff = (xdiff * (wr.right - wr.left)) / (wr.bottom - wr.top);
2894       if (xdiff == 0 && ydiff > 0)
2895         xdiff = (ydiff * (wr.bottom - wr.top)) / (wr.right - wr.left);
2896     }
2897
2898     if (check_window_resize(fe,
2899                             (cr.right - cr.left) + xdiff,
2900                             (cr.bottom - cr.top) + ydiff,
2901                             &nx, &ny, &wx, &wy)) {
2902         new_bitmap(fe, nx, ny);
2903         midend_force_redraw(fe->me);
2904     } else {
2905         /* reset size to current window size */
2906         wx = wr.right - wr.left;
2907         wy = wr.bottom - wr.top;
2908     }
2909     /* Re-fetch rectangle; size limits mean we might not have
2910      * taken it quite to the mouse drag positions. */
2911     GetClientRect(fe->hwnd, &cr);
2912     adjust_statusbar(fe, &cr);
2913
2914     *wx_r = wx; *wy_r = wy;
2915 }
2916
2917 static void update_type_menu_tick(frontend *fe)
2918 {
2919     int total, n, i;
2920
2921     if (fe->typemenu == INVALID_HANDLE_VALUE)
2922         return;
2923
2924     n = midend_which_preset(fe->me);
2925
2926     for (i = 0; i < fe->n_preset_menuitems; i++) {
2927         if (fe->preset_menuitems[i].which_menu) {
2928             int flag = (i == n ? MF_CHECKED : MF_UNCHECKED);
2929             CheckMenuItem(fe->preset_menuitems[i].which_menu,
2930                           fe->preset_menuitems[i].item_index,
2931                           MF_BYPOSITION | flag);
2932         }
2933     }
2934
2935     if (fe->game->can_configure) {
2936         int flag = (n < 0 ? MF_CHECKED : MF_UNCHECKED);
2937         /* "Custom" menu item is at the bottom of the top-level Type menu */
2938         total = GetMenuItemCount(fe->typemenu);
2939         CheckMenuItem(fe->typemenu, total - 1, MF_BYPOSITION | flag);
2940     }
2941
2942     DrawMenuBar(fe->hwnd);
2943 }
2944
2945 static void update_copy_menu_greying(frontend *fe)
2946 {
2947     UINT enable = (midend_can_format_as_text_now(fe->me) ?
2948                    MF_ENABLED : MF_GRAYED);
2949     EnableMenuItem(fe->gamemenu, IDM_COPY, MF_BYCOMMAND | enable);
2950 }
2951
2952 static void new_game_type(frontend *fe)
2953 {
2954     midend_new_game(fe->me);
2955     new_game_size(fe, 1.0);
2956     update_type_menu_tick(fe);
2957     update_copy_menu_greying(fe);
2958 }
2959
2960 static int is_alt_pressed(void)
2961 {
2962     BYTE keystate[256];
2963     int r = GetKeyboardState(keystate);
2964     if (!r)
2965         return FALSE;
2966     if (keystate[VK_MENU] & 0x80)
2967         return TRUE;
2968     if (keystate[VK_RMENU] & 0x80)
2969         return TRUE;
2970     return FALSE;
2971 }
2972
2973 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2974                                 WPARAM wParam, LPARAM lParam)
2975 {
2976     frontend *fe = (frontend *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
2977     int cmd;
2978
2979     switch (message) {
2980       case WM_CLOSE:
2981         DestroyWindow(hwnd);
2982         return 0;
2983       case WM_COMMAND:
2984 #ifdef _WIN32_WCE
2985         /* Numeric pad sends WM_COMMAND messages */
2986         if ((wParam >= IDM_KEYEMUL) && (wParam < IDM_KEYEMUL + 256))
2987         {
2988             midend_process_key(fe->me, 0, 0, wParam - IDM_KEYEMUL);
2989         }
2990 #endif
2991         cmd = wParam & ~0xF;           /* low 4 bits reserved to Windows */
2992         switch (cmd) {
2993           case IDM_NEW:
2994             if (!midend_process_key(fe->me, 0, 0, UI_NEWGAME))
2995                 PostQuitMessage(0);
2996             break;
2997           case IDM_RESTART:
2998             midend_restart_game(fe->me);
2999             break;
3000           case IDM_UNDO:
3001             if (!midend_process_key(fe->me, 0, 0, UI_UNDO))
3002                 PostQuitMessage(0);
3003             break;
3004           case IDM_REDO:
3005             if (!midend_process_key(fe->me, 0, 0, UI_REDO))
3006                 PostQuitMessage(0);
3007             break;
3008           case IDM_COPY:
3009             {
3010                 char *text = midend_text_format(fe->me);
3011                 if (text)
3012                     write_clip(hwnd, text);
3013                 else
3014                     MessageBeep(MB_ICONWARNING);
3015                 sfree(text);
3016             }
3017             break;
3018           case IDM_SOLVE:
3019             {
3020                 const char *msg = midend_solve(fe->me);
3021                 if (msg)
3022                     MessageBox(hwnd, msg, "Unable to solve",
3023                                MB_ICONERROR | MB_OK);
3024             }
3025             break;
3026           case IDM_QUIT:
3027             if (!midend_process_key(fe->me, 0, 0, UI_QUIT))
3028                 PostQuitMessage(0);
3029             break;
3030           case IDM_CONFIG:
3031             if (get_config(fe, CFG_SETTINGS))
3032                 new_game_type(fe);
3033             break;
3034           case IDM_SEED:
3035             if (get_config(fe, CFG_SEED))
3036                 new_game_type(fe);
3037             break;
3038           case IDM_DESC:
3039             if (get_config(fe, CFG_DESC))
3040                 new_game_type(fe);
3041             break;
3042           case IDM_PRINT:
3043             if (get_config(fe, CFG_PRINT))
3044                 print(fe);
3045             break;
3046           case IDM_ABOUT:
3047             about(fe);
3048             break;
3049           case IDM_LOAD:
3050           case IDM_SAVE:
3051             {
3052                 OPENFILENAME of;
3053                 char filename[FILENAME_MAX];
3054                 int ret;
3055
3056                 memset(&of, 0, sizeof(of));
3057                 of.hwndOwner = hwnd;
3058                 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
3059                 of.lpstrCustomFilter = NULL;
3060                 of.nFilterIndex = 1;
3061                 of.lpstrFile = filename;
3062                 filename[0] = '\0';
3063                 of.nMaxFile = lenof(filename);
3064                 of.lpstrFileTitle = NULL;
3065                 of.lpstrTitle = (cmd == IDM_SAVE ?
3066                                  "Enter name of game file to save" :
3067                                  "Enter name of saved game file to load");
3068                 of.Flags = 0;
3069 #ifdef OPENFILENAME_SIZE_VERSION_400
3070                 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
3071 #else
3072                 of.lStructSize = sizeof(of);
3073 #endif
3074                 of.lpstrInitialDir = NULL;
3075
3076                 if (cmd == IDM_SAVE)
3077                     ret = GetSaveFileName(&of);
3078                 else
3079                     ret = GetOpenFileName(&of);
3080
3081                 if (ret) {
3082                     if (cmd == IDM_SAVE) {
3083                         FILE *fp;
3084
3085                         if ((fp = fopen(filename, "r")) != NULL) {
3086                             char buf[256 + FILENAME_MAX];
3087                             fclose(fp);
3088                             /* file exists */
3089
3090                             sprintf(buf, "Are you sure you want to overwrite"
3091                                     " the file \"%.*s\"?",
3092                                     FILENAME_MAX, filename);
3093                             if (MessageBox(hwnd, buf, "Question",
3094                                            MB_YESNO | MB_ICONQUESTION)
3095                                 != IDYES)
3096                                 break;
3097                         }
3098
3099                         fp = fopen(filename, "w");
3100
3101                         if (!fp) {
3102                             MessageBox(hwnd, "Unable to open save file",
3103                                        "Error", MB_ICONERROR | MB_OK);
3104                             break;
3105                         }
3106
3107                         midend_serialise(fe->me, savefile_write, fp);
3108
3109                         fclose(fp);
3110                     } else {
3111                         FILE *fp = fopen(filename, "r");
3112                         const char *err = NULL;
3113                         char *err_w = NULL;
3114                         midend *me = fe->me;
3115 #ifdef COMBINED
3116                         char *id_name;
3117 #endif
3118
3119                         if (!fp) {
3120                             MessageBox(hwnd, "Unable to open saved game file",
3121                                        "Error", MB_ICONERROR | MB_OK);
3122                             break;
3123                         }
3124
3125 #ifdef COMBINED
3126                         /*
3127                          * This save file might be from a different
3128                          * game.
3129                          */
3130                         err = identify_game(&id_name, savefile_read, fp);
3131                         if (!err) {
3132                             int i;
3133                             for (i = 0; i < gamecount; i++)
3134                                 if (!strcmp(id_name, gamelist[i]->name))
3135                                     break;
3136                             if (i == gamecount) {
3137                                 err = "Save file is for a game not "
3138                                     "supported by this program";
3139                             } else {
3140                                 me = midend_for_new_game(fe, gamelist[i], NULL,
3141                                                          FALSE, FALSE, &err_w);
3142                                 err = err_w;
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                             sfree(err_w);
3156                             break;
3157                         }
3158
3159                         if (fe->me != me)
3160                             fe_set_midend(fe, me);
3161                         new_game_size(fe, 1.0);
3162                     }
3163                 }
3164             }
3165
3166             break;
3167 #ifndef _WIN32_WCE
3168           case IDM_HELPC:
3169             start_help(fe, NULL);
3170             break;
3171           case IDM_GAMEHELP:
3172             assert(help_type != NONE);
3173             start_help(fe, help_type == CHM ?
3174                        fe->game->htmlhelp_topic : fe->game->winhelp_topic);
3175             break;
3176 #endif
3177           default:
3178 #ifdef COMBINED
3179             if (wParam >= IDM_GAMES && wParam < (IDM_GAMES + (WPARAM)gamecount)) {
3180                 int p = wParam - IDM_GAMES;
3181                 char *error = NULL;
3182                 fe_set_midend(fe, midend_for_new_game(fe, gamelist[p], NULL,
3183                                                       FALSE, FALSE, &error));
3184                 sfree(error);
3185             } else
3186 #endif
3187             {
3188                 game_params *preset = preset_menu_lookup_by_id(
3189                     fe->preset_menu,
3190                     ((wParam &~ 0xF) - IDM_PRESETS) / 0x10);
3191
3192                 if (preset) {
3193                     midend_set_params(fe->me, preset);
3194                     new_game_type(fe);
3195                 }
3196             }
3197             break;
3198         }
3199         break;
3200       case WM_DESTROY:
3201 #ifndef _WIN32_WCE
3202         stop_help(fe);
3203 #endif
3204         frontend_free(fe);
3205         PostQuitMessage(0);
3206         return 0;
3207       case WM_PAINT:
3208         {
3209             PAINTSTRUCT p;
3210             HDC hdc, hdc2;
3211             HBITMAP prevbm;
3212             RECT rcDest;
3213
3214             hdc = BeginPaint(hwnd, &p);
3215             hdc2 = CreateCompatibleDC(hdc);
3216             prevbm = SelectObject(hdc2, fe->bitmap);
3217 #ifdef _WIN32_WCE
3218             FillRect(hdc, &(p.rcPaint), (HBRUSH) GetStockObject(WHITE_BRUSH));
3219 #endif
3220             IntersectRect(&rcDest, &(fe->bitmapPosition), &(p.rcPaint));
3221             BitBlt(hdc,
3222                    rcDest.left, rcDest.top,
3223                    rcDest.right - rcDest.left,
3224                    rcDest.bottom - rcDest.top,
3225                    hdc2,
3226                    rcDest.left - fe->bitmapPosition.left,
3227                    rcDest.top - fe->bitmapPosition.top,
3228                    SRCCOPY);
3229             SelectObject(hdc2, prevbm);
3230             DeleteDC(hdc2);
3231             EndPaint(hwnd, &p);
3232         }
3233         return 0;
3234       case WM_KEYDOWN:
3235         {
3236             int key = -1;
3237             BYTE keystate[256];
3238             int r = GetKeyboardState(keystate);
3239             int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
3240             int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
3241
3242             switch (wParam) {
3243               case VK_LEFT:
3244                 if (!(lParam & 0x01000000))
3245                     key = MOD_NUM_KEYPAD | '4';
3246                 else
3247                     key = shift | ctrl | CURSOR_LEFT;
3248                 break;
3249               case VK_RIGHT:
3250                 if (!(lParam & 0x01000000))
3251                     key = MOD_NUM_KEYPAD | '6';
3252                 else
3253                     key = shift | ctrl | CURSOR_RIGHT;
3254                 break;
3255               case VK_UP:
3256                 if (!(lParam & 0x01000000))
3257                     key = MOD_NUM_KEYPAD | '8';
3258                 else
3259                     key = shift | ctrl | CURSOR_UP;
3260                 break;
3261               case VK_DOWN:
3262                 if (!(lParam & 0x01000000))
3263                     key = MOD_NUM_KEYPAD | '2';
3264                 else
3265                     key = shift | ctrl | CURSOR_DOWN;
3266                 break;
3267                 /*
3268                  * Diagonal keys on the numeric keypad.
3269                  */
3270               case VK_PRIOR:
3271                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
3272                 break;
3273               case VK_NEXT:
3274                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
3275                 break;
3276               case VK_HOME:
3277                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
3278                 break;
3279               case VK_END:
3280                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
3281                 break;
3282               case VK_INSERT:
3283                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
3284                 break;
3285               case VK_CLEAR:
3286                 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
3287                 break;
3288                 /*
3289                  * Numeric keypad keys with Num Lock on.
3290                  */
3291               case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
3292               case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
3293               case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
3294               case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
3295               case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
3296               case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
3297               case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
3298               case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
3299               case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
3300               case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
3301             }
3302
3303             if (key != -1) {
3304                 if (!midend_process_key(fe->me, 0, 0, key))
3305                     PostQuitMessage(0);
3306             } else {
3307                 MSG m;
3308                 m.hwnd = hwnd;
3309                 m.message = WM_KEYDOWN;
3310                 m.wParam = wParam;
3311                 m.lParam = lParam & 0xdfff;
3312                 TranslateMessage(&m);
3313             }
3314         }
3315         break;
3316       case WM_LBUTTONDOWN:
3317       case WM_RBUTTONDOWN:
3318       case WM_MBUTTONDOWN:
3319         {
3320             int button;
3321
3322             /*
3323              * Shift-clicks count as middle-clicks, since otherwise
3324              * two-button Windows users won't have any kind of
3325              * middle click to use.
3326              */
3327             if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
3328                 button = MIDDLE_BUTTON;
3329             else if (message == WM_RBUTTONDOWN || is_alt_pressed())
3330                 button = RIGHT_BUTTON;
3331             else
3332 #ifndef _WIN32_WCE
3333                 button = LEFT_BUTTON;
3334 #else
3335                 if ((fe->game->flags & REQUIRE_RBUTTON) == 0)
3336                     button = LEFT_BUTTON;
3337                 else
3338                 {
3339                     SHRGINFO shrgi;
3340
3341                     shrgi.cbSize     = sizeof(SHRGINFO);
3342                     shrgi.hwndClient = hwnd;
3343                     shrgi.ptDown.x   = (signed short)LOWORD(lParam);
3344                     shrgi.ptDown.y   = (signed short)HIWORD(lParam);
3345                     shrgi.dwFlags    = SHRG_RETURNCMD;
3346
3347                     if (GN_CONTEXTMENU == SHRecognizeGesture(&shrgi))
3348                         button = RIGHT_BUTTON;
3349                     else
3350                         button = LEFT_BUTTON;
3351                 }
3352 #endif
3353
3354             if (!midend_process_key(fe->me,
3355                                     (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3356                                     (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3357                                     button))
3358                 PostQuitMessage(0);
3359
3360             SetCapture(hwnd);
3361         }
3362         break;
3363       case WM_LBUTTONUP:
3364       case WM_RBUTTONUP:
3365       case WM_MBUTTONUP:
3366         {
3367             int button;
3368
3369             /*
3370              * Shift-clicks count as middle-clicks, since otherwise
3371              * two-button Windows users won't have any kind of
3372              * middle click to use.
3373              */
3374             if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
3375                 button = MIDDLE_RELEASE;
3376             else if (message == WM_RBUTTONUP || is_alt_pressed())
3377                 button = RIGHT_RELEASE;
3378             else
3379                 button = LEFT_RELEASE;
3380
3381             if (!midend_process_key(fe->me,
3382                                     (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3383                                     (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3384                                     button))
3385                 PostQuitMessage(0);
3386
3387             ReleaseCapture();
3388         }
3389         break;
3390       case WM_MOUSEMOVE:
3391         {
3392             int button;
3393
3394             if (wParam & (MK_MBUTTON | MK_SHIFT))
3395                 button = MIDDLE_DRAG;
3396             else if (wParam & MK_RBUTTON || is_alt_pressed())
3397                 button = RIGHT_DRAG;
3398             else
3399                 button = LEFT_DRAG;
3400             
3401             if (!midend_process_key(fe->me,
3402                                     (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3403                                     (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3404                                     button))
3405                 PostQuitMessage(0);
3406         }
3407         break;
3408       case WM_CHAR:
3409         {
3410             int key = (unsigned char)wParam;
3411             if (key == '\x1A') {
3412                 BYTE keystate[256];
3413                 if (GetKeyboardState(keystate) &&
3414                     (keystate[VK_SHIFT] & 0x80) &&
3415                     (keystate[VK_CONTROL] & 0x80))
3416                     key = UI_REDO;
3417             }
3418             if (!midend_process_key(fe->me, 0, 0, key))
3419                 PostQuitMessage(0);
3420         }
3421         return 0;
3422       case WM_TIMER:
3423         if (fe->timer) {
3424             DWORD now = GetTickCount();
3425             float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
3426             midend_timer(fe->me, elapsed);
3427             fe->timer_last_tickcount = now;
3428         }
3429         return 0;
3430 #ifndef _WIN32_WCE
3431       case WM_SIZING:
3432         {
3433             RECT *sr = (RECT *)lParam;
3434             int wx, wy, isedge = 0;
3435
3436             if (wParam == WMSZ_TOP ||
3437                 wParam == WMSZ_RIGHT ||
3438                 wParam == WMSZ_BOTTOM ||
3439                 wParam == WMSZ_LEFT) isedge = 1;
3440             adjust_game_size(fe, sr, isedge, &wx, &wy);
3441
3442             /* Given the window size the puzzles constrain
3443              * us to, work out which edge we should be moving. */
3444             if (wParam == WMSZ_TOP ||
3445                 wParam == WMSZ_TOPLEFT ||
3446                 wParam == WMSZ_TOPRIGHT) {
3447                 sr->top = sr->bottom - wy;
3448             } else {
3449                 sr->bottom = sr->top + wy;
3450             }
3451             if (wParam == WMSZ_LEFT ||
3452                 wParam == WMSZ_TOPLEFT ||
3453                 wParam == WMSZ_BOTTOMLEFT) {
3454                 sr->left = sr->right - wx;
3455             } else {
3456                 sr->right = sr->left + wx;
3457             }
3458             return TRUE;
3459         }
3460         break;
3461 #endif
3462     }
3463
3464     return DefWindowProc(hwnd, message, wParam, lParam);
3465 }
3466
3467 #ifdef _WIN32_WCE
3468 static int FindPreviousInstance()
3469 {
3470     /* Check if application is running. If it's running then focus on the window */
3471     HWND hOtherWnd = NULL;
3472
3473     hOtherWnd = FindWindow (wGameName, wGameName);
3474     if (hOtherWnd)
3475     {
3476         SetForegroundWindow (hOtherWnd);
3477         return TRUE;
3478     }
3479
3480     return FALSE;
3481 }
3482 #endif
3483
3484 /*
3485  * Split a complete command line into argc/argv, attempting to do it
3486  * exactly the same way the Visual Studio C library would do it (so
3487  * that our console utilities, which receive argc and argv already
3488  * broken apart by the C library, will have their command lines
3489  * processed in the same way as the GUI utilities which get a whole
3490  * command line and must call this function).
3491  * 
3492  * Does not modify the input command line.
3493  * 
3494  * The final parameter (argstart) is used to return a second array
3495  * of char * pointers, the same length as argv, each one pointing
3496  * at the start of the corresponding element of argv in the
3497  * original command line. So if you get half way through processing
3498  * your command line in argc/argv form and then decide you want to
3499  * treat the rest as a raw string, you can. If you don't want to,
3500  * `argstart' can be safely left NULL.
3501  */
3502 void split_into_argv(char *cmdline, int *argc, char ***argv,
3503                      char ***argstart)
3504 {
3505     char *p;
3506     char *outputline, *q;
3507     char **outputargv, **outputargstart;
3508     int outputargc;
3509
3510     /*
3511      * These argument-breaking rules apply to Visual Studio 7, which
3512      * is currently the compiler expected to be used for the Windows
3513      * port of my puzzles. Visual Studio 10 has different rules,
3514      * lacking the curious mod 3 behaviour of consecutive quotes
3515      * described below; I presume they fixed a bug. As and when we
3516      * migrate to a newer compiler, we'll have to adjust this to
3517      * match; however, for the moment we faithfully imitate in our GUI
3518      * utilities what our CLI utilities can't be prevented from doing.
3519      *
3520      * When I investigated this, at first glance the rules appeared to
3521      * be:
3522      *
3523      *  - Single quotes are not special characters.
3524      *
3525      *  - Double quotes are removed, but within them spaces cease
3526      *    to be special.
3527      *
3528      *  - Backslashes are _only_ special when a sequence of them
3529      *    appear just before a double quote. In this situation,
3530      *    they are treated like C backslashes: so \" just gives a
3531      *    literal quote, \\" gives a literal backslash and then
3532      *    opens or closes a double-quoted segment, \\\" gives a
3533      *    literal backslash and then a literal quote, \\\\" gives
3534      *    two literal backslashes and then opens/closes a
3535      *    double-quoted segment, and so forth. Note that this
3536      *    behaviour is identical inside and outside double quotes.
3537      *
3538      *  - Two successive double quotes become one literal double
3539      *    quote, but only _inside_ a double-quoted segment.
3540      *    Outside, they just form an empty double-quoted segment
3541      *    (which may cause an empty argument word).
3542      *
3543      *  - That only leaves the interesting question of what happens
3544      *    when one or more backslashes precedes two or more double
3545      *    quotes, starting inside a double-quoted string. And the
3546      *    answer to that appears somewhat bizarre. Here I tabulate
3547      *    number of backslashes (across the top) against number of
3548      *    quotes (down the left), and indicate how many backslashes
3549      *    are output, how many quotes are output, and whether a
3550      *    quoted segment is open at the end of the sequence:
3551      * 
3552      *                      backslashes
3553      * 
3554      *               0         1      2      3      4
3555      * 
3556      *         0   0,0,y  |  1,0,y  2,0,y  3,0,y  4,0,y
3557      *            --------+-----------------------------
3558      *         1   0,0,n  |  0,1,y  1,0,n  1,1,y  2,0,n
3559      *    q    2   0,1,n  |  0,1,n  1,1,n  1,1,n  2,1,n
3560      *    u    3   0,1,y  |  0,2,n  1,1,y  1,2,n  2,1,y
3561      *    o    4   0,1,n  |  0,2,y  1,1,n  1,2,y  2,1,n
3562      *    t    5   0,2,n  |  0,2,n  1,2,n  1,2,n  2,2,n
3563      *    e    6   0,2,y  |  0,3,n  1,2,y  1,3,n  2,2,y
3564      *    s    7   0,2,n  |  0,3,y  1,2,n  1,3,y  2,2,n
3565      *         8   0,3,n  |  0,3,n  1,3,n  1,3,n  2,3,n
3566      *         9   0,3,y  |  0,4,n  1,3,y  1,4,n  2,3,y
3567      *        10   0,3,n  |  0,4,y  1,3,n  1,4,y  2,3,n
3568      *        11   0,4,n  |  0,4,n  1,4,n  1,4,n  2,4,n
3569      * 
3570      * 
3571      *      [Test fragment was of the form "a\\\"""b c" d.]
3572      * 
3573      * There is very weird mod-3 behaviour going on here in the
3574      * number of quotes, and it even applies when there aren't any
3575      * backslashes! How ghastly.
3576      * 
3577      * With a bit of thought, this extremely odd diagram suddenly
3578      * coalesced itself into a coherent, if still ghastly, model of
3579      * how things work:
3580      * 
3581      *  - As before, backslashes are only special when one or more
3582      *    of them appear contiguously before at least one double
3583      *    quote. In this situation the backslashes do exactly what
3584      *    you'd expect: each one quotes the next thing in front of
3585      *    it, so you end up with n/2 literal backslashes (if n is
3586      *    even) or (n-1)/2 literal backslashes and a literal quote
3587      *    (if n is odd). In the latter case the double quote
3588      *    character right after the backslashes is used up.
3589      * 
3590      *  - After that, any remaining double quotes are processed. A
3591      *    string of contiguous unescaped double quotes has a mod-3
3592      *    behaviour:
3593      * 
3594      *     * inside a quoted segment, a quote ends the segment.
3595      *     * _immediately_ after ending a quoted segment, a quote
3596      *       simply produces a literal quote.
3597      *     * otherwise, outside a quoted segment, a quote begins a
3598      *       quoted segment.
3599      * 
3600      *    So, for example, if we started inside a quoted segment
3601      *    then two contiguous quotes would close the segment and
3602      *    produce a literal quote; three would close the segment,
3603      *    produce a literal quote, and open a new segment. If we
3604      *    started outside a quoted segment, then two contiguous
3605      *    quotes would open and then close a segment, producing no
3606      *    output (but potentially creating a zero-length argument);
3607      *    but three quotes would open and close a segment and then
3608      *    produce a literal quote.
3609      */
3610
3611     /*
3612      * First deal with the simplest of all special cases: if there
3613      * aren't any arguments, return 0,NULL,NULL.
3614      */
3615     while (*cmdline && isspace(*cmdline)) cmdline++;
3616     if (!*cmdline) {
3617         if (argc) *argc = 0;
3618         if (argv) *argv = NULL;
3619         if (argstart) *argstart = NULL;
3620         return;
3621     }
3622
3623     /*
3624      * This will guaranteeably be big enough; we can realloc it
3625      * down later.
3626      */
3627     outputline = snewn(1+strlen(cmdline), char);
3628     outputargv = snewn(strlen(cmdline)+1 / 2, char *);
3629     outputargstart = snewn(strlen(cmdline)+1 / 2, char *);
3630
3631     p = cmdline; q = outputline; outputargc = 0;
3632
3633     while (*p) {
3634         int quote;
3635
3636         /* Skip whitespace searching for start of argument. */
3637         while (*p && isspace(*p)) p++;
3638         if (!*p) break;
3639
3640         /* We have an argument; start it. */
3641         outputargv[outputargc] = q;
3642         outputargstart[outputargc] = p;
3643         outputargc++;
3644         quote = 0;
3645
3646         /* Copy data into the argument until it's finished. */
3647         while (*p) {
3648             if (!quote && isspace(*p))
3649                 break;                 /* argument is finished */
3650
3651             if (*p == '"' || *p == '\\') {
3652                 /*
3653                  * We have a sequence of zero or more backslashes
3654                  * followed by a sequence of zero or more quotes.
3655                  * Count up how many of each, and then deal with
3656                  * them as appropriate.
3657                  */
3658                 int i, slashes = 0, quotes = 0;
3659                 while (*p == '\\') slashes++, p++;
3660                 while (*p == '"') quotes++, p++;
3661
3662                 if (!quotes) {
3663                     /*
3664                      * Special case: if there are no quotes,
3665                      * slashes are not special at all, so just copy
3666                      * n slashes to the output string.
3667                      */
3668                     while (slashes--) *q++ = '\\';
3669                 } else {
3670                     /* Slashes annihilate in pairs. */
3671                     while (slashes >= 2) slashes -= 2, *q++ = '\\';
3672
3673                     /* One remaining slash takes out the first quote. */
3674                     if (slashes) quotes--, *q++ = '"';
3675
3676                     if (quotes > 0) {
3677                         /* Outside a quote segment, a quote starts one. */
3678                         if (!quote) quotes--, quote = 1;
3679
3680                         /* Now we produce (n+1)/3 literal quotes... */
3681                         for (i = 3; i <= quotes+1; i += 3) *q++ = '"';
3682
3683                         /* ... and end in a quote segment iff 3 divides n. */
3684                         quote = (quotes % 3 == 0);
3685                     }
3686                 }
3687             } else {
3688                 *q++ = *p++;
3689             }
3690         }
3691
3692         /* At the end of an argument, just append a trailing NUL. */
3693         *q++ = '\0';
3694     }
3695
3696     outputargv = sresize(outputargv, outputargc, char *);
3697     outputargstart = sresize(outputargstart, outputargc, char *);
3698
3699     if (argc) *argc = outputargc;
3700     if (argv) *argv = outputargv; else sfree(outputargv);
3701     if (argstart) *argstart = outputargstart; else sfree(outputargstart);
3702 }
3703
3704 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
3705 {
3706     MSG msg;
3707     char *error = NULL;
3708     const game *gg;
3709     frontend *fe;
3710     midend *me;
3711     int argc;
3712     char **argv;
3713
3714     split_into_argv(cmdline, &argc, &argv, NULL);
3715
3716 #ifdef _WIN32_WCE
3717     MultiByteToWideChar (CP_ACP, 0, CLASSNAME, -1, wClassName, 256);
3718     if (FindPreviousInstance ())
3719         return 0;
3720 #endif
3721
3722     InitCommonControls();
3723
3724     if (!prev) {
3725         WNDCLASS wndclass;
3726
3727         wndclass.style = 0;
3728         wndclass.lpfnWndProc = WndProc;
3729         wndclass.cbClsExtra = 0;
3730         wndclass.cbWndExtra = 0;
3731         wndclass.hInstance = inst;
3732         wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
3733 #ifndef _WIN32_WCE
3734         if (!wndclass.hIcon)           /* in case resource file is absent */
3735             wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
3736 #endif
3737         wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
3738         wndclass.hbrBackground = NULL;
3739         wndclass.lpszMenuName = NULL;
3740 #ifdef _WIN32_WCE
3741         wndclass.lpszClassName = wClassName;
3742 #else
3743         wndclass.lpszClassName = CLASSNAME;
3744 #endif
3745
3746         RegisterClass(&wndclass);
3747     }
3748
3749     while (*cmdline && isspace((unsigned char)*cmdline))
3750         cmdline++;
3751
3752     init_help();
3753
3754 #ifdef COMBINED
3755     gg = gamelist[0];
3756     if (argc > 0) {
3757         int i;
3758         for (i = 0; i < gamecount; i++) {
3759             const char *p = gamelist[i]->name;
3760             char *q = argv[0];
3761             while (*p && *q) {
3762                 if (isspace((unsigned char)*p)) {
3763                     while (*q && isspace((unsigned char)*q))
3764                         q++;
3765                 } else {
3766                     if (tolower((unsigned char)*p) !=
3767                         tolower((unsigned char)*q))
3768                         break;
3769                     q++;
3770                 }
3771                 p++;
3772             }
3773             if (!*p) {
3774                 gg = gamelist[i];
3775                 --argc;
3776                 ++argv;
3777                 break;
3778             }
3779         }
3780     }
3781 #else
3782     gg = &thegame;
3783 #endif
3784
3785     fe = frontend_new(inst);
3786     me = midend_for_new_game(fe, gg, argc > 0 ? argv[0] : NULL,
3787                              TRUE, TRUE, &error);
3788     if (!me) {
3789         char buf[128];
3790 #ifdef COMBINED
3791         sprintf(buf, "Puzzles Error");
3792 #else
3793         sprintf(buf, "%.100s Error", gg->name);
3794 #endif
3795         MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
3796         sfree(error);
3797         return 1;
3798     }
3799     fe_set_midend(fe, me);
3800     show_window(fe);
3801
3802     while (GetMessage(&msg, NULL, 0, 0)) {
3803         DispatchMessage(&msg);
3804     }
3805
3806     DestroyWindow(fe->hwnd);
3807     cleanup_help();
3808
3809     return msg.wParam;
3810 }
3811 /* vim: set shiftwidth=4 tabstop=8: */