2 * windows.c: Windows front end for my puzzle collection.
9 #endif /* NO_HTMLHELP */
21 #define IDM_NEW 0x0010
22 #define IDM_RESTART 0x0020
23 #define IDM_UNDO 0x0030
24 #define IDM_REDO 0x0040
25 #define IDM_COPY 0x0050
26 #define IDM_SOLVE 0x0060
27 #define IDM_QUIT 0x0070
28 #define IDM_CONFIG 0x0080
29 #define IDM_DESC 0x0090
30 #define IDM_SEED 0x00A0
31 #define IDM_HELPC 0x00B0
32 #define IDM_GAMEHELP 0x00C0
33 #define IDM_ABOUT 0x00D0
34 #define IDM_SAVE 0x00E0
35 #define IDM_LOAD 0x00F0
36 #define IDM_PRINT 0x0100
37 #define IDM_PRESETS 0x0110
39 #define HELP_FILE_NAME "puzzles.hlp"
40 #define HELP_CNT_NAME "puzzles.cnt"
42 #define CHM_FILE_NAME "puzzles.chm"
43 #endif /* NO_HTMLHELP */
46 typedef HWND (CALLBACK *htmlhelp_t)(HWND, LPCSTR, UINT, DWORD);
47 static DWORD html_help_cookie;
48 static htmlhelp_t htmlhelp;
49 static HINSTANCE hh_dll;
50 #endif /* NO_HTMLHELP */
51 enum { NONE, HLP, CHM } help_type;
53 const char *help_topic;
54 int help_has_contents;
57 static FILE *debug_fp = NULL;
58 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
59 static int debug_got_console = 0;
65 if (!debug_got_console) {
67 debug_got_console = 1;
68 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
72 debug_fp = fopen("debug.log", "w");
75 if (debug_hdl != INVALID_HANDLE_VALUE) {
76 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
82 void debug_printf(char *fmt, ...)
88 vsprintf(buf, fmt, ap);
94 #define WINFLAGS (WS_OVERLAPPEDWINDOW &~ \
95 (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED))
97 static void new_game_size(frontend *fe);
115 enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
119 HWND hwnd, statusbar, cfgbox;
121 HBITMAP bitmap, prevbm;
128 DWORD timer_last_tickcount;
130 game_params **presets;
132 int nfonts, fontsize;
134 struct cfg_aux *cfgaux;
135 int cfg_which, dlg_done;
140 enum { DRAWING, PRINTING, NOTHING } drawstatus;
142 int printcount, printw, printh, printsolns, printcurr, printcolour;
144 int printoffsetx, printoffsety;
145 float printpixelscale;
151 void fatal(char *fmt, ...)
157 vsprintf(buf, fmt, ap);
160 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
165 char *geterrstr(void)
168 DWORD dw = GetLastError();
172 FORMAT_MESSAGE_ALLOCATE_BUFFER |
173 FORMAT_MESSAGE_FROM_SYSTEM,
176 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
180 ret = dupstr(lpMsgBuf);
187 void get_random_seed(void **randseed, int *randseedsize)
189 time_t *tp = snew(time_t);
191 *randseed = (void *)tp;
192 *randseedsize = sizeof(time_t);
195 static void win_status_bar(void *handle, char *text)
197 frontend *fe = (frontend *)handle;
199 SetWindowText(fe->statusbar, text);
202 static blitter *win_blitter_new(void *handle, int w, int h)
204 blitter *bl = snew(blitter);
206 memset(bl, 0, sizeof(blitter));
214 static void win_blitter_free(void *handle, blitter *bl)
216 if (bl->bitmap) DeleteObject(bl->bitmap);
220 static void blitter_mkbitmap(frontend *fe, blitter *bl)
222 HDC hdc = GetDC(fe->hwnd);
223 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
224 ReleaseDC(fe->hwnd, hdc);
227 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
229 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
231 frontend *fe = (frontend *)handle;
232 HDC hdc_win, hdc_blit;
235 assert(fe->drawstatus == DRAWING);
237 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
239 bl->x = x; bl->y = y;
241 hdc_win = GetDC(fe->hwnd);
242 hdc_blit = CreateCompatibleDC(hdc_win);
243 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
245 prev_blit = SelectObject(hdc_blit, bl->bitmap);
246 if (prev_blit == NULL || prev_blit == HGDI_ERROR)
247 fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
249 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
250 fe->hdc, x, y, SRCCOPY))
251 fatal("BitBlt failed: 0x%x", GetLastError());
253 SelectObject(hdc_blit, prev_blit);
255 ReleaseDC(fe->hwnd, hdc_win);
258 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
260 frontend *fe = (frontend *)handle;
261 HDC hdc_win, hdc_blit;
264 assert(fe->drawstatus == DRAWING);
266 assert(bl->bitmap); /* we should always have saved before loading */
268 if (x == BLITTER_FROMSAVED) x = bl->x;
269 if (y == BLITTER_FROMSAVED) y = bl->y;
271 hdc_win = GetDC(fe->hwnd);
272 hdc_blit = CreateCompatibleDC(hdc_win);
274 prev_blit = SelectObject(hdc_blit, bl->bitmap);
276 BitBlt(fe->hdc, x, y, bl->w, bl->h,
277 hdc_blit, 0, 0, SRCCOPY);
279 SelectObject(hdc_blit, prev_blit);
281 ReleaseDC(fe->hwnd, hdc_win);
284 void frontend_default_colour(frontend *fe, float *output)
286 DWORD c = GetSysColor(COLOR_MENU); /* ick */
288 output[0] = (float)(GetRValue(c) / 255.0);
289 output[1] = (float)(GetGValue(c) / 255.0);
290 output[2] = (float)(GetBValue(c) / 255.0);
293 static POINT win_transform_point(frontend *fe, int x, int y)
297 assert(fe->drawstatus != NOTHING);
299 if (fe->drawstatus == PRINTING) {
300 ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
301 ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
310 static void win_text_colour(frontend *fe, int colour)
312 assert(fe->drawstatus != NOTHING);
314 if (fe->drawstatus == PRINTING) {
317 print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
319 SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
321 SetTextColor(fe->hdc,
322 hatch == HATCH_CLEAR ? RGB(255,255,255) : RGB(0,0,0));
324 SetTextColor(fe->hdc, fe->colours[colour]);
328 static void win_set_brush(frontend *fe, int colour)
331 assert(fe->drawstatus != NOTHING);
333 if (fe->drawstatus == PRINTING) {
336 print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
339 br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
340 else if (hatch == HATCH_SOLID)
341 br = CreateSolidBrush(RGB(0,0,0));
342 else if (hatch == HATCH_CLEAR)
343 br = CreateSolidBrush(RGB(255,255,255));
345 br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
346 hatch == HATCH_SLASH ? HS_BDIAGONAL :
347 hatch == HATCH_HORIZ ? HS_HORIZONTAL :
348 hatch == HATCH_VERT ? HS_VERTICAL :
349 hatch == HATCH_PLUS ? HS_CROSS :
350 /* hatch == HATCH_X ? */ HS_DIAGCROSS,
353 br = fe->brushes[colour];
355 fe->oldbr = SelectObject(fe->hdc, br);
358 static void win_reset_brush(frontend *fe)
362 assert(fe->drawstatus != NOTHING);
364 br = SelectObject(fe->hdc, fe->oldbr);
365 if (fe->drawstatus == PRINTING)
369 static void win_set_pen(frontend *fe, int colour, int thin)
372 assert(fe->drawstatus != NOTHING);
374 if (fe->drawstatus == PRINTING) {
377 int width = thin ? 0 : fe->linewidth;
379 print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
381 pen = CreatePen(PS_SOLID, width,
382 RGB(r * 255, g * 255, b * 255));
383 else if (hatch == HATCH_SOLID)
384 pen = CreatePen(PS_SOLID, width, RGB(0, 0, 0));
385 else if (hatch == HATCH_CLEAR)
386 pen = CreatePen(PS_SOLID, width, RGB(255,255,255));
388 assert(!"This shouldn't happen");
389 pen = CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
392 pen = fe->pens[colour];
394 fe->oldpen = SelectObject(fe->hdc, pen);
397 static void win_reset_pen(frontend *fe)
401 assert(fe->drawstatus != NOTHING);
403 pen = SelectObject(fe->hdc, fe->oldpen);
404 if (fe->drawstatus == PRINTING)
408 static void win_clip(void *handle, int x, int y, int w, int h)
410 frontend *fe = (frontend *)handle;
413 if (fe->drawstatus == NOTHING)
416 p = win_transform_point(fe, x, y);
417 q = win_transform_point(fe, x+w, y+h);
418 IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
421 static void win_unclip(void *handle)
423 frontend *fe = (frontend *)handle;
425 if (fe->drawstatus == NOTHING)
428 SelectClipRgn(fe->hdc, NULL);
431 static void win_draw_text(void *handle, int x, int y, int fonttype,
432 int fontsize, int align, int colour, char *text)
434 frontend *fe = (frontend *)handle;
438 if (fe->drawstatus == NOTHING)
441 if (fe->drawstatus == PRINTING)
442 fontsize = (int)(fontsize * fe->printpixelscale);
444 xy = win_transform_point(fe, x, y);
447 * Find or create the font.
449 for (i = fe->fontstart; i < fe->nfonts; i++)
450 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
453 if (i == fe->nfonts) {
454 if (fe->fontsize <= fe->nfonts) {
455 fe->fontsize = fe->nfonts + 10;
456 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
461 fe->fonts[i].type = fonttype;
462 fe->fonts[i].size = fontsize;
464 fe->fonts[i].font = CreateFont(-fontsize, 0, 0, 0,
465 fe->drawstatus == PRINTING ? 0 : FW_BOLD,
466 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
467 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
469 (fonttype == FONT_FIXED ?
470 FIXED_PITCH | FF_DONTCARE :
471 VARIABLE_PITCH | FF_SWISS),
476 * Position and draw the text.
483 oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
484 if (GetTextMetrics(fe->hdc, &tm)) {
485 if (align & ALIGN_VCENTRE)
486 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
490 if (GetTextExtentPoint32(fe->hdc, text, strlen(text), &size)) {
491 if (align & ALIGN_HCENTRE)
493 else if (align & ALIGN_HRIGHT)
496 SetBkMode(fe->hdc, TRANSPARENT);
497 win_text_colour(fe, colour);
498 TextOut(fe->hdc, xy.x, xy.y, text, strlen(text));
499 SelectObject(fe->hdc, oldfont);
503 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
505 frontend *fe = (frontend *)handle;
508 if (fe->drawstatus == NOTHING)
511 if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
513 * Rectangle() appears to get uppity if asked to draw a 1x1
514 * rectangle, presumably on the grounds that that's beneath
515 * its dignity and you ought to be using SetPixel instead.
518 SetPixel(fe->hdc, x, y, fe->colours[colour]);
520 win_set_brush(fe, colour);
521 win_set_pen(fe, colour, TRUE);
522 p = win_transform_point(fe, x, y);
523 q = win_transform_point(fe, x+w, y+h);
524 Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
530 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
532 frontend *fe = (frontend *)handle;
535 if (fe->drawstatus == NOTHING)
538 win_set_pen(fe, colour, FALSE);
539 p = win_transform_point(fe, x1, y1);
540 q = win_transform_point(fe, x2, y2);
541 MoveToEx(fe->hdc, p.x, p.y, NULL);
542 LineTo(fe->hdc, q.x, q.y);
543 if (fe->drawstatus == DRAWING)
544 SetPixel(fe->hdc, q.x, q.y, fe->colours[colour]);
548 static void win_draw_circle(void *handle, int cx, int cy, int radius,
549 int fillcolour, int outlinecolour)
551 frontend *fe = (frontend *)handle;
554 assert(outlinecolour >= 0);
556 if (fe->drawstatus == NOTHING)
559 if (fillcolour >= 0) {
560 win_set_brush(fe, fillcolour);
561 win_set_pen(fe, outlinecolour, FALSE);
562 p = win_transform_point(fe, cx - radius, cy - radius);
563 q = win_transform_point(fe, cx + radius, cy + radius);
564 Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
568 win_set_pen(fe, outlinecolour, FALSE);
569 p = win_transform_point(fe, cx - radius, cy - radius);
570 q = win_transform_point(fe, cx + radius, cy + radius);
571 r = win_transform_point(fe, cx - radius, cy);
572 Arc(fe->hdc, p.x, p.y, q.x+1, q.y+1, r.x, r.y, r.x, r.y);
577 static void win_draw_polygon(void *handle, int *coords, int npoints,
578 int fillcolour, int outlinecolour)
580 frontend *fe = (frontend *)handle;
584 if (fe->drawstatus == NOTHING)
587 pts = snewn(npoints+1, POINT);
589 for (i = 0; i <= npoints; i++) {
590 int j = (i < npoints ? i : 0);
591 pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
594 assert(outlinecolour >= 0);
596 if (fillcolour >= 0) {
597 win_set_brush(fe, fillcolour);
598 win_set_pen(fe, outlinecolour, FALSE);
599 Polygon(fe->hdc, pts, npoints);
603 win_set_pen(fe, outlinecolour, FALSE);
604 Polyline(fe->hdc, pts, npoints+1);
611 static void win_start_draw(void *handle)
613 frontend *fe = (frontend *)handle;
616 assert(fe->drawstatus == NOTHING);
618 hdc_win = GetDC(fe->hwnd);
619 fe->hdc = CreateCompatibleDC(hdc_win);
620 fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
621 ReleaseDC(fe->hwnd, hdc_win);
623 SetMapMode(fe->hdc, MM_TEXT);
624 fe->drawstatus = DRAWING;
627 static void win_draw_update(void *handle, int x, int y, int w, int h)
629 frontend *fe = (frontend *)handle;
632 if (fe->drawstatus != DRAWING)
640 InvalidateRect(fe->hwnd, &r, FALSE);
643 static void win_end_draw(void *handle)
645 frontend *fe = (frontend *)handle;
646 assert(fe->drawstatus == DRAWING);
647 SelectObject(fe->hdc, fe->prevbm);
650 DeleteObject(fe->clip);
653 fe->drawstatus = NOTHING;
656 static void win_line_width(void *handle, float width)
658 frontend *fe = (frontend *)handle;
660 assert(fe->drawstatus != DRAWING);
661 if (fe->drawstatus == NOTHING)
664 fe->linewidth = (int)(width * fe->printpixelscale);
667 static void win_begin_doc(void *handle, int pages)
669 frontend *fe = (frontend *)handle;
671 assert(fe->drawstatus != DRAWING);
672 if (fe->drawstatus == NOTHING)
675 if (StartDoc(fe->hdc, &fe->di) <= 0) {
676 char *e = geterrstr();
677 MessageBox(fe->hwnd, e, "Error starting to print",
678 MB_ICONERROR | MB_OK);
680 fe->drawstatus = NOTHING;
684 * Push a marker on the font stack so that we won't use the
685 * same fonts for printing and drawing. (This is because
686 * drawing seems to look generally better in bold, but printing
687 * is better not in bold.)
689 fe->fontstart = fe->nfonts;
692 static void win_begin_page(void *handle, int number)
694 frontend *fe = (frontend *)handle;
696 assert(fe->drawstatus != DRAWING);
697 if (fe->drawstatus == NOTHING)
700 if (StartPage(fe->hdc) <= 0) {
701 char *e = geterrstr();
702 MessageBox(fe->hwnd, e, "Error starting a page",
703 MB_ICONERROR | MB_OK);
705 fe->drawstatus = NOTHING;
709 static void win_begin_puzzle(void *handle, float xm, float xc,
710 float ym, float yc, int pw, int ph, float wmm)
712 frontend *fe = (frontend *)handle;
713 int ppw, pph, pox, poy;
714 float mmpw, mmph, mmox, mmoy;
717 assert(fe->drawstatus != DRAWING);
718 if (fe->drawstatus == NOTHING)
721 ppw = GetDeviceCaps(fe->hdc, HORZRES);
722 pph = GetDeviceCaps(fe->hdc, VERTRES);
723 mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
724 mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
727 * Compute the puzzle's position on the logical page.
729 mmox = xm * mmpw + xc;
730 mmoy = ym * mmph + yc;
733 * Work out what that comes to in pixels.
735 pox = (int)(mmox * (float)ppw / mmpw);
736 poy = (int)(mmoy * (float)ppw / mmpw);
739 * And determine the scale.
741 * I need a scale such that the maximum puzzle-coordinate
742 * extent of the rectangle (pw * scale) is equal to the pixel
743 * equivalent of the puzzle's millimetre width (wmm * ppw /
746 scale = (wmm * ppw) / (mmpw * pw);
749 * Now store pox, poy and scale for use in the main drawing
752 fe->printoffsetx = pox;
753 fe->printoffsety = poy;
754 fe->printpixelscale = scale;
759 static void win_end_puzzle(void *handle)
761 /* Nothing needs to be done here. */
764 static void win_end_page(void *handle, int number)
766 frontend *fe = (frontend *)handle;
768 assert(fe->drawstatus != DRAWING);
770 if (fe->drawstatus == NOTHING)
773 if (EndPage(fe->hdc) <= 0) {
774 char *e = geterrstr();
775 MessageBox(fe->hwnd, e, "Error finishing a page",
776 MB_ICONERROR | MB_OK);
778 fe->drawstatus = NOTHING;
782 static void win_end_doc(void *handle)
784 frontend *fe = (frontend *)handle;
786 assert(fe->drawstatus != DRAWING);
789 * Free all the fonts created since we began printing.
791 while (fe->nfonts > fe->fontstart) {
793 DeleteObject(fe->fonts[fe->nfonts].font);
798 * The MSDN web site sample code doesn't bother to call EndDoc
799 * if an error occurs half way through printing. I expect doing
800 * so would cause the erroneous document to actually be
801 * printed, or something equally undesirable.
803 if (fe->drawstatus == NOTHING)
806 if (EndDoc(fe->hdc) <= 0) {
807 char *e = geterrstr();
808 MessageBox(fe->hwnd, e, "Error finishing printing",
809 MB_ICONERROR | MB_OK);
811 fe->drawstatus = NOTHING;
815 const struct drawing_api win_drawing = {
840 void print(frontend *fe)
845 midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
850 * Create our document structure and fill it up with puzzles.
852 doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
853 for (i = 0; i < fe->printcount; i++) {
854 if (i == 0 && fe->printcurr) {
855 err = midend_print_puzzle(fe->me, doc, fe->printsolns);
860 nme = midend_new(NULL, &thegame, NULL, NULL);
863 * Set the non-interactive mid-end to have the same
864 * parameters as the standard one.
866 params = midend_get_params(fe->me);
867 midend_set_params(nme, params);
868 thegame.free_params(params);
871 midend_new_game(nme);
872 err = midend_print_puzzle(nme, doc, fe->printsolns);
881 MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
882 MB_ICONERROR | MB_OK);
887 memset(&pd, 0, sizeof(pd));
888 pd.lStructSize = sizeof(pd);
889 pd.hwndOwner = fe->hwnd;
892 pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
893 PD_NOPAGENUMS | PD_NOSELECTION;
895 pd.nFromPage = pd.nToPage = 0xFFFF;
896 pd.nMinPage = pd.nMaxPage = 1;
898 if (!PrintDlg(&pd)) {
904 * Now pd.hDC is a device context for the printer.
908 * FIXME: IWBNI we put up an Abort box here.
911 memset(&fe->di, 0, sizeof(fe->di));
912 fe->di.cbSize = sizeof(fe->di);
913 sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
914 " Portable Puzzle Collection)", thegame.name);
915 fe->di.lpszDocName = doctitle;
916 fe->di.lpszOutput = NULL;
917 fe->di.lpszDatatype = NULL;
920 fe->drawstatus = PRINTING;
923 fe->dr = drawing_new(&win_drawing, NULL, fe);
924 document_print(doc, fe->dr);
925 drawing_free(fe->dr);
928 fe->drawstatus = NOTHING;
934 void deactivate_timer(frontend *fe)
937 return; /* for non-interactive midend */
938 if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
942 void activate_timer(frontend *fe)
945 return; /* for non-interactive midend */
947 fe->timer = SetTimer(fe->hwnd, fe->timer, 20, NULL);
948 fe->timer_last_tickcount = GetTickCount();
952 void write_clip(HWND hwnd, char *data)
960 * Windows expects CRLF in the clipboard, so we must convert
961 * any \n that has come out of the puzzle backend.
964 for (i = 0; data[i]; i++) {
969 data2 = snewn(len+1, char);
971 for (i = 0; data[i]; i++) {
974 data2[j++] = data[i];
979 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
982 lock = GlobalLock(clipdata);
985 memcpy(lock, data2, len);
986 ((unsigned char *) lock)[len] = 0;
987 GlobalUnlock(clipdata);
989 if (OpenClipboard(hwnd)) {
991 SetClipboardData(CF_TEXT, clipdata);
994 GlobalFree(clipdata);
1000 * Set up Help and see if we can find a help file.
1002 static void init_help(void)
1004 char b[2048], *p, *q, *r;
1008 * Find the executable file path, so we can look alongside
1009 * it for help files. Trim the filename off the end.
1011 GetModuleFileName(NULL, b, sizeof(b) - 1);
1013 p = strrchr(b, '\\');
1014 if (p && p >= r) r = p+1;
1015 q = strrchr(b, ':');
1016 if (q && q >= r) r = q+1;
1020 * Try HTML Help first.
1022 strcpy(r, CHM_FILE_NAME);
1023 if ( (fp = fopen(b, "r")) != NULL) {
1027 * We have a .CHM. See if we can use it.
1029 hh_dll = LoadLibrary("hhctrl.ocx");
1031 htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
1033 FreeLibrary(hh_dll);
1036 htmlhelp(NULL, NULL, HH_INITIALIZE, (DWORD)&html_help_cookie);
1037 help_path = dupstr(b);
1039 help_topic = thegame.htmlhelp_topic;
1043 #endif /* NO_HTMLHELP */
1046 * Now try old-style .HLP.
1048 strcpy(r, HELP_FILE_NAME);
1049 if ( (fp = fopen(b, "r")) != NULL) {
1052 help_path = dupstr(b);
1055 help_topic = thegame.winhelp_topic;
1058 * See if there's a .CNT file alongside it.
1060 strcpy(r, HELP_CNT_NAME);
1061 if ( (fp = fopen(b, "r")) != NULL) {
1063 help_has_contents = TRUE;
1065 help_has_contents = FALSE;
1070 help_type = NONE; /* didn't find any */
1076 static void start_help(frontend *fe, const char *topic)
1081 switch (help_type) {
1085 str = snewn(10+strlen(topic), char);
1086 sprintf(str, "JI(`',`%s')", topic);
1088 } else if (help_has_contents) {
1091 cmd = HELP_CONTENTS;
1093 WinHelp(fe->hwnd, help_path, cmd, (DWORD)str);
1094 fe->help_running = TRUE;
1101 str = snewn(20 + strlen(topic) + strlen(help_path), char);
1102 sprintf(str, "%s::/%s.html>main", help_path, topic);
1104 str = dupstr(help_path);
1106 htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
1107 fe->help_running = TRUE;
1109 #endif /* NO_HTMLHELP */
1111 assert(!"This shouldn't happen");
1119 * Stop Help on window cleanup.
1121 static void stop_help(frontend *fe)
1123 if (fe->help_running) {
1124 switch (help_type) {
1126 WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
1131 htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
1133 #endif /* NO_HTMLHELP */
1135 assert(!"This shouldn't happen");
1138 fe->help_running = FALSE;
1143 * Terminate Help on process exit.
1145 static void cleanup_help(void)
1148 if (help_type == CHM) {
1150 htmlhelp(NULL, NULL, HH_UNINITIALIZE, html_help_cookie);
1152 #endif /* NO_HTMLHELP */
1155 static void check_window_size(frontend *fe, int *px, int *py)
1160 if (fe->statusbar) {
1162 GetWindowRect(fe->statusbar, &sr);
1163 sy = sr.bottom - sr.top;
1169 * See if we actually got the window size we wanted, and adjust
1170 * the puzzle size if not.
1172 GetClientRect(fe->hwnd, &r);
1173 x = r.right - r.left;
1174 y = r.bottom - r.top - sy;
1175 midend_size(fe->me, &x, &y, FALSE);
1176 if (x != r.right - r.left || y != r.bottom - r.top) {
1178 * Resize the window, now we know what size we _really_
1184 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1185 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left, r.bottom - r.top,
1186 SWP_NOMOVE | SWP_NOZORDER);
1189 if (fe->statusbar) {
1190 GetClientRect(fe->hwnd, &r);
1191 SetWindowPos(fe->statusbar, NULL, 0, r.bottom-r.top-sy, r.right-r.left,
1199 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1203 if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1204 *x = sr.right - sr.left;
1205 *y = sr.bottom - sr.top;
1210 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1211 *x -= r.right - r.left - 100;
1212 *y -= r.bottom - r.top - 100;
1217 if (fe->statusbar != NULL) {
1218 GetWindowRect(fe->statusbar, &sr);
1219 *y -= sr.bottom - sr.top;
1223 static frontend *new_window(HINSTANCE inst, char *game_id, char **error)
1229 fe = snew(frontend);
1231 fe->me = midend_new(fe, &thegame, &win_drawing, fe);
1234 *error = midend_game_id(fe->me, game_id);
1236 midend_free(fe->me);
1247 fe->help_running = FALSE;
1249 fe->drawstatus = NOTHING;
1253 midend_new_game(fe->me);
1256 fe->nfonts = fe->fontsize = 0;
1262 colours = midend_colours(fe->me, &ncolours);
1264 fe->colours = snewn(ncolours, COLORREF);
1265 fe->brushes = snewn(ncolours, HBRUSH);
1266 fe->pens = snewn(ncolours, HPEN);
1268 for (i = 0; i < ncolours; i++) {
1269 fe->colours[i] = RGB(255 * colours[i*3+0],
1270 255 * colours[i*3+1],
1271 255 * colours[i*3+2]);
1272 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1273 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1278 if (midend_wants_statusbar(fe->me)) {
1279 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
1280 WS_CHILD | WS_VISIBLE,
1281 0, 0, 0, 0, /* status bar does these */
1282 NULL, NULL, inst, NULL);
1284 fe->statusbar = NULL;
1286 get_max_puzzle_size(fe, &x, &y);
1287 midend_size(fe->me, &x, &y, FALSE);
1292 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1294 fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
1295 WS_OVERLAPPEDWINDOW &~
1296 (WS_THICKFRAME | WS_MAXIMIZEBOX),
1297 CW_USEDEFAULT, CW_USEDEFAULT,
1298 r.right - r.left, r.bottom - r.top,
1299 NULL, NULL, inst, NULL);
1301 if (midend_wants_statusbar(fe->me)) {
1303 DestroyWindow(fe->statusbar);
1304 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
1305 WS_CHILD | WS_VISIBLE,
1306 0, 0, 0, 0, /* status bar does these */
1307 fe->hwnd, NULL, inst, NULL);
1309 * Now resize the window to take account of the status bar.
1311 GetWindowRect(fe->statusbar, &sr);
1312 GetWindowRect(fe->hwnd, &r);
1313 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1314 r.bottom - r.top + sr.bottom - sr.top,
1315 SWP_NOMOVE | SWP_NOZORDER);
1317 fe->statusbar = NULL;
1321 HMENU bar = CreateMenu();
1322 HMENU menu = CreateMenu();
1324 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Game");
1325 AppendMenu(menu, MF_ENABLED, IDM_NEW, "New");
1326 AppendMenu(menu, MF_ENABLED, IDM_RESTART, "Restart");
1327 AppendMenu(menu, MF_ENABLED, IDM_DESC, "Specific...");
1328 AppendMenu(menu, MF_ENABLED, IDM_SEED, "Random Seed...");
1330 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1331 thegame.can_configure) {
1332 HMENU sub = CreateMenu();
1335 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "Type");
1337 fe->presets = snewn(fe->npresets, game_params *);
1339 for (i = 0; i < fe->npresets; i++) {
1342 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1345 * FIXME: we ought to go through and do something
1346 * with ampersands here.
1349 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1352 if (thegame.can_configure) {
1353 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, "Custom...");
1357 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1358 AppendMenu(menu, MF_ENABLED, IDM_LOAD, "Load...");
1359 AppendMenu(menu, MF_ENABLED, IDM_SAVE, "Save...");
1360 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1361 if (thegame.can_print) {
1362 AppendMenu(menu, MF_ENABLED, IDM_PRINT, "Print...");
1363 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1365 AppendMenu(menu, MF_ENABLED, IDM_UNDO, "Undo");
1366 AppendMenu(menu, MF_ENABLED, IDM_REDO, "Redo");
1367 if (thegame.can_format_as_text) {
1368 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1369 AppendMenu(menu, MF_ENABLED, IDM_COPY, "Copy");
1371 if (thegame.can_solve) {
1372 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1373 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, "Solve");
1375 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1376 AppendMenu(menu, MF_ENABLED, IDM_QUIT, "Exit");
1377 menu = CreateMenu();
1378 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Help");
1379 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, "About");
1380 if (help_type != NONE) {
1381 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1382 AppendMenu(menu, MF_ENABLED, IDM_HELPC, "Contents");
1385 assert(thegame.name);
1386 item = snewn(9+strlen(thegame.name), char); /*ick*/
1387 sprintf(item, "Help on %s", thegame.name);
1388 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1392 SetMenu(fe->hwnd, bar);
1396 new_game_size(fe); /* initialises fe->bitmap */
1397 check_window_size(fe, &x, &y);
1399 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1401 ShowWindow(fe->hwnd, SW_NORMAL);
1402 SetForegroundWindow(fe->hwnd);
1404 midend_redraw(fe->me);
1409 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1410 WPARAM wParam, LPARAM lParam)
1412 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1419 if ((HIWORD(wParam) == BN_CLICKED ||
1420 HIWORD(wParam) == BN_DOUBLECLICKED) &&
1421 LOWORD(wParam) == IDOK)
1434 * Wrappers on midend_{get,set}_config, which extend the CFG_*
1435 * enumeration to add CFG_PRINT.
1437 static config_item *frontend_get_config(frontend *fe, int which,
1440 if (which < CFG_FRONTEND_SPECIFIC) {
1441 return midend_get_config(fe->me, which, wintitle);
1442 } else if (which == CFG_PRINT) {
1446 *wintitle = snewn(40 + strlen(thegame.name), char);
1447 sprintf(*wintitle, "%s print setup", thegame.name);
1449 ret = snewn(8, config_item);
1453 ret[i].name = "Number of puzzles to print";
1454 ret[i].type = C_STRING;
1455 ret[i].sval = dupstr("1");
1459 ret[i].name = "Number of puzzles across the page";
1460 ret[i].type = C_STRING;
1461 ret[i].sval = dupstr("1");
1465 ret[i].name = "Number of puzzles down the page";
1466 ret[i].type = C_STRING;
1467 ret[i].sval = dupstr("1");
1471 ret[i].name = "Percentage of standard size";
1472 ret[i].type = C_STRING;
1473 ret[i].sval = dupstr("100.0");
1477 ret[i].name = "Include currently shown puzzle";
1478 ret[i].type = C_BOOLEAN;
1483 ret[i].name = "Print solutions";
1484 ret[i].type = C_BOOLEAN;
1486 ret[i].ival = FALSE;
1489 if (thegame.can_print_in_colour) {
1490 ret[i].name = "Print in colour";
1491 ret[i].type = C_BOOLEAN;
1493 ret[i].ival = FALSE;
1498 ret[i].type = C_END;
1505 assert(!"We should never get here");
1510 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
1512 if (which < CFG_FRONTEND_SPECIFIC) {
1513 return midend_set_config(fe->me, which, cfg);
1514 } else if (which == CFG_PRINT) {
1515 if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
1516 return "Number of puzzles to print should be at least one";
1517 if ((fe->printw = atoi(cfg[1].sval)) <= 0)
1518 return "Number of puzzles across the page should be at least one";
1519 if ((fe->printh = atoi(cfg[2].sval)) <= 0)
1520 return "Number of puzzles down the page should be at least one";
1521 if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
1522 return "Print size should be positive";
1523 fe->printcurr = cfg[4].ival;
1524 fe->printsolns = cfg[5].ival;
1525 fe->printcolour = thegame.can_print_in_colour && cfg[6].ival;
1528 assert(!"We should never get here");
1529 return "Internal error";
1533 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
1534 WPARAM wParam, LPARAM lParam)
1536 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1546 * OK and Cancel are special cases.
1548 if ((HIWORD(wParam) == BN_CLICKED ||
1549 HIWORD(wParam) == BN_DOUBLECLICKED) &&
1550 (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
1551 if (LOWORD(wParam) == IDOK) {
1552 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
1555 MessageBox(hwnd, err, "Validation error",
1556 MB_ICONERROR | MB_OK);
1567 * First find the control whose id this is.
1569 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1570 if (j->ctlid == LOWORD(wParam))
1573 if (i->type == C_END)
1574 return 0; /* not our problem */
1576 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
1578 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
1579 buffer[lenof(buffer)-1] = '\0';
1581 i->sval = dupstr(buffer);
1582 } else if (i->type == C_BOOLEAN &&
1583 (HIWORD(wParam) == BN_CLICKED ||
1584 HIWORD(wParam) == BN_DOUBLECLICKED)) {
1585 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
1586 } else if (i->type == C_CHOICES &&
1587 HIWORD(wParam) == CBN_SELCHANGE) {
1588 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
1589 CB_GETCURSEL, 0, 0);
1602 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
1603 char *wclass, int wstyle,
1604 int exstyle, const char *wtext, int wid)
1607 ret = CreateWindowEx(exstyle, wclass, wtext,
1608 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
1609 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
1610 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
1614 static void about(frontend *fe)
1624 int winwidth, winheight, y;
1625 int height, width, maxwid;
1626 const char *strings[16];
1631 sprintf(titlebuf, "About %.250s", thegame.name);
1633 strings[nstrings++] = thegame.name;
1634 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
1635 strings[nstrings++] = ver;
1637 wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1638 wc.lpfnWndProc = DefDlgProc;
1640 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1641 wc.hInstance = fe->inst;
1643 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1644 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1645 wc.lpszMenuName = NULL;
1646 wc.lpszClassName = "GameAboutBox";
1649 hdc = GetDC(fe->hwnd);
1650 SetMapMode(hdc, MM_TEXT);
1652 fe->dlg_done = FALSE;
1654 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1656 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1657 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1662 oldfont = SelectObject(hdc, fe->cfgfont);
1663 if (GetTextMetrics(hdc, &tm)) {
1664 height = tm.tmAscent + tm.tmDescent;
1665 width = tm.tmAveCharWidth;
1667 height = width = 30;
1671 * Figure out the layout of the About box by measuring the
1672 * length of each piece of text.
1675 winheight = height/2;
1677 for (i = 0; i < nstrings; i++) {
1678 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
1679 lengths[i] = size.cx;
1681 lengths[i] = 0; /* *shrug* */
1682 if (maxwid < lengths[i])
1683 maxwid = lengths[i];
1684 winheight += height * 3 / 2 + (height / 2);
1687 winheight += height + height * 7 / 4; /* OK button */
1688 winwidth = maxwid + 4*width;
1690 SelectObject(hdc, oldfont);
1691 ReleaseDC(fe->hwnd, hdc);
1694 * Create the dialog, now that we know its size.
1701 r.bottom = winheight;
1703 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1704 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1705 WS_CAPTION | WS_SYSMENU*/) &~
1706 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1710 * Centre the dialog on its parent window.
1714 GetWindowRect(fe->hwnd, &r2);
1715 r.left = (r2.left + r2.right - r.right) / 2;
1716 r.top = (r2.top + r2.bottom - r.bottom) / 2;
1720 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
1721 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1722 WS_CAPTION | WS_SYSMENU,
1724 r.right-r.left, r.bottom-r.top,
1725 fe->hwnd, NULL, fe->inst, NULL);
1728 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1730 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1731 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
1735 for (i = 0; i < nstrings; i++) {
1736 int border = width*2 + (maxwid - lengths[i]) / 2;
1737 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
1738 "Static", 0, 0, strings[i], id++);
1741 assert(y < winheight);
1745 y += height/2; /* extra space before OK */
1746 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
1747 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1750 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1752 EnableWindow(fe->hwnd, FALSE);
1753 ShowWindow(fe->cfgbox, SW_NORMAL);
1754 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1755 if (!IsDialogMessage(fe->cfgbox, &msg))
1756 DispatchMessage(&msg);
1760 EnableWindow(fe->hwnd, TRUE);
1761 SetForegroundWindow(fe->hwnd);
1762 DestroyWindow(fe->cfgbox);
1763 DeleteObject(fe->cfgfont);
1766 static int get_config(frontend *fe, int which)
1779 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
1780 int height, width, maxlabel, maxcheckbox;
1782 wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1783 wc.lpfnWndProc = DefDlgProc;
1785 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1786 wc.hInstance = fe->inst;
1788 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1789 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1790 wc.lpszMenuName = NULL;
1791 wc.lpszClassName = "GameConfigBox";
1794 hdc = GetDC(fe->hwnd);
1795 SetMapMode(hdc, MM_TEXT);
1797 fe->dlg_done = FALSE;
1799 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1801 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1802 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1807 oldfont = SelectObject(hdc, fe->cfgfont);
1808 if (GetTextMetrics(hdc, &tm)) {
1809 height = tm.tmAscent + tm.tmDescent;
1810 width = tm.tmAveCharWidth;
1812 height = width = 30;
1815 fe->cfg = frontend_get_config(fe, which, &title);
1816 fe->cfg_which = which;
1819 * Figure out the layout of the config box by measuring the
1820 * length of each piece of text.
1822 maxlabel = maxcheckbox = 0;
1823 winheight = height/2;
1825 for (i = fe->cfg; i->type != C_END; i++) {
1830 * Both these control types have a label filling only
1831 * the left-hand column of the box.
1833 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1836 winheight += height * 3 / 2 + (height / 2);
1841 * Checkboxes take up the whole of the box width.
1843 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1844 maxcheckbox < size.cx)
1845 maxcheckbox = size.cx;
1846 winheight += height + (height / 2);
1851 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
1854 col1r = col1l + maxlabel;
1855 col2l = col1r + 2*width;
1856 col2r = col2l + 30*width;
1857 if (col2r < col1l+2*height+maxcheckbox)
1858 col2r = col1l+2*height+maxcheckbox;
1859 winwidth = col2r + 2*width;
1861 SelectObject(hdc, oldfont);
1862 ReleaseDC(fe->hwnd, hdc);
1865 * Create the dialog, now that we know its size.
1872 r.bottom = winheight;
1874 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1875 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1876 WS_CAPTION | WS_SYSMENU*/) &~
1877 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1881 * Centre the dialog on its parent window.
1885 GetWindowRect(fe->hwnd, &r2);
1886 r.left = (r2.left + r2.right - r.right) / 2;
1887 r.top = (r2.top + r2.bottom - r.bottom) / 2;
1891 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
1892 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1893 WS_CAPTION | WS_SYSMENU,
1895 r.right-r.left, r.bottom-r.top,
1896 fe->hwnd, NULL, fe->inst, NULL);
1900 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1902 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1903 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
1906 * Count the controls so we can allocate cfgaux.
1908 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
1910 fe->cfgaux = snewn(nctrls, struct cfg_aux);
1914 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1918 * Edit box with a label beside it.
1920 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1921 "Static", 0, 0, i->name, id++);
1922 ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
1923 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
1924 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1925 SetWindowText(ctl, i->sval);
1933 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
1934 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
1935 0, i->name, (j->ctlid = id++));
1936 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
1942 * Drop-down list with a label beside it.
1944 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1945 "STATIC", 0, 0, i->name, id++);
1946 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
1947 "COMBOBOX", WS_TABSTOP |
1948 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
1949 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1951 char c, *p, *q, *str;
1953 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
1958 while (*q && *q != c) q++;
1959 str = snewn(q-p+1, char);
1960 strncpy(str, p, q-p);
1962 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
1969 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
1975 assert(y < winheight);
1979 y += height/2; /* extra space before OK and Cancel */
1980 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
1981 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1983 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
1984 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP, 0, "Cancel", IDCANCEL);
1986 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1988 EnableWindow(fe->hwnd, FALSE);
1989 ShowWindow(fe->cfgbox, SW_NORMAL);
1990 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1991 if (!IsDialogMessage(fe->cfgbox, &msg))
1992 DispatchMessage(&msg);
1996 EnableWindow(fe->hwnd, TRUE);
1997 SetForegroundWindow(fe->hwnd);
1998 DestroyWindow(fe->cfgbox);
1999 DeleteObject(fe->cfgfont);
2004 return (fe->dlg_done == 2);
2007 static void new_game_size(frontend *fe)
2013 get_max_puzzle_size(fe, &x, &y);
2014 midend_size(fe->me, &x, &y, FALSE);
2019 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2021 if (fe->statusbar != NULL) {
2022 GetWindowRect(fe->statusbar, &sr);
2024 sr.left = sr.right = sr.top = sr.bottom = 0;
2026 SetWindowPos(fe->hwnd, NULL, 0, 0,
2028 r.bottom - r.top + sr.bottom - sr.top,
2029 SWP_NOMOVE | SWP_NOZORDER);
2031 check_window_size(fe, &x, &y);
2033 if (fe->statusbar != NULL)
2034 SetWindowPos(fe->statusbar, NULL, 0, y, x,
2035 sr.bottom - sr.top, SWP_NOZORDER);
2037 if (fe->bitmap) DeleteObject(fe->bitmap);
2039 hdc = GetDC(fe->hwnd);
2040 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2041 ReleaseDC(fe->hwnd, hdc);
2043 midend_redraw(fe->me);
2046 static void new_game_type(frontend *fe)
2048 midend_new_game(fe->me);
2052 static int is_alt_pressed(void)
2055 int r = GetKeyboardState(keystate);
2058 if (keystate[VK_MENU] & 0x80)
2060 if (keystate[VK_RMENU] & 0x80)
2065 static void savefile_write(void *wctx, void *buf, int len)
2067 FILE *fp = (FILE *)wctx;
2068 fwrite(buf, 1, len, fp);
2071 static int savefile_read(void *wctx, void *buf, int len)
2073 FILE *fp = (FILE *)wctx;
2076 ret = fread(buf, 1, len, fp);
2077 return (ret == len);
2080 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2081 WPARAM wParam, LPARAM lParam)
2083 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2088 DestroyWindow(hwnd);
2091 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
2094 if (!midend_process_key(fe->me, 0, 0, 'n'))
2098 midend_restart_game(fe->me);
2101 if (!midend_process_key(fe->me, 0, 0, 'u'))
2105 if (!midend_process_key(fe->me, 0, 0, '\x12'))
2110 char *text = midend_text_format(fe->me);
2112 write_clip(hwnd, text);
2114 MessageBeep(MB_ICONWARNING);
2120 char *msg = midend_solve(fe->me);
2122 MessageBox(hwnd, msg, "Unable to solve",
2123 MB_ICONERROR | MB_OK);
2127 if (!midend_process_key(fe->me, 0, 0, 'q'))
2131 if (get_config(fe, CFG_SETTINGS))
2135 if (get_config(fe, CFG_SEED))
2139 if (get_config(fe, CFG_DESC))
2143 if (get_config(fe, CFG_PRINT))
2153 char filename[FILENAME_MAX];
2156 memset(&of, 0, sizeof(of));
2157 of.hwndOwner = hwnd;
2158 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
2159 of.lpstrCustomFilter = NULL;
2160 of.nFilterIndex = 1;
2161 of.lpstrFile = filename;
2163 of.nMaxFile = lenof(filename);
2164 of.lpstrFileTitle = NULL;
2165 of.lpstrTitle = (cmd == IDM_SAVE ?
2166 "Enter name of game file to save" :
2167 "Enter name of saved game file to load");
2169 #ifdef OPENFILENAME_SIZE_VERSION_400
2170 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2172 of.lStructSize = sizeof(of);
2174 of.lpstrInitialDir = NULL;
2176 if (cmd == IDM_SAVE)
2177 ret = GetSaveFileName(&of);
2179 ret = GetOpenFileName(&of);
2182 if (cmd == IDM_SAVE) {
2185 if ((fp = fopen(filename, "r")) != NULL) {
2186 char buf[256 + FILENAME_MAX];
2190 sprintf(buf, "Are you sure you want to overwrite"
2191 " the file \"%.*s\"?",
2192 FILENAME_MAX, filename);
2193 if (MessageBox(hwnd, buf, "Question",
2194 MB_YESNO | MB_ICONQUESTION)
2199 fp = fopen(filename, "w");
2202 MessageBox(hwnd, "Unable to open save file",
2203 "Error", MB_ICONERROR | MB_OK);
2207 midend_serialise(fe->me, savefile_write, fp);
2211 FILE *fp = fopen(filename, "r");
2215 MessageBox(hwnd, "Unable to open saved game file",
2216 "Error", MB_ICONERROR | MB_OK);
2220 err = midend_deserialise(fe->me, savefile_read, fp);
2225 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
2236 start_help(fe, NULL);
2239 start_help(fe, help_topic);
2243 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
2245 if (p >= 0 && p < fe->npresets) {
2246 midend_set_params(fe->me, fe->presets[p]);
2263 hdc = BeginPaint(hwnd, &p);
2264 hdc2 = CreateCompatibleDC(hdc);
2265 prevbm = SelectObject(hdc2, fe->bitmap);
2267 p.rcPaint.left, p.rcPaint.top,
2268 p.rcPaint.right - p.rcPaint.left,
2269 p.rcPaint.bottom - p.rcPaint.top,
2271 p.rcPaint.left, p.rcPaint.top,
2273 SelectObject(hdc2, prevbm);
2282 int r = GetKeyboardState(keystate);
2283 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
2284 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
2288 if (!(lParam & 0x01000000))
2289 key = MOD_NUM_KEYPAD | '4';
2291 key = shift | ctrl | CURSOR_LEFT;
2294 if (!(lParam & 0x01000000))
2295 key = MOD_NUM_KEYPAD | '6';
2297 key = shift | ctrl | CURSOR_RIGHT;
2300 if (!(lParam & 0x01000000))
2301 key = MOD_NUM_KEYPAD | '8';
2303 key = shift | ctrl | CURSOR_UP;
2306 if (!(lParam & 0x01000000))
2307 key = MOD_NUM_KEYPAD | '2';
2309 key = shift | ctrl | CURSOR_DOWN;
2312 * Diagonal keys on the numeric keypad.
2315 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
2318 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
2321 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
2324 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
2327 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
2330 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
2333 * Numeric keypad keys with Num Lock on.
2335 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
2336 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
2337 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
2338 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
2339 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
2340 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
2341 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
2342 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
2343 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
2344 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
2348 if (!midend_process_key(fe->me, 0, 0, key))
2353 m.message = WM_KEYDOWN;
2355 m.lParam = lParam & 0xdfff;
2356 TranslateMessage(&m);
2360 case WM_LBUTTONDOWN:
2361 case WM_RBUTTONDOWN:
2362 case WM_MBUTTONDOWN:
2367 * Shift-clicks count as middle-clicks, since otherwise
2368 * two-button Windows users won't have any kind of
2369 * middle click to use.
2371 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
2372 button = MIDDLE_BUTTON;
2373 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
2374 button = RIGHT_BUTTON;
2376 button = LEFT_BUTTON;
2378 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2379 (signed short)HIWORD(lParam), button))
2392 * Shift-clicks count as middle-clicks, since otherwise
2393 * two-button Windows users won't have any kind of
2394 * middle click to use.
2396 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
2397 button = MIDDLE_RELEASE;
2398 else if (message == WM_RBUTTONUP || is_alt_pressed())
2399 button = RIGHT_RELEASE;
2401 button = LEFT_RELEASE;
2403 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2404 (signed short)HIWORD(lParam), button))
2414 if (wParam & (MK_MBUTTON | MK_SHIFT))
2415 button = MIDDLE_DRAG;
2416 else if (wParam & MK_RBUTTON || is_alt_pressed())
2417 button = RIGHT_DRAG;
2421 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2422 (signed short)HIWORD(lParam), button))
2427 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
2432 DWORD now = GetTickCount();
2433 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
2434 midend_timer(fe->me, elapsed);
2435 fe->timer_last_tickcount = now;
2440 return DefWindowProc(hwnd, message, wParam, lParam);
2443 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
2448 InitCommonControls();
2454 wndclass.lpfnWndProc = WndProc;
2455 wndclass.cbClsExtra = 0;
2456 wndclass.cbWndExtra = 0;
2457 wndclass.hInstance = inst;
2458 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
2459 if (!wndclass.hIcon) /* in case resource file is absent */
2460 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
2461 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
2462 wndclass.hbrBackground = NULL;
2463 wndclass.lpszMenuName = NULL;
2464 wndclass.lpszClassName = thegame.name;
2466 RegisterClass(&wndclass);
2469 while (*cmdline && isspace((unsigned char)*cmdline))
2474 if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
2476 sprintf(buf, "%.100s Error", thegame.name);
2477 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
2481 while (GetMessage(&msg, NULL, 0, 0)) {
2482 DispatchMessage(&msg);