2 * windows.c: Windows front end for my puzzle collection.
9 #endif /* NO_HTMLHELP */
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
49 #define IDM_KEYEMUL 0x0400
51 #define HELP_FILE_NAME "puzzles.hlp"
52 #define HELP_CNT_NAME "puzzles.cnt"
54 #define CHM_FILE_NAME "puzzles.chm"
55 #endif /* 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;
64 int help_has_contents;
67 #define FILENAME_MAX (260)
71 #define HGDI_ERROR ((HANDLE)GDI_ERROR)
75 #define CLASSNAME "Puzzles"
77 #define CLASSNAME thegame.name
83 * Wrapper implementations of functions not supplied by the
87 #define SHGetSubMenu(hWndMB,ID_MENU) (HMENU)SendMessage((hWndMB), SHCMBM_GETSUBMENU, (WPARAM)0, (LPARAM)ID_MENU)
91 int MessageBox(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType)
96 MultiByteToWideChar (CP_ACP, 0, lpText, -1, wText, 2048);
97 MultiByteToWideChar (CP_ACP, 0, lpCaption, -1, wCaption, 2048);
99 return MessageBoxW (hWnd, wText, wCaption, uType);
102 BOOL SetDlgItemTextA(HWND hDlg, int nIDDlgItem, LPCSTR lpString)
106 MultiByteToWideChar (CP_ACP, 0, lpString, -1, wText, 256);
107 return SetDlgItemTextW(hDlg, nIDDlgItem, wText);
110 LPCSTR getenv(LPCSTR buf)
115 BOOL GetKeyboardState(PBYTE pb)
120 static TCHAR wClassName[256], wGameName[256];
125 static FILE *debug_fp = NULL;
126 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
127 static int debug_got_console = 0;
129 void dputs(char *buf)
133 if (!debug_got_console) {
134 if (AllocConsole()) {
135 debug_got_console = 1;
136 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
140 debug_fp = fopen("debug.log", "w");
143 if (debug_hdl != INVALID_HANDLE_VALUE) {
144 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
147 fputs(buf, debug_fp);
150 OutputDebugString(buf);
153 void debug_printf(char *fmt, ...)
159 _vsnprintf(buf, 4095, fmt, ap);
166 #define WINFLAGS (WS_OVERLAPPEDWINDOW &~ \
167 (WS_MAXIMIZEBOX | WS_OVERLAPPED))
169 #define WINFLAGS (WS_CAPTION | WS_SYSMENU)
172 static void new_game_size(frontend *fe, float scale);
190 enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
195 HWND hwnd, statusbar, cfgbox;
197 HWND numpad; /* window handle for the numeric pad */
200 HBITMAP bitmap, prevbm;
201 RECT bitmapPosition; /* game bitmap position within game window */
207 HMENU gamemenu, typemenu;
209 DWORD timer_last_tickcount;
211 game_params **presets;
213 int nfonts, fontsize;
215 struct cfg_aux *cfgaux;
216 int cfg_which, dlg_done;
221 enum { DRAWING, PRINTING, NOTHING } drawstatus;
223 int printcount, printw, printh, printsolns, printcurr, printcolour;
225 int printoffsetx, printoffsety;
226 float printpixelscale;
228 int linewidth, linedotted;
234 void frontend_free(frontend *fe)
247 static void update_type_menu_tick(frontend *fe);
248 static void update_copy_menu_greying(frontend *fe);
250 void fatal(char *fmt, ...)
256 vsprintf(buf, fmt, ap);
259 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
264 char *geterrstr(void)
267 DWORD dw = GetLastError();
271 FORMAT_MESSAGE_ALLOCATE_BUFFER |
272 FORMAT_MESSAGE_FROM_SYSTEM,
275 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
279 ret = dupstr(lpMsgBuf);
286 void get_random_seed(void **randseed, int *randseedsize)
288 SYSTEMTIME *st = snew(SYSTEMTIME);
292 *randseed = (void *)st;
293 *randseedsize = sizeof(SYSTEMTIME);
296 static void win_status_bar(void *handle, char *text)
301 frontend *fe = (frontend *)handle;
304 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 255);
305 SendMessage(fe->statusbar, SB_SETTEXT,
306 (WPARAM) 255 | SBT_NOBORDERS,
309 SetWindowText(fe->statusbar, text);
313 static blitter *win_blitter_new(void *handle, int w, int h)
315 blitter *bl = snew(blitter);
317 memset(bl, 0, sizeof(blitter));
325 static void win_blitter_free(void *handle, blitter *bl)
327 if (bl->bitmap) DeleteObject(bl->bitmap);
331 static void blitter_mkbitmap(frontend *fe, blitter *bl)
333 HDC hdc = GetDC(fe->hwnd);
334 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
335 ReleaseDC(fe->hwnd, hdc);
338 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
340 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
342 frontend *fe = (frontend *)handle;
343 HDC hdc_win, hdc_blit;
346 assert(fe->drawstatus == DRAWING);
348 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
350 bl->x = x; bl->y = y;
352 hdc_win = GetDC(fe->hwnd);
353 hdc_blit = CreateCompatibleDC(hdc_win);
354 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
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());
360 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
361 fe->hdc, x, y, SRCCOPY))
362 fatal("BitBlt failed: 0x%x", GetLastError());
364 SelectObject(hdc_blit, prev_blit);
366 ReleaseDC(fe->hwnd, hdc_win);
369 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
371 frontend *fe = (frontend *)handle;
372 HDC hdc_win, hdc_blit;
375 assert(fe->drawstatus == DRAWING);
377 assert(bl->bitmap); /* we should always have saved before loading */
379 if (x == BLITTER_FROMSAVED) x = bl->x;
380 if (y == BLITTER_FROMSAVED) y = bl->y;
382 hdc_win = GetDC(fe->hwnd);
383 hdc_blit = CreateCompatibleDC(hdc_win);
385 prev_blit = SelectObject(hdc_blit, bl->bitmap);
387 BitBlt(fe->hdc, x, y, bl->w, bl->h,
388 hdc_blit, 0, 0, SRCCOPY);
390 SelectObject(hdc_blit, prev_blit);
392 ReleaseDC(fe->hwnd, hdc_win);
395 void frontend_default_colour(frontend *fe, float *output)
397 DWORD c = GetSysColor(COLOR_MENU); /* ick */
399 output[0] = (float)(GetRValue(c) / 255.0);
400 output[1] = (float)(GetGValue(c) / 255.0);
401 output[2] = (float)(GetBValue(c) / 255.0);
404 static POINT win_transform_point(frontend *fe, int x, int y)
408 assert(fe->drawstatus != NOTHING);
410 if (fe->drawstatus == PRINTING) {
411 ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
412 ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
421 static void win_text_colour(frontend *fe, int colour)
423 assert(fe->drawstatus != NOTHING);
425 if (fe->drawstatus == PRINTING) {
428 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
431 * Displaying text in hatched colours is not permitted.
435 SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
437 SetTextColor(fe->hdc, fe->colours[colour]);
441 static void win_set_brush(frontend *fe, int colour)
444 assert(fe->drawstatus != NOTHING);
446 if (fe->drawstatus == PRINTING) {
449 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
452 br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
456 * This is only ever required during printing, and the
457 * PocketPC port doesn't support printing.
459 fatal("CreateHatchBrush not supported");
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,
471 br = fe->brushes[colour];
473 fe->oldbr = SelectObject(fe->hdc, br);
476 static void win_reset_brush(frontend *fe)
480 assert(fe->drawstatus != NOTHING);
482 br = SelectObject(fe->hdc, fe->oldbr);
483 if (fe->drawstatus == PRINTING)
487 static void win_set_pen(frontend *fe, int colour, int thin)
490 assert(fe->drawstatus != NOTHING);
492 if (fe->drawstatus == PRINTING) {
495 int width = thin ? 0 : fe->linewidth;
500 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
502 * Stroking in hatched colours is not permitted.
505 pen = CreatePen(fe->linedotted ? PS_DOT : PS_SOLID,
506 width, RGB(r * 255, g * 255, b * 255));
508 pen = fe->pens[colour];
510 fe->oldpen = SelectObject(fe->hdc, pen);
513 static void win_reset_pen(frontend *fe)
517 assert(fe->drawstatus != NOTHING);
519 pen = SelectObject(fe->hdc, fe->oldpen);
520 if (fe->drawstatus == PRINTING)
524 static void win_clip(void *handle, int x, int y, int w, int h)
526 frontend *fe = (frontend *)handle;
529 if (fe->drawstatus == NOTHING)
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);
537 static void win_unclip(void *handle)
539 frontend *fe = (frontend *)handle;
541 if (fe->drawstatus == NOTHING)
544 SelectClipRgn(fe->hdc, NULL);
547 static void win_draw_text(void *handle, int x, int y, int fonttype,
548 int fontsize, int align, int colour, char *text)
550 frontend *fe = (frontend *)handle;
555 if (fe->drawstatus == NOTHING)
558 if (fe->drawstatus == PRINTING)
559 fontsize = (int)(fontsize * fe->printpixelscale);
561 xy = win_transform_point(fe, x, y);
564 * Find or create the font.
566 for (i = fe->fontstart; i < fe->nfonts; i++)
567 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
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);
578 fe->fonts[i].type = fonttype;
579 fe->fonts[i].size = fontsize;
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);
592 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
595 fe->fonts[i].font = CreateFontIndirect(&lf);
599 * Position and draw the text.
606 MultiByteToWideChar (CP_UTF8, 0, text, -1, wText, 256);
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;
615 if (GetTextExtentPoint32W(fe->hdc, wText, wcslen(wText), &size))
617 if (align & ALIGN_HCENTRE)
619 else if (align & ALIGN_HRIGHT)
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);
629 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
631 frontend *fe = (frontend *)handle;
634 if (fe->drawstatus == NOTHING)
637 if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
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.
644 SetPixel(fe->hdc, x, y, fe->colours[colour]);
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);
656 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
658 frontend *fe = (frontend *)handle;
661 if (fe->drawstatus == NOTHING)
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]);
673 static void win_draw_circle(void *handle, int cx, int cy, int radius,
674 int fillcolour, int outlinecolour)
676 frontend *fe = (frontend *)handle;
679 assert(outlinecolour >= 0);
681 if (fe->drawstatus == NOTHING)
685 win_set_brush(fe, fillcolour);
687 fe->oldbr = SelectObject(fe->hdc, GetStockObject(NULL_BRUSH));
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);
697 static void win_draw_polygon(void *handle, int *coords, int npoints,
698 int fillcolour, int outlinecolour)
700 frontend *fe = (frontend *)handle;
704 if (fe->drawstatus == NOTHING)
707 pts = snewn(npoints+1, POINT);
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]);
714 assert(outlinecolour >= 0);
716 if (fillcolour >= 0) {
717 win_set_brush(fe, fillcolour);
718 win_set_pen(fe, outlinecolour, FALSE);
719 Polygon(fe->hdc, pts, npoints);
723 win_set_pen(fe, outlinecolour, FALSE);
724 Polyline(fe->hdc, pts, npoints+1);
731 static void win_start_draw(void *handle)
733 frontend *fe = (frontend *)handle;
736 assert(fe->drawstatus == NOTHING);
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);
744 SetMapMode(fe->hdc, MM_TEXT);
746 fe->drawstatus = DRAWING;
749 static void win_draw_update(void *handle, int x, int y, int w, int h)
751 frontend *fe = (frontend *)handle;
754 if (fe->drawstatus != DRAWING)
762 OffsetRect(&r, fe->bitmapPosition.left, fe->bitmapPosition.top);
763 InvalidateRect(fe->hwnd, &r, FALSE);
766 static void win_end_draw(void *handle)
768 frontend *fe = (frontend *)handle;
769 assert(fe->drawstatus == DRAWING);
770 SelectObject(fe->hdc, fe->prevbm);
773 DeleteObject(fe->clip);
776 fe->drawstatus = NOTHING;
779 static void win_line_width(void *handle, float width)
781 frontend *fe = (frontend *)handle;
783 assert(fe->drawstatus != DRAWING);
784 if (fe->drawstatus == NOTHING)
787 fe->linewidth = (int)(width * fe->printpixelscale);
790 static void win_line_dotted(void *handle, int dotted)
792 frontend *fe = (frontend *)handle;
794 assert(fe->drawstatus != DRAWING);
795 if (fe->drawstatus == NOTHING)
798 fe->linedotted = dotted;
801 static void win_begin_doc(void *handle, int pages)
803 frontend *fe = (frontend *)handle;
805 assert(fe->drawstatus != DRAWING);
806 if (fe->drawstatus == NOTHING)
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);
814 fe->drawstatus = NOTHING;
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.)
823 fe->fontstart = fe->nfonts;
826 static void win_begin_page(void *handle, int number)
828 frontend *fe = (frontend *)handle;
830 assert(fe->drawstatus != DRAWING);
831 if (fe->drawstatus == NOTHING)
834 if (StartPage(fe->hdc) <= 0) {
835 char *e = geterrstr();
836 MessageBox(fe->hwnd, e, "Error starting a page",
837 MB_ICONERROR | MB_OK);
839 fe->drawstatus = NOTHING;
843 static void win_begin_puzzle(void *handle, float xm, float xc,
844 float ym, float yc, int pw, int ph, float wmm)
846 frontend *fe = (frontend *)handle;
847 int ppw, pph, pox, poy;
848 float mmpw, mmph, mmox, mmoy;
851 assert(fe->drawstatus != DRAWING);
852 if (fe->drawstatus == NOTHING)
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);
861 * Compute the puzzle's position on the logical page.
863 mmox = xm * mmpw + xc;
864 mmoy = ym * mmph + yc;
867 * Work out what that comes to in pixels.
869 pox = (int)(mmox * (float)ppw / mmpw);
870 poy = (int)(mmoy * (float)pph / mmph);
873 * And determine the scale.
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 /
880 scale = (wmm * ppw) / (mmpw * pw);
883 * Now store pox, poy and scale for use in the main drawing
886 fe->printoffsetx = pox;
887 fe->printoffsety = poy;
888 fe->printpixelscale = scale;
891 fe->linedotted = FALSE;
894 static void win_end_puzzle(void *handle)
896 /* Nothing needs to be done here. */
899 static void win_end_page(void *handle, int number)
901 frontend *fe = (frontend *)handle;
903 assert(fe->drawstatus != DRAWING);
905 if (fe->drawstatus == NOTHING)
908 if (EndPage(fe->hdc) <= 0) {
909 char *e = geterrstr();
910 MessageBox(fe->hwnd, e, "Error finishing a page",
911 MB_ICONERROR | MB_OK);
913 fe->drawstatus = NOTHING;
917 static void win_end_doc(void *handle)
919 frontend *fe = (frontend *)handle;
921 assert(fe->drawstatus != DRAWING);
924 * Free all the fonts created since we began printing.
926 while (fe->nfonts > fe->fontstart) {
928 DeleteObject(fe->fonts[fe->nfonts].font);
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.
938 if (fe->drawstatus == NOTHING)
941 if (EndDoc(fe->hdc) <= 0) {
942 char *e = geterrstr();
943 MessageBox(fe->hwnd, e, "Error finishing printing",
944 MB_ICONERROR | MB_OK);
946 fe->drawstatus = NOTHING;
950 char *win_text_fallback(void *handle, const char *const *strings, int nstrings)
953 * We assume Windows can cope with any UTF-8 likely to be
954 * emitted by a puzzle.
956 return dupstr(strings[0]);
959 const struct drawing_api win_drawing = {
986 void print(frontend *fe)
992 midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
997 * Create our document structure and fill it up with puzzles.
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);
1005 game_params *params;
1007 nme = midend_new(NULL, fe->game, NULL, NULL);
1010 * Set the non-interactive mid-end to have the same
1011 * parameters as the standard one.
1013 params = midend_get_params(fe->me);
1014 midend_set_params(nme, params);
1015 fe->game->free_params(params);
1018 midend_new_game(nme);
1019 err = midend_print_puzzle(nme, doc, fe->printsolns);
1028 MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
1029 MB_ICONERROR | MB_OK);
1034 memset(&pd, 0, sizeof(pd));
1035 pd.lStructSize = sizeof(pd);
1036 pd.hwndOwner = fe->hwnd;
1038 pd.hDevNames = NULL;
1039 pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
1040 PD_NOPAGENUMS | PD_NOSELECTION;
1042 pd.nFromPage = pd.nToPage = 0xFFFF;
1043 pd.nMinPage = pd.nMaxPage = 1;
1045 if (!PrintDlg(&pd)) {
1051 * Now pd.hDC is a device context for the printer.
1055 * FIXME: IWBNI we put up an Abort box here.
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;
1067 fe->drawstatus = PRINTING;
1070 fe->dr = drawing_new(&win_drawing, NULL, fe);
1071 document_print(doc, fe->dr);
1072 drawing_free(fe->dr);
1075 fe->drawstatus = NOTHING;
1082 void deactivate_timer(frontend *fe)
1085 return; /* for non-interactive midend */
1086 if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
1090 void activate_timer(frontend *fe)
1093 return; /* for non-interactive midend */
1095 fe->timer = SetTimer(fe->hwnd, 1, 20, NULL);
1096 fe->timer_last_tickcount = GetTickCount();
1100 void write_clip(HWND hwnd, char *data)
1108 * Windows expects CRLF in the clipboard, so we must convert
1109 * any \n that has come out of the puzzle backend.
1112 for (i = 0; data[i]; i++) {
1113 if (data[i] == '\n')
1117 data2 = snewn(len+1, char);
1119 for (i = 0; data[i]; i++) {
1120 if (data[i] == '\n')
1122 data2[j++] = data[i];
1127 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
1132 lock = GlobalLock(clipdata);
1134 GlobalFree(clipdata);
1138 memcpy(lock, data2, len);
1139 ((unsigned char *) lock)[len] = 0;
1140 GlobalUnlock(clipdata);
1142 if (OpenClipboard(hwnd)) {
1144 SetClipboardData(CF_TEXT, clipdata);
1147 GlobalFree(clipdata);
1153 * Set up Help and see if we can find a help file.
1155 static void init_help(void)
1158 char b[2048], *p, *q, *r;
1162 * Find the executable file path, so we can look alongside
1163 * it for help files. Trim the filename off the end.
1165 GetModuleFileName(NULL, b, sizeof(b) - 1);
1167 p = strrchr(b, '\\');
1168 if (p && p >= r) r = p+1;
1169 q = strrchr(b, ':');
1170 if (q && q >= r) r = q+1;
1174 * Try HTML Help first.
1176 strcpy(r, CHM_FILE_NAME);
1177 if ( (fp = fopen(b, "r")) != NULL) {
1181 * We have a .CHM. See if we can use it.
1183 hh_dll = LoadLibrary("hhctrl.ocx");
1185 htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
1187 FreeLibrary(hh_dll);
1190 help_path = dupstr(b);
1195 #endif /* NO_HTMLHELP */
1198 * Now try old-style .HLP.
1200 strcpy(r, HELP_FILE_NAME);
1201 if ( (fp = fopen(b, "r")) != NULL) {
1204 help_path = dupstr(b);
1208 * See if there's a .CNT file alongside it.
1210 strcpy(r, HELP_CNT_NAME);
1211 if ( (fp = fopen(b, "r")) != NULL) {
1213 help_has_contents = TRUE;
1215 help_has_contents = FALSE;
1220 help_type = NONE; /* didn't find any */
1229 static void start_help(frontend *fe, const char *topic)
1234 switch (help_type) {
1238 str = snewn(10+strlen(topic), char);
1239 sprintf(str, "JI(`',`%s')", topic);
1241 } else if (help_has_contents) {
1244 cmd = HELP_CONTENTS;
1246 WinHelp(fe->hwnd, help_path, cmd, (DWORD)str);
1247 fe->help_running = TRUE;
1254 str = snewn(20 + strlen(topic) + strlen(help_path), char);
1255 sprintf(str, "%s::/%s.html>main", help_path, topic);
1257 str = dupstr(help_path);
1259 htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
1260 fe->help_running = TRUE;
1262 #endif /* NO_HTMLHELP */
1264 assert(!"This shouldn't happen");
1272 * Stop Help on window cleanup.
1274 static void stop_help(frontend *fe)
1276 if (fe->help_running) {
1277 switch (help_type) {
1279 WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
1284 htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
1286 #endif /* NO_HTMLHELP */
1288 assert(!"This shouldn't happen");
1291 fe->help_running = FALSE;
1298 * Terminate Help on process exit.
1300 static void cleanup_help(void)
1302 /* Nothing to do currently.
1303 * (If we were running HTML Help single-threaded, this is where we'd
1304 * call HH_UNINITIALIZE.) */
1307 static int get_statusbar_height(frontend *fe)
1310 if (fe->statusbar) {
1312 GetWindowRect(fe->statusbar, &sr);
1313 sy = sr.bottom - sr.top;
1320 static void adjust_statusbar(frontend *fe, RECT *r)
1324 if (!fe->statusbar) return;
1326 sy = get_statusbar_height(fe);
1328 SetWindowPos(fe->statusbar, NULL, 0, r->bottom-r->top-sy, r->right-r->left,
1333 static void get_menu_size(HWND wh, RECT *r)
1335 HMENU bar = GetMenu(wh);
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);
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).
1352 static int check_window_resize(frontend *fe, int cx, int cy,
1357 int x, y, sy = get_statusbar_height(fe), changed = 0;
1359 /* disallow making window thinner than menu bar */
1360 x = max(cx, fe->xmin);
1361 y = max(cy - sy, fe->ymin);
1364 * See if we actually got the window size we wanted, and adjust
1365 * the puzzle size if not.
1367 midend_size(fe->me, &x, &y, TRUE);
1368 if (x != cx || y != cy) {
1370 * Resize the window, now we know what size we _really_
1376 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1377 *wx = r.right - r.left;
1378 *wy = r.bottom - r.top;
1386 (float)midend_tilesize(fe->me) / (float)fe->game->preferred_tilesize;
1392 * Given the current window size, make sure it's sane for the
1393 * current puzzle and resize if necessary.
1396 static void check_window_size(frontend *fe, int *px, int *py)
1401 GetClientRect(fe->hwnd, &r);
1402 cx = r.right - r.left;
1403 cy = r.bottom - r.top;
1405 if (check_window_resize(fe, cx, cy, px, py, &wx, &wy)) {
1407 SetWindowPos(fe->hwnd, NULL, 0, 0, wx, wy,
1408 SWP_NOMOVE | SWP_NOZORDER);
1413 GetClientRect(fe->hwnd, &r);
1414 adjust_statusbar(fe, &r);
1417 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1421 if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1422 *x = sr.right - sr.left;
1423 *y = sr.bottom - sr.top;
1428 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1429 *x -= r.right - r.left - 100;
1430 *y -= r.bottom - r.top - 100;
1435 if (fe->statusbar != NULL) {
1436 GetWindowRect(fe->statusbar, &sr);
1437 *y -= sr.bottom - sr.top;
1442 /* Toolbar buttons on the numeric pad */
1443 static TBBUTTON tbNumpadButtons[] =
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}
1459 * Allocate a new frontend structure and create its main window.
1461 static frontend *frontend_new(HINSTANCE inst)
1464 const char *nogame = "Puzzles (no game selected)";
1466 fe = snew(frontend);
1476 fe->help_running = FALSE;
1478 fe->drawstatus = NOTHING;
1483 fe->nfonts = fe->fontsize = 0;
1489 fe->puzz_scale = 1.0;
1492 MultiByteToWideChar (CP_ACP, 0, nogame, -1, wGameName, 256);
1493 fe->hwnd = CreateWindowEx(0, wClassName, wGameName,
1495 CW_USEDEFAULT, CW_USEDEFAULT,
1496 CW_USEDEFAULT, CW_USEDEFAULT,
1497 NULL, NULL, inst, NULL);
1501 RECT rc, rcBar, rcTB, rcClient;
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;
1509 SHCreateMenuBar(&mbi);
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);
1519 fe->hwnd = CreateWindowEx(0, CLASSNAME, nogame,
1520 WS_OVERLAPPEDWINDOW &~
1522 CW_USEDEFAULT, CW_USEDEFAULT,
1523 CW_USEDEFAULT, CW_USEDEFAULT,
1524 NULL, NULL, inst, NULL);
1526 DWORD lerr = GetLastError();
1527 printf("no window: 0x%x\n", lerr);
1531 fe->gamemenu = NULL;
1534 fe->statusbar = NULL;
1537 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1543 * Populate a frontend structure with a (new) game and midend structure, and
1544 * create any window furniture that it needs.
1546 * Previously-allocated memory and window furniture will be freed by this function.
1548 static int new_game(frontend *fe, const game *game, char *game_id, char **error)
1555 if (fe->me) midend_free(fe->me);
1556 fe->me = midend_new(fe, fe->game, &win_drawing, fe);
1559 *error = midend_game_id(fe->me, game_id);
1561 midend_free(fe->me);
1567 midend_new_game(fe->me);
1573 colours = midend_colours(fe->me, &ncolours);
1575 if (fe->colours) sfree(fe->colours);
1576 if (fe->brushes) sfree(fe->brushes);
1577 if (fe->pens) sfree(fe->pens);
1579 fe->colours = snewn(ncolours, COLORREF);
1580 fe->brushes = snewn(ncolours, HBRUSH);
1581 fe->pens = snewn(ncolours, HPEN);
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]);
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);
1601 fe->statusbar = NULL;
1603 get_max_puzzle_size(fe, &x, &y);
1604 midend_size(fe->me, &x, &y, FALSE);
1609 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1613 DestroyWindow(fe->numpad);
1614 if (fe->game->flags & REQUIRE_NUMPAD)
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,
1625 rcClient.bottom - (rcTB.bottom - rcTB.top) - 1,
1627 rcTB.bottom - rcTB.top,
1629 SendMessage(fe->numpad, TB_SETINDENT, (rcClient.right - (10 * 21)) / 2, 0);
1634 MultiByteToWideChar (CP_ACP, 0, fe->game->name, -1, wGameName, 256);
1635 SetWindowText(fe->hwnd, wGameName);
1637 SetWindowText(fe->hwnd, fe->game->name);
1641 DestroyWindow(fe->statusbar);
1642 if (midend_wants_statusbar(fe->me)) {
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);
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,
1657 * Now resize the window to take account of the status bar.
1659 GetWindowRect(fe->statusbar, &sr);
1660 GetWindowRect(fe->hwnd, &r);
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);
1667 fe->statusbar = NULL;
1671 HMENU oldmenu = GetMenu(fe->hwnd);
1674 HMENU bar = CreateMenu();
1675 HMENU menu = CreateMenu();
1678 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "&Game");
1680 HMENU menu = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_GAME);
1681 DeleteMenu(menu, 0, MF_BYPOSITION);
1683 fe->gamemenu = menu;
1684 AppendMenu(menu, MF_ENABLED, IDM_NEW, TEXT("&New"));
1685 AppendMenu(menu, MF_ENABLED, IDM_RESTART, TEXT("&Restart"));
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..."));
1694 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1695 fe->game->can_configure) {
1698 HMENU sub = CreateMenu();
1700 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "&Type");
1702 HMENU sub = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_TYPE);
1703 DeleteMenu(sub, 0, MF_BYPOSITION);
1705 fe->presets = snewn(fe->npresets, game_params *);
1707 for (i = 0; i < fe->npresets; i++) {
1713 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1716 * FIXME: we ought to go through and do something
1717 * with ampersands here.
1721 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1723 MultiByteToWideChar (CP_ACP, 0, name, -1, wName, 255);
1724 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, wName);
1727 if (fe->game->can_configure) {
1728 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, TEXT("&Custom..."));
1733 fe->typemenu = INVALID_HANDLE_VALUE;
1739 #error Windows CE does not support COMBINED build.
1742 HMENU games = CreateMenu();
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);
1757 AppendMenu(menu, MF_SEPARATOR, 0, 0);
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);
1767 AppendMenu(menu, MF_ENABLED, IDM_UNDO, TEXT("Undo"));
1768 AppendMenu(menu, MF_ENABLED, IDM_REDO, TEXT("Redo"));
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"));
1775 if (fe->game->can_solve) {
1776 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1777 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, TEXT("Sol&ve"));
1779 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1781 AppendMenu(menu, MF_ENABLED, IDM_QUIT, TEXT("E&xit"));
1782 menu = CreateMenu();
1783 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, TEXT("&Help"));
1785 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, TEXT("&About"));
1787 if (help_type != NONE) {
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);
1797 DestroyMenu(oldmenu);
1798 SetMenu(fe->hwnd, bar);
1799 get_menu_size(fe->hwnd, &menusize);
1800 fe->xmin = (menusize.right - menusize.left) + 25;
1804 if (fe->bitmap) DeleteObject(fe->bitmap);
1806 new_game_size(fe, fe->puzz_scale); /* initialises fe->bitmap */
1811 static void show_window(frontend *fe)
1813 ShowWindow(fe->hwnd, SW_SHOWNORMAL);
1814 SetForegroundWindow(fe->hwnd);
1816 update_type_menu_tick(fe);
1817 update_copy_menu_greying(fe);
1819 midend_redraw(fe->me);
1823 static HFONT dialog_title_font()
1825 static HFONT hf = NULL;
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"));
1836 return hf = CreateFontIndirect(&lf);
1839 static void make_dialog_full_screen(HWND hwnd)
1841 SHINITDLGINFO shidi;
1843 /* Make dialog full screen */
1844 shidi.dwMask = SHIDIM_FLAGS;
1845 shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIZEDLGFULLSCREEN |
1848 SHInitDialog(&shidi);
1852 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1853 WPARAM wParam, LPARAM lParam)
1855 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1863 make_dialog_full_screen(hwnd);
1865 sprintf(title, "About %.250s", fe->game->name);
1866 SetDlgItemTextA(hwnd, IDC_ABOUT_CAPTION, title);
1868 SendDlgItemMessage(hwnd, IDC_ABOUT_CAPTION, WM_SETFONT,
1869 (WPARAM) dialog_title_font(), 0);
1871 SetDlgItemTextA(hwnd, IDC_ABOUT_GAME, fe->game->name);
1872 SetDlgItemTextA(hwnd, IDC_ABOUT_VERSION, ver);
1878 if (LOWORD(wParam) == IDOK)
1899 * Wrappers on midend_{get,set}_config, which extend the CFG_*
1900 * enumeration to add CFG_PRINT.
1902 static config_item *frontend_get_config(frontend *fe, int which,
1905 if (which < CFG_FRONTEND_SPECIFIC) {
1906 return midend_get_config(fe->me, which, wintitle);
1907 } else if (which == CFG_PRINT) {
1911 *wintitle = snewn(40 + strlen(fe->game->name), char);
1912 sprintf(*wintitle, "%s print setup", fe->game->name);
1914 ret = snewn(8, config_item);
1918 ret[i].name = "Number of puzzles to print";
1919 ret[i].type = C_STRING;
1920 ret[i].sval = dupstr("1");
1924 ret[i].name = "Number of puzzles across the page";
1925 ret[i].type = C_STRING;
1926 ret[i].sval = dupstr("1");
1930 ret[i].name = "Number of puzzles down the page";
1931 ret[i].type = C_STRING;
1932 ret[i].sval = dupstr("1");
1936 ret[i].name = "Percentage of standard size";
1937 ret[i].type = C_STRING;
1938 ret[i].sval = dupstr("100.0");
1942 ret[i].name = "Include currently shown puzzle";
1943 ret[i].type = C_BOOLEAN;
1948 ret[i].name = "Print solutions";
1949 ret[i].type = C_BOOLEAN;
1951 ret[i].ival = FALSE;
1954 if (fe->game->can_print_in_colour) {
1955 ret[i].name = "Print in colour";
1956 ret[i].type = C_BOOLEAN;
1958 ret[i].ival = FALSE;
1963 ret[i].type = C_END;
1970 assert(!"We should never get here");
1975 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
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;
1993 assert(!"We should never get here");
1994 return "Internal error";
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)
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);
2013 MultiByteToWideChar (CP_ACP, 0, wtext, -1, wwtext, 256);
2015 return CreateWindowEx(exstyle, wclass, wwtext,
2016 wstyle | WS_CHILD | WS_VISIBLE,
2018 rc.right - rc.left, rc.bottom - rc.top,
2019 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2022 static void create_config_controls(frontend * fe)
2025 int col1l, col1r, col2l, col2r, y;
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) */
2035 * Count the controls so we can allocate cfgaux.
2037 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2039 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2042 y = 22; /* Leave some room for the dialog title */
2043 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2047 * Edit box with a label beside it.
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);
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));
2069 * Drop-down list with a label beside it.
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++));
2078 char c, *p, *q, *str;
2084 while (*q && *q != c) q++;
2085 str = snewn(q-p+1, char);
2086 strncpy(str, p, q-p);
2090 MultiByteToWideChar (CP_ACP, 0, str, -1, ws, 50);
2091 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)ws);
2099 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2109 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
2110 WPARAM wParam, LPARAM lParam)
2112 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2122 fe = (frontend *) lParam;
2123 SetWindowLong(hwnd, GWL_USERDATA, lParam);
2126 fe->cfg = frontend_get_config(fe, fe->cfg_which, &title);
2128 make_dialog_full_screen(hwnd);
2130 SetDlgItemTextA(hwnd, IDC_CONFIG_CAPTION, title);
2131 SendDlgItemMessage(hwnd, IDC_CONFIG_CAPTION, WM_SETFONT,
2132 (WPARAM) dialog_title_font(), 0);
2134 create_config_controls(fe);
2141 * OK and Cancel are special cases.
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);
2148 MessageBox(hwnd, err, "Validation error",
2149 MB_ICONERROR | MB_OK);
2168 * First find the control whose id this is.
2170 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2171 if (j->ctlid == LOWORD(wParam))
2174 if (i->type == C_END)
2175 return 0; /* not our problem */
2177 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
2180 TCHAR wBuffer[4096];
2181 GetDlgItemText(fe->cfgbox, j->ctlid, wBuffer, 4096);
2182 WideCharToMultiByte(CP_ACP, 0, wBuffer, -1, buffer, 4096, NULL, NULL);
2184 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
2186 buffer[lenof(buffer)-1] = '\0';
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);
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)
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));
2223 static void about(frontend *fe)
2226 DialogBox(fe->inst, MAKEINTRESOURCE(IDD_ABOUT), fe->hwnd, AboutDlgProc);
2236 int winwidth, winheight, y;
2237 int height, width, maxwid;
2238 const char *strings[16];
2243 sprintf(titlebuf, "About %.250s", fe->game->name);
2245 strings[nstrings++] = fe->game->name;
2246 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
2247 strings[nstrings++] = ver;
2249 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2250 wc.lpfnWndProc = DefDlgProc;
2252 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2253 wc.hInstance = fe->inst;
2255 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2256 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2257 wc.lpszMenuName = NULL;
2258 wc.lpszClassName = "GameAboutBox";
2261 hdc = GetDC(fe->hwnd);
2262 SetMapMode(hdc, MM_TEXT);
2264 fe->dlg_done = FALSE;
2266 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2268 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2269 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2274 oldfont = SelectObject(hdc, fe->cfgfont);
2275 if (GetTextMetrics(hdc, &tm)) {
2276 height = tm.tmAscent + tm.tmDescent;
2277 width = tm.tmAveCharWidth;
2279 height = width = 30;
2283 * Figure out the layout of the About box by measuring the
2284 * length of each piece of text.
2287 winheight = height/2;
2289 for (i = 0; i < nstrings; i++) {
2290 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
2291 lengths[i] = size.cx;
2293 lengths[i] = 0; /* *shrug* */
2294 if (maxwid < lengths[i])
2295 maxwid = lengths[i];
2296 winheight += height * 3 / 2 + (height / 2);
2299 winheight += height + height * 7 / 4; /* OK button */
2300 winwidth = maxwid + 4*width;
2302 SelectObject(hdc, oldfont);
2303 ReleaseDC(fe->hwnd, hdc);
2306 * Create the dialog, now that we know its size.
2313 r.bottom = winheight;
2315 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2316 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2317 WS_CAPTION | WS_SYSMENU*/) &~
2318 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2322 * Centre the dialog on its parent window.
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;
2332 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
2333 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2334 WS_CAPTION | WS_SYSMENU,
2336 r.right-r.left, r.bottom-r.top,
2337 fe->hwnd, NULL, fe->inst, NULL);
2340 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2342 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2343 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
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++);
2353 assert(y < winheight);
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,
2362 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
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);
2372 EnableWindow(fe->hwnd, TRUE);
2373 SetForegroundWindow(fe->hwnd);
2374 DestroyWindow(fe->cfgbox);
2375 DeleteObject(fe->cfgfont);
2379 static int get_config(frontend *fe, int which)
2382 fe->cfg_which = which;
2384 return DialogBoxParam(fe->inst,
2385 MAKEINTRESOURCE(IDD_CONFIG),
2386 fe->hwnd, ConfigDlgProc,
2400 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
2401 int height, width, maxlabel, maxcheckbox;
2403 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2404 wc.lpfnWndProc = DefDlgProc;
2406 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2407 wc.hInstance = fe->inst;
2409 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2410 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2411 wc.lpszMenuName = NULL;
2412 wc.lpszClassName = "GameConfigBox";
2415 hdc = GetDC(fe->hwnd);
2416 SetMapMode(hdc, MM_TEXT);
2418 fe->dlg_done = FALSE;
2420 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2422 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2423 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2428 oldfont = SelectObject(hdc, fe->cfgfont);
2429 if (GetTextMetrics(hdc, &tm)) {
2430 height = tm.tmAscent + tm.tmDescent;
2431 width = tm.tmAveCharWidth;
2433 height = width = 30;
2436 fe->cfg = frontend_get_config(fe, which, &title);
2437 fe->cfg_which = which;
2440 * Figure out the layout of the config box by measuring the
2441 * length of each piece of text.
2443 maxlabel = maxcheckbox = 0;
2444 winheight = height/2;
2446 for (i = fe->cfg; i->type != C_END; i++) {
2451 * Both these control types have a label filling only
2452 * the left-hand column of the box.
2454 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2457 winheight += height * 3 / 2 + (height / 2);
2462 * Checkboxes take up the whole of the box width.
2464 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2465 maxcheckbox < size.cx)
2466 maxcheckbox = size.cx;
2467 winheight += height + (height / 2);
2472 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
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;
2482 SelectObject(hdc, oldfont);
2483 ReleaseDC(fe->hwnd, hdc);
2486 * Create the dialog, now that we know its size.
2493 r.bottom = winheight;
2495 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2496 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2497 WS_CAPTION | WS_SYSMENU*/) &~
2498 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2502 * Centre the dialog on its parent window.
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;
2512 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
2513 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2514 WS_CAPTION | WS_SYSMENU,
2516 r.right-r.left, r.bottom-r.top,
2517 fe->hwnd, NULL, fe->inst, NULL);
2521 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2523 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2524 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
2527 * Count the controls so we can allocate cfgaux.
2529 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2531 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2535 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2539 * Edit box with a label beside it.
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);
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));
2563 * Drop-down list with a label beside it.
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++));
2572 char c, *p, *q, *str;
2574 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
2579 while (*q && *q != c) q++;
2580 str = snewn(q-p+1, char);
2581 strncpy(str, p, q-p);
2583 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
2590 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2596 assert(y < winheight);
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,
2604 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
2605 BS_PUSHBUTTON | WS_TABSTOP, 0, "Cancel", IDCANCEL);
2607 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
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);
2617 EnableWindow(fe->hwnd, TRUE);
2618 SetForegroundWindow(fe->hwnd);
2619 DestroyWindow(fe->cfgbox);
2620 DeleteObject(fe->cfgfont);
2625 return (fe->dlg_done == 2);
2630 static void calculate_bitmap_position(frontend *fe, int x, int y)
2632 /* Pocket PC - center the game in the full screen window */
2636 GetClientRect(fe->hwnd, &rcClient);
2637 fe->bitmapPosition.left = (rcClient.right - x) / 2;
2638 yMargin = rcClient.bottom - y;
2640 if (fe->numpad != NULL) {
2642 GetWindowRect(fe->numpad, &rcPad);
2643 yMargin -= rcPad.bottom - rcPad.top;
2646 if (fe->statusbar != NULL) {
2648 GetWindowRect(fe->statusbar, &rcStatus);
2649 yMargin -= rcStatus.bottom - rcStatus.top;
2652 fe->bitmapPosition.top = yMargin / 2;
2654 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2655 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2658 static void calculate_bitmap_position(frontend *fe, int x, int y)
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;
2668 static void new_bitmap(frontend *fe, int x, int y)
2672 if (fe->bitmap) DeleteObject(fe->bitmap);
2674 hdc = GetDC(fe->hwnd);
2675 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2676 calculate_bitmap_position(fe, x, y);
2677 ReleaseDC(fe->hwnd, hdc);
2680 static void new_game_size(frontend *fe, float scale)
2685 get_max_puzzle_size(fe, &x, &y);
2686 midend_size(fe->me, &x, &y, FALSE);
2689 x = (int)((float)x * fe->puzz_scale);
2690 y = (int)((float)y * fe->puzz_scale);
2691 midend_size(fe->me, &x, &y, TRUE);
2693 fe->ymin = (fe->xmin * y) / x;
2698 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2700 if (fe->statusbar != NULL) {
2701 GetWindowRect(fe->statusbar, &sr);
2703 sr.left = sr.right = sr.top = sr.bottom = 0;
2706 SetWindowPos(fe->hwnd, NULL, 0, 0,
2708 r.bottom - r.top + sr.bottom - sr.top,
2709 SWP_NOMOVE | SWP_NOZORDER);
2712 check_window_size(fe, &x, &y);
2715 if (fe->statusbar != NULL)
2716 SetWindowPos(fe->statusbar, NULL, 0, y, x,
2717 sr.bottom - sr.top, SWP_NOZORDER);
2720 new_bitmap(fe, x, y);
2723 InvalidateRect(fe->hwnd, NULL, TRUE);
2725 midend_redraw(fe->me);
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
2735 static void adjust_game_size(frontend *fe, RECT *proposed, int isedge,
2736 int *wx_r, int *wy_r)
2739 int nx, ny, xdiff, ydiff, wx, wy;
2741 /* Work out the current window sizing, and thus the
2742 * difference in size we're asking for. */
2743 GetClientRect(fe->hwnd, &cr);
2745 AdjustWindowRectEx(&wr, WINFLAGS, TRUE, 0);
2747 xdiff = (proposed->right - proposed->left) - (wr.right - wr.left);
2748 ydiff = (proposed->bottom - proposed->top) - (wr.bottom - wr.top);
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);
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);
2767 /* reset size to current window size */
2768 wx = wr.right - wr.left;
2769 wy = wr.bottom - wr.top;
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);
2776 *wx_r = wx; *wy_r = wy;
2779 static void update_type_menu_tick(frontend *fe)
2783 if (fe->typemenu == INVALID_HANDLE_VALUE)
2786 total = GetMenuItemCount(fe->typemenu);
2787 n = midend_which_preset(fe->me);
2789 n = total - 1; /* "Custom" item */
2791 for (i = 0; i < total; i++) {
2792 int flag = (i == n ? MF_CHECKED : MF_UNCHECKED);
2793 CheckMenuItem(fe->typemenu, i, MF_BYPOSITION | flag);
2796 DrawMenuBar(fe->hwnd);
2799 static void update_copy_menu_greying(frontend *fe)
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);
2806 static void new_game_type(frontend *fe)
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);
2814 static int is_alt_pressed(void)
2817 int r = GetKeyboardState(keystate);
2820 if (keystate[VK_MENU] & 0x80)
2822 if (keystate[VK_RMENU] & 0x80)
2827 static void savefile_write(void *wctx, void *buf, int len)
2829 FILE *fp = (FILE *)wctx;
2830 fwrite(buf, 1, len, fp);
2833 static int savefile_read(void *wctx, void *buf, int len)
2835 FILE *fp = (FILE *)wctx;
2838 ret = fread(buf, 1, len, fp);
2839 return (ret == len);
2842 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2843 WPARAM wParam, LPARAM lParam)
2845 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2850 DestroyWindow(hwnd);
2854 /* Numeric pad sends WM_COMMAND messages */
2855 if ((wParam >= IDM_KEYEMUL) && (wParam < IDM_KEYEMUL + 256))
2857 midend_process_key(fe->me, 0, 0, wParam - IDM_KEYEMUL);
2860 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
2863 if (!midend_process_key(fe->me, 0, 0, 'n'))
2867 midend_restart_game(fe->me);
2870 if (!midend_process_key(fe->me, 0, 0, 'u'))
2874 if (!midend_process_key(fe->me, 0, 0, '\x12'))
2879 char *text = midend_text_format(fe->me);
2881 write_clip(hwnd, text);
2883 MessageBeep(MB_ICONWARNING);
2889 char *msg = midend_solve(fe->me);
2891 MessageBox(hwnd, msg, "Unable to solve",
2892 MB_ICONERROR | MB_OK);
2896 if (!midend_process_key(fe->me, 0, 0, 'q'))
2900 if (get_config(fe, CFG_SETTINGS))
2904 if (get_config(fe, CFG_SEED))
2908 if (get_config(fe, CFG_DESC))
2912 if (get_config(fe, CFG_PRINT))
2922 char filename[FILENAME_MAX];
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;
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");
2938 #ifdef OPENFILENAME_SIZE_VERSION_400
2939 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2941 of.lStructSize = sizeof(of);
2943 of.lpstrInitialDir = NULL;
2945 if (cmd == IDM_SAVE)
2946 ret = GetSaveFileName(&of);
2948 ret = GetOpenFileName(&of);
2951 if (cmd == IDM_SAVE) {
2954 if ((fp = fopen(filename, "r")) != NULL) {
2955 char buf[256 + FILENAME_MAX];
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)
2968 fp = fopen(filename, "w");
2971 MessageBox(hwnd, "Unable to open save file",
2972 "Error", MB_ICONERROR | MB_OK);
2976 midend_serialise(fe->me, savefile_write, fp);
2980 FILE *fp = fopen(filename, "r");
2984 MessageBox(hwnd, "Unable to open saved game file",
2985 "Error", MB_ICONERROR | MB_OK);
2989 err = midend_deserialise(fe->me, savefile_read, fp);
2994 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
2998 new_game_size(fe, 1.0);
3006 start_help(fe, NULL);
3009 assert(help_type != NONE);
3010 start_help(fe, help_type == CHM ?
3011 fe->game->htmlhelp_topic : fe->game->winhelp_topic);
3016 if (wParam >= IDM_GAMES && wParam < (IDM_GAMES + (WPARAM)gamecount)) {
3017 int p = wParam - IDM_GAMES;
3020 new_game(fe, gamelist[p], NULL, &error);
3024 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
3026 if (p >= 0 && p < fe->npresets) {
3027 midend_set_params(fe->me, fe->presets[p]);
3048 hdc = BeginPaint(hwnd, &p);
3049 hdc2 = CreateCompatibleDC(hdc);
3050 prevbm = SelectObject(hdc2, fe->bitmap);
3052 FillRect(hdc, &(p.rcPaint), (HBRUSH) GetStockObject(WHITE_BRUSH));
3054 IntersectRect(&rcDest, &(fe->bitmapPosition), &(p.rcPaint));
3056 rcDest.left, rcDest.top,
3057 rcDest.right - rcDest.left,
3058 rcDest.bottom - rcDest.top,
3060 rcDest.left - fe->bitmapPosition.left,
3061 rcDest.top - fe->bitmapPosition.top,
3063 SelectObject(hdc2, prevbm);
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;
3078 if (!(lParam & 0x01000000))
3079 key = MOD_NUM_KEYPAD | '4';
3081 key = shift | ctrl | CURSOR_LEFT;
3084 if (!(lParam & 0x01000000))
3085 key = MOD_NUM_KEYPAD | '6';
3087 key = shift | ctrl | CURSOR_RIGHT;
3090 if (!(lParam & 0x01000000))
3091 key = MOD_NUM_KEYPAD | '8';
3093 key = shift | ctrl | CURSOR_UP;
3096 if (!(lParam & 0x01000000))
3097 key = MOD_NUM_KEYPAD | '2';
3099 key = shift | ctrl | CURSOR_DOWN;
3102 * Diagonal keys on the numeric keypad.
3105 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
3108 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
3111 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
3114 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
3117 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
3120 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
3123 * Numeric keypad keys with Num Lock on.
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;
3138 if (!midend_process_key(fe->me, 0, 0, key))
3143 m.message = WM_KEYDOWN;
3145 m.lParam = lParam & 0xdfff;
3146 TranslateMessage(&m);
3150 case WM_LBUTTONDOWN:
3151 case WM_RBUTTONDOWN:
3152 case WM_MBUTTONDOWN:
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.
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;
3167 button = LEFT_BUTTON;
3169 if ((fe->game->flags & REQUIRE_RBUTTON) == 0)
3170 button = LEFT_BUTTON;
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;
3181 if (GN_CONTEXTMENU == SHRecognizeGesture(&shrgi))
3182 button = RIGHT_BUTTON;
3184 button = LEFT_BUTTON;
3188 if (!midend_process_key(fe->me,
3189 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3190 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
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.
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;
3213 button = LEFT_RELEASE;
3215 if (!midend_process_key(fe->me,
3216 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3217 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3228 if (wParam & (MK_MBUTTON | MK_SHIFT))
3229 button = MIDDLE_DRAG;
3230 else if (wParam & MK_RBUTTON || is_alt_pressed())
3231 button = RIGHT_DRAG;
3235 if (!midend_process_key(fe->me,
3236 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3237 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3243 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
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;
3257 RECT *sr = (RECT *)lParam;
3258 int wx, wy, isedge = 0;
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);
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;
3273 sr->bottom = sr->top + wy;
3275 if (wParam == WMSZ_LEFT ||
3276 wParam == WMSZ_TOPLEFT ||
3277 wParam == WMSZ_BOTTOMLEFT) {
3278 sr->left = sr->right - wx;
3280 sr->right = sr->left + wx;
3288 return DefWindowProc(hwnd, message, wParam, lParam);
3292 static int FindPreviousInstance()
3294 /* Check if application is running. If it's running then focus on the window */
3295 HWND hOtherWnd = NULL;
3297 hOtherWnd = FindWindow (wGameName, wGameName);
3300 SetForegroundWindow (hOtherWnd);
3308 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
3316 MultiByteToWideChar (CP_ACP, 0, CLASSNAME, -1, wClassName, 256);
3317 if (FindPreviousInstance ())
3321 InitCommonControls();
3327 wndclass.lpfnWndProc = WndProc;
3328 wndclass.cbClsExtra = 0;
3329 wndclass.cbWndExtra = 0;
3330 wndclass.hInstance = inst;
3331 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
3333 if (!wndclass.hIcon) /* in case resource file is absent */
3334 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
3336 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
3337 wndclass.hbrBackground = NULL;
3338 wndclass.lpszMenuName = NULL;
3340 wndclass.lpszClassName = wClassName;
3342 wndclass.lpszClassName = CLASSNAME;
3345 RegisterClass(&wndclass);
3348 while (*cmdline && isspace((unsigned char)*cmdline))
3357 for (i = 0; i < gamecount; i++) {
3358 const char *p = gamelist[i]->name;
3360 while (*q && isspace((unsigned char)*q))
3363 if (isspace((unsigned char)*p)) {
3364 while (*q && isspace((unsigned char)*q))
3367 if (tolower((unsigned char)*p) !=
3368 tolower((unsigned char)*q))
3378 while (*cmdline && isspace((unsigned char)*cmdline))
3388 fe = frontend_new(inst);
3389 if (new_game(fe, gg, *cmdline ? cmdline : NULL, &error)) {
3391 sprintf(buf, "%.100s Error", gg->name);
3392 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
3397 while (GetMessage(&msg, NULL, 0, 0)) {
3398 DispatchMessage(&msg);
3401 DestroyWindow(fe->hwnd);
3406 /* vim: set shiftwidth=4 tabstop=8: */