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