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