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