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