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