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)
246 static void update_type_menu_tick(frontend *fe);
247 static void update_copy_menu_greying(frontend *fe);
249 void fatal(char *fmt, ...)
255 vsprintf(buf, fmt, ap);
258 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
263 char *geterrstr(void)
266 DWORD dw = GetLastError();
270 FORMAT_MESSAGE_ALLOCATE_BUFFER |
271 FORMAT_MESSAGE_FROM_SYSTEM,
274 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
278 ret = dupstr(lpMsgBuf);
285 void get_random_seed(void **randseed, int *randseedsize)
287 SYSTEMTIME *st = snew(SYSTEMTIME);
291 *randseed = (void *)st;
292 *randseedsize = sizeof(SYSTEMTIME);
295 static void win_status_bar(void *handle, char *text)
300 frontend *fe = (frontend *)handle;
303 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 255);
304 SendMessage(fe->statusbar, SB_SETTEXT,
305 (WPARAM) 255 | SBT_NOBORDERS,
308 SetWindowText(fe->statusbar, text);
312 static blitter *win_blitter_new(void *handle, int w, int h)
314 blitter *bl = snew(blitter);
316 memset(bl, 0, sizeof(blitter));
324 static void win_blitter_free(void *handle, blitter *bl)
326 if (bl->bitmap) DeleteObject(bl->bitmap);
330 static void blitter_mkbitmap(frontend *fe, blitter *bl)
332 HDC hdc = GetDC(fe->hwnd);
333 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
334 ReleaseDC(fe->hwnd, hdc);
337 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
339 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
341 frontend *fe = (frontend *)handle;
342 HDC hdc_win, hdc_blit;
345 assert(fe->drawstatus == DRAWING);
347 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
349 bl->x = x; bl->y = y;
351 hdc_win = GetDC(fe->hwnd);
352 hdc_blit = CreateCompatibleDC(hdc_win);
353 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
355 prev_blit = SelectObject(hdc_blit, bl->bitmap);
356 if (prev_blit == NULL || prev_blit == HGDI_ERROR)
357 fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
359 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
360 fe->hdc, x, y, SRCCOPY))
361 fatal("BitBlt failed: 0x%x", GetLastError());
363 SelectObject(hdc_blit, prev_blit);
365 ReleaseDC(fe->hwnd, hdc_win);
368 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
370 frontend *fe = (frontend *)handle;
371 HDC hdc_win, hdc_blit;
374 assert(fe->drawstatus == DRAWING);
376 assert(bl->bitmap); /* we should always have saved before loading */
378 if (x == BLITTER_FROMSAVED) x = bl->x;
379 if (y == BLITTER_FROMSAVED) y = bl->y;
381 hdc_win = GetDC(fe->hwnd);
382 hdc_blit = CreateCompatibleDC(hdc_win);
384 prev_blit = SelectObject(hdc_blit, bl->bitmap);
386 BitBlt(fe->hdc, x, y, bl->w, bl->h,
387 hdc_blit, 0, 0, SRCCOPY);
389 SelectObject(hdc_blit, prev_blit);
391 ReleaseDC(fe->hwnd, hdc_win);
394 void frontend_default_colour(frontend *fe, float *output)
396 DWORD c = GetSysColor(COLOR_MENU); /* ick */
398 output[0] = (float)(GetRValue(c) / 255.0);
399 output[1] = (float)(GetGValue(c) / 255.0);
400 output[2] = (float)(GetBValue(c) / 255.0);
403 static POINT win_transform_point(frontend *fe, int x, int y)
407 assert(fe->drawstatus != NOTHING);
409 if (fe->drawstatus == PRINTING) {
410 ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
411 ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
420 static void win_text_colour(frontend *fe, int colour)
422 assert(fe->drawstatus != NOTHING);
424 if (fe->drawstatus == PRINTING) {
427 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
430 * Displaying text in hatched colours is not permitted.
434 SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
436 SetTextColor(fe->hdc, fe->colours[colour]);
440 static void win_set_brush(frontend *fe, int colour)
443 assert(fe->drawstatus != NOTHING);
445 if (fe->drawstatus == PRINTING) {
448 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
451 br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
455 * This is only ever required during printing, and the
456 * PocketPC port doesn't support printing.
458 fatal("CreateHatchBrush not supported");
460 br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
461 hatch == HATCH_SLASH ? HS_BDIAGONAL :
462 hatch == HATCH_HORIZ ? HS_HORIZONTAL :
463 hatch == HATCH_VERT ? HS_VERTICAL :
464 hatch == HATCH_PLUS ? HS_CROSS :
465 /* hatch == HATCH_X ? */ HS_DIAGCROSS,
470 br = fe->brushes[colour];
472 fe->oldbr = SelectObject(fe->hdc, br);
475 static void win_reset_brush(frontend *fe)
479 assert(fe->drawstatus != NOTHING);
481 br = SelectObject(fe->hdc, fe->oldbr);
482 if (fe->drawstatus == PRINTING)
486 static void win_set_pen(frontend *fe, int colour, int thin)
489 assert(fe->drawstatus != NOTHING);
491 if (fe->drawstatus == PRINTING) {
494 int width = thin ? 0 : fe->linewidth;
499 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
501 * Stroking in hatched colours is not permitted.
504 pen = CreatePen(fe->linedotted ? PS_DOT : PS_SOLID,
505 width, RGB(r * 255, g * 255, b * 255));
507 pen = fe->pens[colour];
509 fe->oldpen = SelectObject(fe->hdc, pen);
512 static void win_reset_pen(frontend *fe)
516 assert(fe->drawstatus != NOTHING);
518 pen = SelectObject(fe->hdc, fe->oldpen);
519 if (fe->drawstatus == PRINTING)
523 static void win_clip(void *handle, int x, int y, int w, int h)
525 frontend *fe = (frontend *)handle;
528 if (fe->drawstatus == NOTHING)
531 p = win_transform_point(fe, x, y);
532 q = win_transform_point(fe, x+w, y+h);
533 IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
536 static void win_unclip(void *handle)
538 frontend *fe = (frontend *)handle;
540 if (fe->drawstatus == NOTHING)
543 SelectClipRgn(fe->hdc, NULL);
546 static void win_draw_text(void *handle, int x, int y, int fonttype,
547 int fontsize, int align, int colour, char *text)
549 frontend *fe = (frontend *)handle;
554 if (fe->drawstatus == NOTHING)
557 if (fe->drawstatus == PRINTING)
558 fontsize = (int)(fontsize * fe->printpixelscale);
560 xy = win_transform_point(fe, x, y);
563 * Find or create the font.
565 for (i = fe->fontstart; i < fe->nfonts; i++)
566 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
569 if (i == fe->nfonts) {
570 if (fe->fontsize <= fe->nfonts) {
571 fe->fontsize = fe->nfonts + 10;
572 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
577 fe->fonts[i].type = fonttype;
578 fe->fonts[i].size = fontsize;
580 memset (&lf, 0, sizeof(LOGFONT));
581 lf.lfHeight = -fontsize;
582 lf.lfWeight = (fe->drawstatus == PRINTING ? 0 : FW_BOLD);
583 lf.lfCharSet = DEFAULT_CHARSET;
584 lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
585 lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
586 lf.lfQuality = DEFAULT_QUALITY;
587 lf.lfPitchAndFamily = (fonttype == FONT_FIXED ?
588 FIXED_PITCH | FF_DONTCARE :
589 VARIABLE_PITCH | FF_SWISS);
591 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
594 fe->fonts[i].font = CreateFontIndirect(&lf);
598 * Position and draw the text.
606 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 256);
609 oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
610 if (GetTextMetrics(fe->hdc, &tm)) {
611 if (align & ALIGN_VCENTRE)
612 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
617 if (GetTextExtentPoint32(fe->hdc, text, strlen(text), &size))
619 if (GetTextExtentPoint32(fe->hdc, wText, wcslen(wText), &size))
622 if (align & ALIGN_HCENTRE)
624 else if (align & ALIGN_HRIGHT)
627 SetBkMode(fe->hdc, TRANSPARENT);
628 win_text_colour(fe, colour);
630 TextOut(fe->hdc, xy.x, xy.y, text, strlen(text));
632 ExtTextOut(fe->hdc, xy.x, xy.y, 0, NULL, wText, wcslen(wText), NULL);
634 SelectObject(fe->hdc, oldfont);
638 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
640 frontend *fe = (frontend *)handle;
643 if (fe->drawstatus == NOTHING)
646 if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
648 * Rectangle() appears to get uppity if asked to draw a 1x1
649 * rectangle, presumably on the grounds that that's beneath
650 * its dignity and you ought to be using SetPixel instead.
653 SetPixel(fe->hdc, x, y, fe->colours[colour]);
655 win_set_brush(fe, colour);
656 win_set_pen(fe, colour, TRUE);
657 p = win_transform_point(fe, x, y);
658 q = win_transform_point(fe, x+w, y+h);
659 Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
665 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
667 frontend *fe = (frontend *)handle;
670 if (fe->drawstatus == NOTHING)
673 win_set_pen(fe, colour, FALSE);
674 pp[0] = win_transform_point(fe, x1, y1);
675 pp[1] = win_transform_point(fe, x2, y2);
676 Polyline(fe->hdc, pp, 2);
677 if (fe->drawstatus == DRAWING)
678 SetPixel(fe->hdc, pp[1].x, pp[1].y, fe->colours[colour]);
682 static void win_draw_circle(void *handle, int cx, int cy, int radius,
683 int fillcolour, int outlinecolour)
685 frontend *fe = (frontend *)handle;
688 assert(outlinecolour >= 0);
690 if (fe->drawstatus == NOTHING)
694 win_set_brush(fe, fillcolour);
696 fe->oldbr = SelectObject(fe->hdc, GetStockObject(NULL_BRUSH));
698 win_set_pen(fe, outlinecolour, FALSE);
699 p = win_transform_point(fe, cx - radius, cy - radius);
700 q = win_transform_point(fe, cx + radius, cy + radius);
701 Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
706 static void win_draw_polygon(void *handle, int *coords, int npoints,
707 int fillcolour, int outlinecolour)
709 frontend *fe = (frontend *)handle;
713 if (fe->drawstatus == NOTHING)
716 pts = snewn(npoints+1, POINT);
718 for (i = 0; i <= npoints; i++) {
719 int j = (i < npoints ? i : 0);
720 pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
723 assert(outlinecolour >= 0);
725 if (fillcolour >= 0) {
726 win_set_brush(fe, fillcolour);
727 win_set_pen(fe, outlinecolour, FALSE);
728 Polygon(fe->hdc, pts, npoints);
732 win_set_pen(fe, outlinecolour, FALSE);
733 Polyline(fe->hdc, pts, npoints+1);
740 static void win_start_draw(void *handle)
742 frontend *fe = (frontend *)handle;
745 assert(fe->drawstatus == NOTHING);
747 hdc_win = GetDC(fe->hwnd);
748 fe->hdc = CreateCompatibleDC(hdc_win);
749 fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
750 ReleaseDC(fe->hwnd, hdc_win);
753 SetMapMode(fe->hdc, MM_TEXT);
755 fe->drawstatus = DRAWING;
758 static void win_draw_update(void *handle, int x, int y, int w, int h)
760 frontend *fe = (frontend *)handle;
763 if (fe->drawstatus != DRAWING)
771 OffsetRect(&r, fe->bitmapPosition.left, fe->bitmapPosition.top);
772 InvalidateRect(fe->hwnd, &r, FALSE);
775 static void win_end_draw(void *handle)
777 frontend *fe = (frontend *)handle;
778 assert(fe->drawstatus == DRAWING);
779 SelectObject(fe->hdc, fe->prevbm);
782 DeleteObject(fe->clip);
785 fe->drawstatus = NOTHING;
788 static void win_line_width(void *handle, float width)
790 frontend *fe = (frontend *)handle;
792 assert(fe->drawstatus != DRAWING);
793 if (fe->drawstatus == NOTHING)
796 fe->linewidth = (int)(width * fe->printpixelscale);
799 static void win_line_dotted(void *handle, int dotted)
801 frontend *fe = (frontend *)handle;
803 assert(fe->drawstatus != DRAWING);
804 if (fe->drawstatus == NOTHING)
807 fe->linedotted = dotted;
810 static void win_begin_doc(void *handle, int pages)
812 frontend *fe = (frontend *)handle;
814 assert(fe->drawstatus != DRAWING);
815 if (fe->drawstatus == NOTHING)
818 if (StartDoc(fe->hdc, &fe->di) <= 0) {
819 char *e = geterrstr();
820 MessageBox(fe->hwnd, e, "Error starting to print",
821 MB_ICONERROR | MB_OK);
823 fe->drawstatus = NOTHING;
827 * Push a marker on the font stack so that we won't use the
828 * same fonts for printing and drawing. (This is because
829 * drawing seems to look generally better in bold, but printing
830 * is better not in bold.)
832 fe->fontstart = fe->nfonts;
835 static void win_begin_page(void *handle, int number)
837 frontend *fe = (frontend *)handle;
839 assert(fe->drawstatus != DRAWING);
840 if (fe->drawstatus == NOTHING)
843 if (StartPage(fe->hdc) <= 0) {
844 char *e = geterrstr();
845 MessageBox(fe->hwnd, e, "Error starting a page",
846 MB_ICONERROR | MB_OK);
848 fe->drawstatus = NOTHING;
852 static void win_begin_puzzle(void *handle, float xm, float xc,
853 float ym, float yc, int pw, int ph, float wmm)
855 frontend *fe = (frontend *)handle;
856 int ppw, pph, pox, poy;
857 float mmpw, mmph, mmox, mmoy;
860 assert(fe->drawstatus != DRAWING);
861 if (fe->drawstatus == NOTHING)
864 ppw = GetDeviceCaps(fe->hdc, HORZRES);
865 pph = GetDeviceCaps(fe->hdc, VERTRES);
866 mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
867 mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
870 * Compute the puzzle's position on the logical page.
872 mmox = xm * mmpw + xc;
873 mmoy = ym * mmph + yc;
876 * Work out what that comes to in pixels.
878 pox = (int)(mmox * (float)ppw / mmpw);
879 poy = (int)(mmoy * (float)pph / mmph);
882 * And determine the scale.
884 * I need a scale such that the maximum puzzle-coordinate
885 * extent of the rectangle (pw * scale) is equal to the pixel
886 * equivalent of the puzzle's millimetre width (wmm * ppw /
889 scale = (wmm * ppw) / (mmpw * pw);
892 * Now store pox, poy and scale for use in the main drawing
895 fe->printoffsetx = pox;
896 fe->printoffsety = poy;
897 fe->printpixelscale = scale;
900 fe->linedotted = FALSE;
903 static void win_end_puzzle(void *handle)
905 /* Nothing needs to be done here. */
908 static void win_end_page(void *handle, int number)
910 frontend *fe = (frontend *)handle;
912 assert(fe->drawstatus != DRAWING);
914 if (fe->drawstatus == NOTHING)
917 if (EndPage(fe->hdc) <= 0) {
918 char *e = geterrstr();
919 MessageBox(fe->hwnd, e, "Error finishing a page",
920 MB_ICONERROR | MB_OK);
922 fe->drawstatus = NOTHING;
926 static void win_end_doc(void *handle)
928 frontend *fe = (frontend *)handle;
930 assert(fe->drawstatus != DRAWING);
933 * Free all the fonts created since we began printing.
935 while (fe->nfonts > fe->fontstart) {
937 DeleteObject(fe->fonts[fe->nfonts].font);
942 * The MSDN web site sample code doesn't bother to call EndDoc
943 * if an error occurs half way through printing. I expect doing
944 * so would cause the erroneous document to actually be
945 * printed, or something equally undesirable.
947 if (fe->drawstatus == NOTHING)
950 if (EndDoc(fe->hdc) <= 0) {
951 char *e = geterrstr();
952 MessageBox(fe->hwnd, e, "Error finishing printing",
953 MB_ICONERROR | MB_OK);
955 fe->drawstatus = NOTHING;
959 const struct drawing_api win_drawing = {
985 void print(frontend *fe)
991 midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
996 * Create our document structure and fill it up with puzzles.
998 doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
999 for (i = 0; i < fe->printcount; i++) {
1000 if (i == 0 && fe->printcurr) {
1001 err = midend_print_puzzle(fe->me, doc, fe->printsolns);
1004 game_params *params;
1006 nme = midend_new(NULL, fe->game, NULL, NULL);
1009 * Set the non-interactive mid-end to have the same
1010 * parameters as the standard one.
1012 params = midend_get_params(fe->me);
1013 midend_set_params(nme, params);
1014 fe->game->free_params(params);
1017 midend_new_game(nme);
1018 err = midend_print_puzzle(nme, doc, fe->printsolns);
1027 MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
1028 MB_ICONERROR | MB_OK);
1033 memset(&pd, 0, sizeof(pd));
1034 pd.lStructSize = sizeof(pd);
1035 pd.hwndOwner = fe->hwnd;
1037 pd.hDevNames = NULL;
1038 pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
1039 PD_NOPAGENUMS | PD_NOSELECTION;
1041 pd.nFromPage = pd.nToPage = 0xFFFF;
1042 pd.nMinPage = pd.nMaxPage = 1;
1044 if (!PrintDlg(&pd)) {
1050 * Now pd.hDC is a device context for the printer.
1054 * FIXME: IWBNI we put up an Abort box here.
1057 memset(&fe->di, 0, sizeof(fe->di));
1058 fe->di.cbSize = sizeof(fe->di);
1059 sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
1060 " Portable Puzzle Collection)", fe->game->name);
1061 fe->di.lpszDocName = doctitle;
1062 fe->di.lpszOutput = NULL;
1063 fe->di.lpszDatatype = NULL;
1066 fe->drawstatus = PRINTING;
1069 fe->dr = drawing_new(&win_drawing, NULL, fe);
1070 document_print(doc, fe->dr);
1071 drawing_free(fe->dr);
1074 fe->drawstatus = NOTHING;
1081 void deactivate_timer(frontend *fe)
1084 return; /* for non-interactive midend */
1085 if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
1089 void activate_timer(frontend *fe)
1092 return; /* for non-interactive midend */
1094 fe->timer = SetTimer(fe->hwnd, 1, 20, NULL);
1095 fe->timer_last_tickcount = GetTickCount();
1099 void write_clip(HWND hwnd, char *data)
1107 * Windows expects CRLF in the clipboard, so we must convert
1108 * any \n that has come out of the puzzle backend.
1111 for (i = 0; data[i]; i++) {
1112 if (data[i] == '\n')
1116 data2 = snewn(len+1, char);
1118 for (i = 0; data[i]; i++) {
1119 if (data[i] == '\n')
1121 data2[j++] = data[i];
1126 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
1131 lock = GlobalLock(clipdata);
1133 GlobalFree(clipdata);
1137 memcpy(lock, data2, len);
1138 ((unsigned char *) lock)[len] = 0;
1139 GlobalUnlock(clipdata);
1141 if (OpenClipboard(hwnd)) {
1143 SetClipboardData(CF_TEXT, clipdata);
1146 GlobalFree(clipdata);
1152 * Set up Help and see if we can find a help file.
1154 static void init_help(void)
1157 char b[2048], *p, *q, *r;
1161 * Find the executable file path, so we can look alongside
1162 * it for help files. Trim the filename off the end.
1164 GetModuleFileName(NULL, b, sizeof(b) - 1);
1166 p = strrchr(b, '\\');
1167 if (p && p >= r) r = p+1;
1168 q = strrchr(b, ':');
1169 if (q && q >= r) r = q+1;
1173 * Try HTML Help first.
1175 strcpy(r, CHM_FILE_NAME);
1176 if ( (fp = fopen(b, "r")) != NULL) {
1180 * We have a .CHM. See if we can use it.
1182 hh_dll = LoadLibrary("hhctrl.ocx");
1184 htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
1186 FreeLibrary(hh_dll);
1189 help_path = dupstr(b);
1194 #endif /* NO_HTMLHELP */
1197 * Now try old-style .HLP.
1199 strcpy(r, HELP_FILE_NAME);
1200 if ( (fp = fopen(b, "r")) != NULL) {
1203 help_path = dupstr(b);
1207 * See if there's a .CNT file alongside it.
1209 strcpy(r, HELP_CNT_NAME);
1210 if ( (fp = fopen(b, "r")) != NULL) {
1212 help_has_contents = TRUE;
1214 help_has_contents = FALSE;
1219 help_type = NONE; /* didn't find any */
1228 static void start_help(frontend *fe, const char *topic)
1233 switch (help_type) {
1237 str = snewn(10+strlen(topic), char);
1238 sprintf(str, "JI(`',`%s')", topic);
1240 } else if (help_has_contents) {
1243 cmd = HELP_CONTENTS;
1245 WinHelp(fe->hwnd, help_path, cmd, (DWORD)str);
1246 fe->help_running = TRUE;
1253 str = snewn(20 + strlen(topic) + strlen(help_path), char);
1254 sprintf(str, "%s::/%s.html>main", help_path, topic);
1256 str = dupstr(help_path);
1258 htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
1259 fe->help_running = TRUE;
1261 #endif /* NO_HTMLHELP */
1263 assert(!"This shouldn't happen");
1271 * Stop Help on window cleanup.
1273 static void stop_help(frontend *fe)
1275 if (fe->help_running) {
1276 switch (help_type) {
1278 WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
1283 htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
1285 #endif /* NO_HTMLHELP */
1287 assert(!"This shouldn't happen");
1290 fe->help_running = FALSE;
1297 * Terminate Help on process exit.
1299 static void cleanup_help(void)
1301 /* Nothing to do currently.
1302 * (If we were running HTML Help single-threaded, this is where we'd
1303 * call HH_UNINITIALIZE.) */
1306 static int get_statusbar_height(frontend *fe)
1309 if (fe->statusbar) {
1311 GetWindowRect(fe->statusbar, &sr);
1312 sy = sr.bottom - sr.top;
1319 static void adjust_statusbar(frontend *fe, RECT *r)
1323 if (!fe->statusbar) return;
1325 sy = get_statusbar_height(fe);
1327 SetWindowPos(fe->statusbar, NULL, 0, r->bottom-r->top-sy, r->right-r->left,
1332 static void get_menu_size(HWND wh, RECT *r)
1334 HMENU bar = GetMenu(wh);
1338 SetRect(r, 0, 0, 0, 0);
1339 for (i = 0; i < GetMenuItemCount(bar); i++) {
1340 GetMenuItemRect(wh, bar, i, &rect);
1341 UnionRect(r, r, &rect);
1346 * Given a proposed new puzzle size (cx,cy), work out the actual
1347 * puzzle size that would be (px,py) and the window size including
1348 * furniture (wx,wy).
1351 static int check_window_resize(frontend *fe, int cx, int cy,
1356 int x, y, sy = get_statusbar_height(fe), changed = 0;
1358 /* disallow making window thinner than menu bar */
1359 x = max(cx, fe->xmin);
1360 y = max(cy - sy, fe->ymin);
1363 * See if we actually got the window size we wanted, and adjust
1364 * the puzzle size if not.
1366 midend_size(fe->me, &x, &y, TRUE);
1367 if (x != cx || y != cy) {
1369 * Resize the window, now we know what size we _really_
1375 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1376 *wx = r.right - r.left;
1377 *wy = r.bottom - r.top;
1385 (float)midend_tilesize(fe->me) / (float)fe->game->preferred_tilesize;
1391 * Given the current window size, make sure it's sane for the
1392 * current puzzle and resize if necessary.
1395 static void check_window_size(frontend *fe, int *px, int *py)
1400 GetClientRect(fe->hwnd, &r);
1401 cx = r.right - r.left;
1402 cy = r.bottom - r.top;
1404 if (check_window_resize(fe, cx, cy, px, py, &wx, &wy)) {
1406 SetWindowPos(fe->hwnd, NULL, 0, 0, wx, wy,
1407 SWP_NOMOVE | SWP_NOZORDER);
1412 GetClientRect(fe->hwnd, &r);
1413 adjust_statusbar(fe, &r);
1416 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1420 if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1421 *x = sr.right - sr.left;
1422 *y = sr.bottom - sr.top;
1427 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1428 *x -= r.right - r.left - 100;
1429 *y -= r.bottom - r.top - 100;
1434 if (fe->statusbar != NULL) {
1435 GetWindowRect(fe->statusbar, &sr);
1436 *y -= sr.bottom - sr.top;
1441 /* Toolbar buttons on the numeric pad */
1442 static TBBUTTON tbNumpadButtons[] =
1444 {0, IDM_KEYEMUL + '1', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1445 {1, IDM_KEYEMUL + '2', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1446 {2, IDM_KEYEMUL + '3', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1447 {3, IDM_KEYEMUL + '4', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1448 {4, IDM_KEYEMUL + '5', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1449 {5, IDM_KEYEMUL + '6', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1450 {6, IDM_KEYEMUL + '7', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1451 {7, IDM_KEYEMUL + '8', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1452 {8, IDM_KEYEMUL + '9', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1453 {9, IDM_KEYEMUL + ' ', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1}
1458 * Allocate a new frontend structure and create its main window.
1460 static frontend *frontend_new(HINSTANCE inst)
1463 const char *nogame = "Puzzles (no game selected)";
1465 fe = snew(frontend);
1475 fe->help_running = FALSE;
1477 fe->drawstatus = NOTHING;
1482 fe->nfonts = fe->fontsize = 0;
1488 fe->puzz_scale = 1.0;
1491 MultiByteToWideChar (CP_ACP, 0, nogame, -1, wGameName, 256);
1492 fe->hwnd = CreateWindowEx(0, wClassName, wGameName,
1494 CW_USEDEFAULT, CW_USEDEFAULT,
1495 CW_USEDEFAULT, CW_USEDEFAULT,
1496 NULL, NULL, inst, NULL);
1500 RECT rc, rcBar, rcTB, rcClient;
1502 memset (&mbi, 0, sizeof(SHMENUBARINFO));
1503 mbi.cbSize = sizeof(SHMENUBARINFO);
1504 mbi.hwndParent = fe->hwnd;
1505 mbi.nToolBarId = IDR_MENUBAR1;
1506 mbi.hInstRes = inst;
1508 SHCreateMenuBar(&mbi);
1510 GetWindowRect(fe->hwnd, &rc);
1511 GetWindowRect(mbi.hwndMB, &rcBar);
1512 rc.bottom -= rcBar.bottom - rcBar.top;
1513 MoveWindow(fe->hwnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, FALSE);
1518 fe->hwnd = CreateWindowEx(0, CLASSNAME, nogame,
1519 WS_OVERLAPPEDWINDOW &~
1521 CW_USEDEFAULT, CW_USEDEFAULT,
1522 CW_USEDEFAULT, CW_USEDEFAULT,
1523 NULL, NULL, inst, NULL);
1525 DWORD lerr = GetLastError();
1526 printf("no window: 0x%x\n", lerr);
1530 fe->gamemenu = NULL;
1533 fe->statusbar = NULL;
1536 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1542 * Populate a frontend structure with a (new) game and midend structure, and
1543 * create any window furniture that it needs.
1545 * Previously-allocated memory and window furniture will be freed by this function.
1547 static int new_game(frontend *fe, const game *game, char *game_id, char **error)
1554 if (fe->me) midend_free(fe->me);
1555 fe->me = midend_new(fe, fe->game, &win_drawing, fe);
1558 *error = midend_game_id(fe->me, game_id);
1560 midend_free(fe->me);
1566 midend_new_game(fe->me);
1572 colours = midend_colours(fe->me, &ncolours);
1574 if (fe->colours) sfree(fe->colours);
1575 if (fe->brushes) sfree(fe->brushes);
1576 if (fe->pens) sfree(fe->pens);
1578 fe->colours = snewn(ncolours, COLORREF);
1579 fe->brushes = snewn(ncolours, HBRUSH);
1580 fe->pens = snewn(ncolours, HPEN);
1582 for (i = 0; i < ncolours; i++) {
1583 fe->colours[i] = RGB(255 * colours[i*3+0],
1584 255 * colours[i*3+1],
1585 255 * colours[i*3+2]);
1586 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1587 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1593 DestroyWindow(fe->statusbar);
1594 if (midend_wants_statusbar(fe->me)) {
1595 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1596 WS_CHILD | WS_VISIBLE,
1597 0, 0, 0, 0, /* status bar does these */
1598 NULL, NULL, fe->inst, NULL);
1600 fe->statusbar = NULL;
1602 get_max_puzzle_size(fe, &x, &y);
1603 midend_size(fe->me, &x, &y, FALSE);
1608 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1612 DestroyWindow(fe->numpad);
1613 if (fe->game->flags & REQUIRE_NUMPAD)
1615 fe->numpad = CreateToolbarEx (fe->hwnd,
1616 WS_VISIBLE | WS_CHILD | CCS_NOPARENTALIGN | TBSTYLE_FLAT,
1617 0, 10, fe->inst, IDR_PADTOOLBAR,
1618 tbNumpadButtons, sizeof (tbNumpadButtons) / sizeof (TBBUTTON),
1619 0, 0, 14, 15, sizeof (TBBUTTON));
1620 GetWindowRect(fe->numpad, &rcTB);
1621 GetClientRect(fe->hwnd, &rcClient);
1622 MoveWindow(fe->numpad,
1624 rcClient.bottom - (rcTB.bottom - rcTB.top) - 1,
1626 rcTB.bottom - rcTB.top,
1628 SendMessage(fe->numpad, TB_SETINDENT, (rcClient.right - (10 * 21)) / 2, 0);
1633 MultiByteToWideChar (CP_ACP, 0, fe->game->name, -1, wGameName, 256);
1634 SetWindowText(fe->hwnd, wGameName);
1636 SetWindowText(fe->hwnd, fe->game->name);
1640 DestroyWindow(fe->statusbar);
1641 if (midend_wants_statusbar(fe->me)) {
1643 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1644 WS_CHILD | WS_VISIBLE,
1645 0, 0, 0, 0, /* status bar does these */
1646 fe->hwnd, NULL, fe->inst, NULL);
1648 /* Flat status bar looks better on the Pocket PC */
1649 SendMessage(fe->statusbar, SB_SIMPLE, (WPARAM) TRUE, 0);
1650 SendMessage(fe->statusbar, SB_SETTEXT,
1651 (WPARAM) 255 | SBT_NOBORDERS,
1656 * Now resize the window to take account of the status bar.
1658 GetWindowRect(fe->statusbar, &sr);
1659 GetWindowRect(fe->hwnd, &r);
1661 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1662 r.bottom - r.top + sr.bottom - sr.top,
1663 SWP_NOMOVE | SWP_NOZORDER);
1666 fe->statusbar = NULL;
1670 HMENU oldmenu = GetMenu(fe->hwnd);
1673 HMENU bar = CreateMenu();
1674 HMENU menu = CreateMenu();
1677 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "&Game");
1679 HMENU menu = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_GAME);
1680 DeleteMenu(menu, 0, MF_BYPOSITION);
1682 fe->gamemenu = menu;
1683 AppendMenu(menu, MF_ENABLED, IDM_NEW, TEXT("&New"));
1684 AppendMenu(menu, MF_ENABLED, IDM_RESTART, TEXT("&Restart"));
1686 /* ...here I run out of sensible accelerator characters. */
1687 AppendMenu(menu, MF_ENABLED, IDM_DESC, TEXT("Speci&fic..."));
1688 AppendMenu(menu, MF_ENABLED, IDM_SEED, TEXT("Rando&m Seed..."));
1693 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1694 fe->game->can_configure) {
1697 HMENU sub = CreateMenu();
1699 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "&Type");
1701 HMENU sub = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_TYPE);
1702 DeleteMenu(sub, 0, MF_BYPOSITION);
1704 fe->presets = snewn(fe->npresets, game_params *);
1706 for (i = 0; i < fe->npresets; i++) {
1712 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1715 * FIXME: we ought to go through and do something
1716 * with ampersands here.
1720 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1722 MultiByteToWideChar (CP_ACP, 0, name, -1, wName, 255);
1723 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, wName);
1726 if (fe->game->can_configure) {
1727 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, TEXT("&Custom..."));
1732 fe->typemenu = INVALID_HANDLE_VALUE;
1738 #error Windows CE does not support COMBINED build.
1741 HMENU games = CreateMenu();
1744 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1745 AppendMenu(menu, MF_ENABLED|MF_POPUP, (UINT)games, "&Other");
1746 for (i = 0; i < gamecount; i++) {
1747 if (strcmp(gamelist[i]->name, fe->game->name) != 0) {
1748 /* only include those games that aren't the same as the
1749 * game we're currently playing. */
1750 AppendMenu(games, MF_ENABLED, IDM_GAMES + i, gamelist[i]->name);
1756 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1758 AppendMenu(menu, MF_ENABLED, IDM_LOAD, TEXT("&Load..."));
1759 AppendMenu(menu, MF_ENABLED, IDM_SAVE, TEXT("&Save..."));
1760 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1761 if (fe->game->can_print) {
1762 AppendMenu(menu, MF_ENABLED, IDM_PRINT, TEXT("&Print..."));
1763 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1766 AppendMenu(menu, MF_ENABLED, IDM_UNDO, TEXT("Undo"));
1767 AppendMenu(menu, MF_ENABLED, IDM_REDO, TEXT("Redo"));
1769 if (fe->game->can_format_as_text_ever) {
1770 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1771 AppendMenu(menu, MF_ENABLED, IDM_COPY, TEXT("&Copy"));
1774 if (fe->game->can_solve) {
1775 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1776 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, TEXT("Sol&ve"));
1778 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1780 AppendMenu(menu, MF_ENABLED, IDM_QUIT, TEXT("E&xit"));
1781 menu = CreateMenu();
1782 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, TEXT("&Help"));
1784 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, TEXT("&About"));
1786 if (help_type != NONE) {
1788 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1789 AppendMenu(menu, MF_ENABLED, IDM_HELPC, TEXT("&Contents"));
1790 assert(fe->game->name);
1791 item = snewn(10+strlen(fe->game->name), char); /*ick*/
1792 sprintf(item, "&Help on %s", fe->game->name);
1793 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1796 DestroyMenu(oldmenu);
1797 SetMenu(fe->hwnd, bar);
1798 get_menu_size(fe->hwnd, &menusize);
1799 fe->xmin = (menusize.right - menusize.left) + 25;
1803 if (fe->bitmap) DeleteObject(fe->bitmap);
1805 new_game_size(fe, fe->puzz_scale); /* initialises fe->bitmap */
1810 static void show_window(frontend *fe)
1812 ShowWindow(fe->hwnd, SW_SHOWNORMAL);
1813 SetForegroundWindow(fe->hwnd);
1815 update_type_menu_tick(fe);
1816 update_copy_menu_greying(fe);
1818 midend_redraw(fe->me);
1822 static HFONT dialog_title_font()
1824 static HFONT hf = NULL;
1830 memset (&lf, 0, sizeof(LOGFONT));
1831 lf.lfHeight = -11; /* - ((8 * GetDeviceCaps(hdc, LOGPIXELSY)) / 72) */
1832 lf.lfWeight = FW_BOLD;
1833 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
1835 return hf = CreateFontIndirect(&lf);
1838 static void make_dialog_full_screen(HWND hwnd)
1840 SHINITDLGINFO shidi;
1842 /* Make dialog full screen */
1843 shidi.dwMask = SHIDIM_FLAGS;
1844 shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIZEDLGFULLSCREEN |
1847 SHInitDialog(&shidi);
1851 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1852 WPARAM wParam, LPARAM lParam)
1854 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1862 make_dialog_full_screen(hwnd);
1864 sprintf(title, "About %.250s", fe->game->name);
1865 SetDlgItemTextA(hwnd, IDC_ABOUT_CAPTION, title);
1867 SendDlgItemMessage(hwnd, IDC_ABOUT_CAPTION, WM_SETFONT,
1868 (WPARAM) dialog_title_font(), 0);
1870 SetDlgItemTextA(hwnd, IDC_ABOUT_GAME, fe->game->name);
1871 SetDlgItemTextA(hwnd, IDC_ABOUT_VERSION, ver);
1877 if (LOWORD(wParam) == IDOK)
1898 * Wrappers on midend_{get,set}_config, which extend the CFG_*
1899 * enumeration to add CFG_PRINT.
1901 static config_item *frontend_get_config(frontend *fe, int which,
1904 if (which < CFG_FRONTEND_SPECIFIC) {
1905 return midend_get_config(fe->me, which, wintitle);
1906 } else if (which == CFG_PRINT) {
1910 *wintitle = snewn(40 + strlen(fe->game->name), char);
1911 sprintf(*wintitle, "%s print setup", fe->game->name);
1913 ret = snewn(8, config_item);
1917 ret[i].name = "Number of puzzles to print";
1918 ret[i].type = C_STRING;
1919 ret[i].sval = dupstr("1");
1923 ret[i].name = "Number of puzzles across the page";
1924 ret[i].type = C_STRING;
1925 ret[i].sval = dupstr("1");
1929 ret[i].name = "Number of puzzles down the page";
1930 ret[i].type = C_STRING;
1931 ret[i].sval = dupstr("1");
1935 ret[i].name = "Percentage of standard size";
1936 ret[i].type = C_STRING;
1937 ret[i].sval = dupstr("100.0");
1941 ret[i].name = "Include currently shown puzzle";
1942 ret[i].type = C_BOOLEAN;
1947 ret[i].name = "Print solutions";
1948 ret[i].type = C_BOOLEAN;
1950 ret[i].ival = FALSE;
1953 if (fe->game->can_print_in_colour) {
1954 ret[i].name = "Print in colour";
1955 ret[i].type = C_BOOLEAN;
1957 ret[i].ival = FALSE;
1962 ret[i].type = C_END;
1969 assert(!"We should never get here");
1974 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
1976 if (which < CFG_FRONTEND_SPECIFIC) {
1977 return midend_set_config(fe->me, which, cfg);
1978 } else if (which == CFG_PRINT) {
1979 if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
1980 return "Number of puzzles to print should be at least one";
1981 if ((fe->printw = atoi(cfg[1].sval)) <= 0)
1982 return "Number of puzzles across the page should be at least one";
1983 if ((fe->printh = atoi(cfg[2].sval)) <= 0)
1984 return "Number of puzzles down the page should be at least one";
1985 if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
1986 return "Print size should be positive";
1987 fe->printcurr = cfg[4].ival;
1988 fe->printsolns = cfg[5].ival;
1989 fe->printcolour = fe->game->can_print_in_colour && cfg[6].ival;
1992 assert(!"We should never get here");
1993 return "Internal error";
1998 /* Separate version of mkctrl function for the Pocket PC. */
1999 /* Control coordinates should be specified in dialog units. */
2000 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2001 LPCTSTR wclass, int wstyle,
2002 int exstyle, const char *wtext, int wid)
2007 /* Convert dialog units into pixels */
2008 rc.left = x1; rc.right = x2;
2009 rc.top = y1; rc.bottom = y2;
2010 MapDialogRect(fe->cfgbox, &rc);
2012 MultiByteToWideChar (CP_ACP, 0, wtext, -1, wwtext, 256);
2014 return CreateWindowEx(exstyle, wclass, wwtext,
2015 wstyle | WS_CHILD | WS_VISIBLE,
2017 rc.right - rc.left, rc.bottom - rc.top,
2018 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2021 static void create_config_controls(frontend * fe)
2024 int col1l, col1r, col2l, col2r, y;
2029 /* Control placement done in dialog units */
2030 col1l = 4; col1r = 96; /* Label column */
2031 col2l = 100; col2r = 154; /* Input column (edit boxes and combo boxes) */
2034 * Count the controls so we can allocate cfgaux.
2036 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2038 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2041 y = 22; /* Leave some room for the dialog title */
2042 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2046 * Edit box with a label beside it.
2048 mkctrl(fe, col1l, col1r, y + 1, y + 11,
2049 TEXT("Static"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
2050 mkctrl(fe, col2l, col2r, y, y + 12,
2051 TEXT("EDIT"), WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
2052 0, "", (j->ctlid = id++));
2053 SetDlgItemTextA(fe->cfgbox, j->ctlid, i->sval);
2060 mkctrl(fe, col1l, col2r, y + 1, y + 11, TEXT("BUTTON"),
2061 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2062 0, i->name, (j->ctlid = id++));
2063 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2068 * Drop-down list with a label beside it.
2070 mkctrl(fe, col1l, col1r, y + 1, y + 11,
2071 TEXT("STATIC"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
2072 ctl = mkctrl(fe, col2l, col2r, y, y + 48,
2073 TEXT("COMBOBOX"), WS_BORDER | WS_TABSTOP |
2074 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2075 0, "", (j->ctlid = id++));
2077 char c, *p, *q, *str;
2083 while (*q && *q != c) q++;
2084 str = snewn(q-p+1, char);
2085 strncpy(str, p, q-p);
2089 MultiByteToWideChar (CP_ACP, 0, str, -1, ws, 50);
2090 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)ws);
2098 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2108 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
2109 WPARAM wParam, LPARAM lParam)
2111 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2121 fe = (frontend *) lParam;
2122 SetWindowLong(hwnd, GWL_USERDATA, lParam);
2125 fe->cfg = frontend_get_config(fe, fe->cfg_which, &title);
2127 make_dialog_full_screen(hwnd);
2129 SetDlgItemTextA(hwnd, IDC_CONFIG_CAPTION, title);
2130 SendDlgItemMessage(hwnd, IDC_CONFIG_CAPTION, WM_SETFONT,
2131 (WPARAM) dialog_title_font(), 0);
2133 create_config_controls(fe);
2140 * OK and Cancel are special cases.
2142 if ((LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
2143 if (LOWORD(wParam) == IDOK) {
2144 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
2147 MessageBox(hwnd, err, "Validation error",
2148 MB_ICONERROR | MB_OK);
2167 * First find the control whose id this is.
2169 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2170 if (j->ctlid == LOWORD(wParam))
2173 if (i->type == C_END)
2174 return 0; /* not our problem */
2176 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
2179 TCHAR wBuffer[4096];
2180 GetDlgItemText(fe->cfgbox, j->ctlid, wBuffer, 4096);
2181 WideCharToMultiByte(CP_ACP, 0, wBuffer, -1, buffer, 4096, NULL, NULL);
2183 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
2185 buffer[lenof(buffer)-1] = '\0';
2187 i->sval = dupstr(buffer);
2188 } else if (i->type == C_BOOLEAN &&
2189 (HIWORD(wParam) == BN_CLICKED ||
2190 HIWORD(wParam) == BN_DBLCLK)) {
2191 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
2192 } else if (i->type == C_CHOICES &&
2193 HIWORD(wParam) == CBN_SELCHANGE) {
2194 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
2195 CB_GETCURSEL, 0, 0);
2209 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2210 char *wclass, int wstyle,
2211 int exstyle, const char *wtext, int wid)
2214 ret = CreateWindowEx(exstyle, wclass, wtext,
2215 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
2216 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2217 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
2222 static void about(frontend *fe)
2225 DialogBox(fe->inst, MAKEINTRESOURCE(IDD_ABOUT), fe->hwnd, AboutDlgProc);
2235 int winwidth, winheight, y;
2236 int height, width, maxwid;
2237 const char *strings[16];
2242 sprintf(titlebuf, "About %.250s", fe->game->name);
2244 strings[nstrings++] = fe->game->name;
2245 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
2246 strings[nstrings++] = ver;
2248 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2249 wc.lpfnWndProc = DefDlgProc;
2251 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2252 wc.hInstance = fe->inst;
2254 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2255 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2256 wc.lpszMenuName = NULL;
2257 wc.lpszClassName = "GameAboutBox";
2260 hdc = GetDC(fe->hwnd);
2261 SetMapMode(hdc, MM_TEXT);
2263 fe->dlg_done = FALSE;
2265 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2267 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2268 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2273 oldfont = SelectObject(hdc, fe->cfgfont);
2274 if (GetTextMetrics(hdc, &tm)) {
2275 height = tm.tmAscent + tm.tmDescent;
2276 width = tm.tmAveCharWidth;
2278 height = width = 30;
2282 * Figure out the layout of the About box by measuring the
2283 * length of each piece of text.
2286 winheight = height/2;
2288 for (i = 0; i < nstrings; i++) {
2289 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
2290 lengths[i] = size.cx;
2292 lengths[i] = 0; /* *shrug* */
2293 if (maxwid < lengths[i])
2294 maxwid = lengths[i];
2295 winheight += height * 3 / 2 + (height / 2);
2298 winheight += height + height * 7 / 4; /* OK button */
2299 winwidth = maxwid + 4*width;
2301 SelectObject(hdc, oldfont);
2302 ReleaseDC(fe->hwnd, hdc);
2305 * Create the dialog, now that we know its size.
2312 r.bottom = winheight;
2314 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2315 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2316 WS_CAPTION | WS_SYSMENU*/) &~
2317 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2321 * Centre the dialog on its parent window.
2325 GetWindowRect(fe->hwnd, &r2);
2326 r.left = (r2.left + r2.right - r.right) / 2;
2327 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2331 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
2332 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2333 WS_CAPTION | WS_SYSMENU,
2335 r.right-r.left, r.bottom-r.top,
2336 fe->hwnd, NULL, fe->inst, NULL);
2339 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2341 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2342 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
2346 for (i = 0; i < nstrings; i++) {
2347 int border = width*2 + (maxwid - lengths[i]) / 2;
2348 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
2349 "Static", 0, 0, strings[i], id++);
2352 assert(y < winheight);
2356 y += height/2; /* extra space before OK */
2357 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
2358 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2361 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2363 EnableWindow(fe->hwnd, FALSE);
2364 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2365 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2366 if (!IsDialogMessage(fe->cfgbox, &msg))
2367 DispatchMessage(&msg);
2371 EnableWindow(fe->hwnd, TRUE);
2372 SetForegroundWindow(fe->hwnd);
2373 DestroyWindow(fe->cfgbox);
2374 DeleteObject(fe->cfgfont);
2378 static int get_config(frontend *fe, int which)
2381 fe->cfg_which = which;
2383 return DialogBoxParam(fe->inst,
2384 MAKEINTRESOURCE(IDD_CONFIG),
2385 fe->hwnd, ConfigDlgProc,
2399 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
2400 int height, width, maxlabel, maxcheckbox;
2402 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2403 wc.lpfnWndProc = DefDlgProc;
2405 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2406 wc.hInstance = fe->inst;
2408 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2409 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2410 wc.lpszMenuName = NULL;
2411 wc.lpszClassName = "GameConfigBox";
2414 hdc = GetDC(fe->hwnd);
2415 SetMapMode(hdc, MM_TEXT);
2417 fe->dlg_done = FALSE;
2419 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2421 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2422 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2427 oldfont = SelectObject(hdc, fe->cfgfont);
2428 if (GetTextMetrics(hdc, &tm)) {
2429 height = tm.tmAscent + tm.tmDescent;
2430 width = tm.tmAveCharWidth;
2432 height = width = 30;
2435 fe->cfg = frontend_get_config(fe, which, &title);
2436 fe->cfg_which = which;
2439 * Figure out the layout of the config box by measuring the
2440 * length of each piece of text.
2442 maxlabel = maxcheckbox = 0;
2443 winheight = height/2;
2445 for (i = fe->cfg; i->type != C_END; i++) {
2450 * Both these control types have a label filling only
2451 * the left-hand column of the box.
2453 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2456 winheight += height * 3 / 2 + (height / 2);
2461 * Checkboxes take up the whole of the box width.
2463 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2464 maxcheckbox < size.cx)
2465 maxcheckbox = size.cx;
2466 winheight += height + (height / 2);
2471 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
2474 col1r = col1l + maxlabel;
2475 col2l = col1r + 2*width;
2476 col2r = col2l + 30*width;
2477 if (col2r < col1l+2*height+maxcheckbox)
2478 col2r = col1l+2*height+maxcheckbox;
2479 winwidth = col2r + 2*width;
2481 SelectObject(hdc, oldfont);
2482 ReleaseDC(fe->hwnd, hdc);
2485 * Create the dialog, now that we know its size.
2492 r.bottom = winheight;
2494 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2495 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2496 WS_CAPTION | WS_SYSMENU*/) &~
2497 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2501 * Centre the dialog on its parent window.
2505 GetWindowRect(fe->hwnd, &r2);
2506 r.left = (r2.left + r2.right - r.right) / 2;
2507 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2511 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
2512 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2513 WS_CAPTION | WS_SYSMENU,
2515 r.right-r.left, r.bottom-r.top,
2516 fe->hwnd, NULL, fe->inst, NULL);
2520 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2522 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2523 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
2526 * Count the controls so we can allocate cfgaux.
2528 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2530 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2534 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2538 * Edit box with a label beside it.
2540 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2541 "Static", 0, 0, i->name, id++);
2542 ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
2543 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
2544 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2545 SetWindowText(ctl, i->sval);
2553 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
2554 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2555 0, i->name, (j->ctlid = id++));
2556 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2562 * Drop-down list with a label beside it.
2564 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2565 "STATIC", 0, 0, i->name, id++);
2566 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
2567 "COMBOBOX", WS_TABSTOP |
2568 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2569 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2571 char c, *p, *q, *str;
2573 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
2578 while (*q && *q != c) q++;
2579 str = snewn(q-p+1, char);
2580 strncpy(str, p, q-p);
2582 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
2589 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2595 assert(y < winheight);
2599 y += height/2; /* extra space before OK and Cancel */
2600 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
2601 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2603 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
2604 BS_PUSHBUTTON | WS_TABSTOP, 0, "Cancel", IDCANCEL);
2606 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2608 EnableWindow(fe->hwnd, FALSE);
2609 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2610 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2611 if (!IsDialogMessage(fe->cfgbox, &msg))
2612 DispatchMessage(&msg);
2616 EnableWindow(fe->hwnd, TRUE);
2617 SetForegroundWindow(fe->hwnd);
2618 DestroyWindow(fe->cfgbox);
2619 DeleteObject(fe->cfgfont);
2624 return (fe->dlg_done == 2);
2629 static void calculate_bitmap_position(frontend *fe, int x, int y)
2631 /* Pocket PC - center the game in the full screen window */
2635 GetClientRect(fe->hwnd, &rcClient);
2636 fe->bitmapPosition.left = (rcClient.right - x) / 2;
2637 yMargin = rcClient.bottom - y;
2639 if (fe->numpad != NULL) {
2641 GetWindowRect(fe->numpad, &rcPad);
2642 yMargin -= rcPad.bottom - rcPad.top;
2645 if (fe->statusbar != NULL) {
2647 GetWindowRect(fe->statusbar, &rcStatus);
2648 yMargin -= rcStatus.bottom - rcStatus.top;
2651 fe->bitmapPosition.top = yMargin / 2;
2653 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2654 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2657 static void calculate_bitmap_position(frontend *fe, int x, int y)
2659 /* Plain Windows - position the game in the upper-left corner */
2660 fe->bitmapPosition.left = 0;
2661 fe->bitmapPosition.top = 0;
2662 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2663 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2667 static void new_bitmap(frontend *fe, int x, int y)
2671 if (fe->bitmap) DeleteObject(fe->bitmap);
2673 hdc = GetDC(fe->hwnd);
2674 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2675 calculate_bitmap_position(fe, x, y);
2676 ReleaseDC(fe->hwnd, hdc);
2679 static void new_game_size(frontend *fe, float scale)
2684 get_max_puzzle_size(fe, &x, &y);
2685 midend_size(fe->me, &x, &y, FALSE);
2688 x = (int)((float)x * fe->puzz_scale);
2689 y = (int)((float)y * fe->puzz_scale);
2690 midend_size(fe->me, &x, &y, TRUE);
2692 fe->ymin = (fe->xmin * y) / x;
2697 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2699 if (fe->statusbar != NULL) {
2700 GetWindowRect(fe->statusbar, &sr);
2702 sr.left = sr.right = sr.top = sr.bottom = 0;
2705 SetWindowPos(fe->hwnd, NULL, 0, 0,
2707 r.bottom - r.top + sr.bottom - sr.top,
2708 SWP_NOMOVE | SWP_NOZORDER);
2711 check_window_size(fe, &x, &y);
2714 if (fe->statusbar != NULL)
2715 SetWindowPos(fe->statusbar, NULL, 0, y, x,
2716 sr.bottom - sr.top, SWP_NOZORDER);
2719 new_bitmap(fe, x, y);
2722 InvalidateRect(fe->hwnd, NULL, TRUE);
2724 midend_redraw(fe->me);
2728 * Given a proposed new window rect, work out the resulting
2729 * difference in client size (from current), and use to try
2730 * and resize the puzzle, returning (wx,wy) as the actual
2734 static void adjust_game_size(frontend *fe, RECT *proposed, int isedge,
2735 int *wx_r, int *wy_r)
2738 int nx, ny, xdiff, ydiff, wx, wy;
2740 /* Work out the current window sizing, and thus the
2741 * difference in size we're asking for. */
2742 GetClientRect(fe->hwnd, &cr);
2744 AdjustWindowRectEx(&wr, WINFLAGS, TRUE, 0);
2746 xdiff = (proposed->right - proposed->left) - (wr.right - wr.left);
2747 ydiff = (proposed->bottom - proposed->top) - (wr.bottom - wr.top);
2750 /* These next four lines work around the fact that midend_size
2751 * is happy to shrink _but not grow_ if you change one dimension
2752 * but not the other. */
2753 if (xdiff > 0 && ydiff == 0)
2754 ydiff = (xdiff * (wr.right - wr.left)) / (wr.bottom - wr.top);
2755 if (xdiff == 0 && ydiff > 0)
2756 xdiff = (ydiff * (wr.bottom - wr.top)) / (wr.right - wr.left);
2759 if (check_window_resize(fe,
2760 (cr.right - cr.left) + xdiff,
2761 (cr.bottom - cr.top) + ydiff,
2762 &nx, &ny, &wx, &wy)) {
2763 new_bitmap(fe, nx, ny);
2764 midend_force_redraw(fe->me);
2766 /* reset size to current window size */
2767 wx = wr.right - wr.left;
2768 wy = wr.bottom - wr.top;
2770 /* Re-fetch rectangle; size limits mean we might not have
2771 * taken it quite to the mouse drag positions. */
2772 GetClientRect(fe->hwnd, &cr);
2773 adjust_statusbar(fe, &cr);
2775 *wx_r = wx; *wy_r = wy;
2778 static void update_type_menu_tick(frontend *fe)
2782 if (fe->typemenu == INVALID_HANDLE_VALUE)
2785 total = GetMenuItemCount(fe->typemenu);
2786 n = midend_which_preset(fe->me);
2788 n = total - 1; /* "Custom" item */
2790 for (i = 0; i < total; i++) {
2791 int flag = (i == n ? MF_CHECKED : MF_UNCHECKED);
2792 CheckMenuItem(fe->typemenu, i, MF_BYPOSITION | flag);
2795 DrawMenuBar(fe->hwnd);
2798 static void update_copy_menu_greying(frontend *fe)
2800 UINT enable = (midend_can_format_as_text_now(fe->me) ?
2801 MF_ENABLED : MF_GRAYED);
2802 EnableMenuItem(fe->gamemenu, IDM_COPY, MF_BYCOMMAND | enable);
2805 static void new_game_type(frontend *fe)
2807 midend_new_game(fe->me);
2808 new_game_size(fe, 1.0);
2809 update_type_menu_tick(fe);
2810 update_copy_menu_greying(fe);
2813 static int is_alt_pressed(void)
2816 int r = GetKeyboardState(keystate);
2819 if (keystate[VK_MENU] & 0x80)
2821 if (keystate[VK_RMENU] & 0x80)
2826 static void savefile_write(void *wctx, void *buf, int len)
2828 FILE *fp = (FILE *)wctx;
2829 fwrite(buf, 1, len, fp);
2832 static int savefile_read(void *wctx, void *buf, int len)
2834 FILE *fp = (FILE *)wctx;
2837 ret = fread(buf, 1, len, fp);
2838 return (ret == len);
2841 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2842 WPARAM wParam, LPARAM lParam)
2844 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2849 DestroyWindow(hwnd);
2853 /* Numeric pad sends WM_COMMAND messages */
2854 if ((wParam >= IDM_KEYEMUL) && (wParam < IDM_KEYEMUL + 256))
2856 midend_process_key(fe->me, 0, 0, wParam - IDM_KEYEMUL);
2859 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
2862 if (!midend_process_key(fe->me, 0, 0, 'n'))
2866 midend_restart_game(fe->me);
2869 if (!midend_process_key(fe->me, 0, 0, 'u'))
2873 if (!midend_process_key(fe->me, 0, 0, '\x12'))
2878 char *text = midend_text_format(fe->me);
2880 write_clip(hwnd, text);
2882 MessageBeep(MB_ICONWARNING);
2888 char *msg = midend_solve(fe->me);
2890 MessageBox(hwnd, msg, "Unable to solve",
2891 MB_ICONERROR | MB_OK);
2895 if (!midend_process_key(fe->me, 0, 0, 'q'))
2899 if (get_config(fe, CFG_SETTINGS))
2903 if (get_config(fe, CFG_SEED))
2907 if (get_config(fe, CFG_DESC))
2911 if (get_config(fe, CFG_PRINT))
2921 char filename[FILENAME_MAX];
2924 memset(&of, 0, sizeof(of));
2925 of.hwndOwner = hwnd;
2926 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
2927 of.lpstrCustomFilter = NULL;
2928 of.nFilterIndex = 1;
2929 of.lpstrFile = filename;
2931 of.nMaxFile = lenof(filename);
2932 of.lpstrFileTitle = NULL;
2933 of.lpstrTitle = (cmd == IDM_SAVE ?
2934 "Enter name of game file to save" :
2935 "Enter name of saved game file to load");
2937 #ifdef OPENFILENAME_SIZE_VERSION_400
2938 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2940 of.lStructSize = sizeof(of);
2942 of.lpstrInitialDir = NULL;
2944 if (cmd == IDM_SAVE)
2945 ret = GetSaveFileName(&of);
2947 ret = GetOpenFileName(&of);
2950 if (cmd == IDM_SAVE) {
2953 if ((fp = fopen(filename, "r")) != NULL) {
2954 char buf[256 + FILENAME_MAX];
2958 sprintf(buf, "Are you sure you want to overwrite"
2959 " the file \"%.*s\"?",
2960 FILENAME_MAX, filename);
2961 if (MessageBox(hwnd, buf, "Question",
2962 MB_YESNO | MB_ICONQUESTION)
2967 fp = fopen(filename, "w");
2970 MessageBox(hwnd, "Unable to open save file",
2971 "Error", MB_ICONERROR | MB_OK);
2975 midend_serialise(fe->me, savefile_write, fp);
2979 FILE *fp = fopen(filename, "r");
2983 MessageBox(hwnd, "Unable to open saved game file",
2984 "Error", MB_ICONERROR | MB_OK);
2988 err = midend_deserialise(fe->me, savefile_read, fp);
2993 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
2997 new_game_size(fe, 1.0);
3005 start_help(fe, NULL);
3008 assert(help_type != NONE);
3009 start_help(fe, help_type == CHM ?
3010 fe->game->htmlhelp_topic : fe->game->winhelp_topic);
3015 if (wParam >= IDM_GAMES && wParam < (IDM_GAMES + (WPARAM)gamecount)) {
3016 int p = wParam - IDM_GAMES;
3019 new_game(fe, gamelist[p], NULL, &error);
3023 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
3025 if (p >= 0 && p < fe->npresets) {
3026 midend_set_params(fe->me, fe->presets[p]);
3047 hdc = BeginPaint(hwnd, &p);
3048 hdc2 = CreateCompatibleDC(hdc);
3049 prevbm = SelectObject(hdc2, fe->bitmap);
3051 FillRect(hdc, &(p.rcPaint), (HBRUSH) GetStockObject(WHITE_BRUSH));
3053 IntersectRect(&rcDest, &(fe->bitmapPosition), &(p.rcPaint));
3055 rcDest.left, rcDest.top,
3056 rcDest.right - rcDest.left,
3057 rcDest.bottom - rcDest.top,
3059 rcDest.left - fe->bitmapPosition.left,
3060 rcDest.top - fe->bitmapPosition.top,
3062 SelectObject(hdc2, prevbm);
3071 int r = GetKeyboardState(keystate);
3072 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
3073 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
3077 if (!(lParam & 0x01000000))
3078 key = MOD_NUM_KEYPAD | '4';
3080 key = shift | ctrl | CURSOR_LEFT;
3083 if (!(lParam & 0x01000000))
3084 key = MOD_NUM_KEYPAD | '6';
3086 key = shift | ctrl | CURSOR_RIGHT;
3089 if (!(lParam & 0x01000000))
3090 key = MOD_NUM_KEYPAD | '8';
3092 key = shift | ctrl | CURSOR_UP;
3095 if (!(lParam & 0x01000000))
3096 key = MOD_NUM_KEYPAD | '2';
3098 key = shift | ctrl | CURSOR_DOWN;
3101 * Diagonal keys on the numeric keypad.
3104 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
3107 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
3110 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
3113 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
3116 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
3119 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
3122 * Numeric keypad keys with Num Lock on.
3124 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
3125 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
3126 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
3127 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
3128 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
3129 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
3130 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
3131 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
3132 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
3133 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
3137 if (!midend_process_key(fe->me, 0, 0, key))
3142 m.message = WM_KEYDOWN;
3144 m.lParam = lParam & 0xdfff;
3145 TranslateMessage(&m);
3149 case WM_LBUTTONDOWN:
3150 case WM_RBUTTONDOWN:
3151 case WM_MBUTTONDOWN:
3156 * Shift-clicks count as middle-clicks, since otherwise
3157 * two-button Windows users won't have any kind of
3158 * middle click to use.
3160 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
3161 button = MIDDLE_BUTTON;
3162 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
3163 button = RIGHT_BUTTON;
3166 button = LEFT_BUTTON;
3168 if ((fe->game->flags & REQUIRE_RBUTTON) == 0)
3169 button = LEFT_BUTTON;
3174 shrgi.cbSize = sizeof(SHRGINFO);
3175 shrgi.hwndClient = hwnd;
3176 shrgi.ptDown.x = (signed short)LOWORD(lParam);
3177 shrgi.ptDown.y = (signed short)HIWORD(lParam);
3178 shrgi.dwFlags = SHRG_RETURNCMD;
3180 if (GN_CONTEXTMENU == SHRecognizeGesture(&shrgi))
3181 button = RIGHT_BUTTON;
3183 button = LEFT_BUTTON;
3187 if (!midend_process_key(fe->me,
3188 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3189 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3203 * Shift-clicks count as middle-clicks, since otherwise
3204 * two-button Windows users won't have any kind of
3205 * middle click to use.
3207 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
3208 button = MIDDLE_RELEASE;
3209 else if (message == WM_RBUTTONUP || is_alt_pressed())
3210 button = RIGHT_RELEASE;
3212 button = LEFT_RELEASE;
3214 if (!midend_process_key(fe->me,
3215 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3216 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3227 if (wParam & (MK_MBUTTON | MK_SHIFT))
3228 button = MIDDLE_DRAG;
3229 else if (wParam & MK_RBUTTON || is_alt_pressed())
3230 button = RIGHT_DRAG;
3234 if (!midend_process_key(fe->me,
3235 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3236 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3242 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
3247 DWORD now = GetTickCount();
3248 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
3249 midend_timer(fe->me, elapsed);
3250 fe->timer_last_tickcount = now;
3256 RECT *sr = (RECT *)lParam;
3257 int wx, wy, isedge = 0;
3259 if (wParam == WMSZ_TOP ||
3260 wParam == WMSZ_RIGHT ||
3261 wParam == WMSZ_BOTTOM ||
3262 wParam == WMSZ_LEFT) isedge = 1;
3263 adjust_game_size(fe, sr, isedge, &wx, &wy);
3265 /* Given the window size the puzzles constrain
3266 * us to, work out which edge we should be moving. */
3267 if (wParam == WMSZ_TOP ||
3268 wParam == WMSZ_TOPLEFT ||
3269 wParam == WMSZ_TOPRIGHT) {
3270 sr->top = sr->bottom - wy;
3272 sr->bottom = sr->top + wy;
3274 if (wParam == WMSZ_LEFT ||
3275 wParam == WMSZ_TOPLEFT ||
3276 wParam == WMSZ_BOTTOMLEFT) {
3277 sr->left = sr->right - wx;
3279 sr->right = sr->left + wx;
3287 return DefWindowProc(hwnd, message, wParam, lParam);
3291 static int FindPreviousInstance()
3293 /* Check if application is running. If it's running then focus on the window */
3294 HWND hOtherWnd = NULL;
3296 hOtherWnd = FindWindow (wGameName, wGameName);
3299 SetForegroundWindow (hOtherWnd);
3307 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
3315 MultiByteToWideChar (CP_ACP, 0, CLASSNAME, -1, wClassName, 256);
3316 if (FindPreviousInstance ())
3320 InitCommonControls();
3326 wndclass.lpfnWndProc = WndProc;
3327 wndclass.cbClsExtra = 0;
3328 wndclass.cbWndExtra = 0;
3329 wndclass.hInstance = inst;
3330 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
3332 if (!wndclass.hIcon) /* in case resource file is absent */
3333 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
3335 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
3336 wndclass.hbrBackground = NULL;
3337 wndclass.lpszMenuName = NULL;
3339 wndclass.lpszClassName = wClassName;
3341 wndclass.lpszClassName = CLASSNAME;
3344 RegisterClass(&wndclass);
3347 while (*cmdline && isspace((unsigned char)*cmdline))
3356 for (i = 0; i < gamecount; i++) {
3357 const char *p = gamelist[i]->name;
3359 while (*q && isspace((unsigned char)*q))
3362 if (isspace((unsigned char)*p)) {
3363 while (*q && isspace((unsigned char)*q))
3366 if (tolower((unsigned char)*p) !=
3367 tolower((unsigned char)*q))
3377 while (*cmdline && isspace((unsigned char)*cmdline))
3387 fe = frontend_new(inst);
3388 if (new_game(fe, gg, *cmdline ? cmdline : NULL, &error)) {
3390 sprintf(buf, "%.100s Error", gg->name);
3391 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
3396 while (GetMessage(&msg, NULL, 0, 0)) {
3397 DispatchMessage(&msg);
3400 DestroyWindow(fe->hwnd);
3405 /* vim: set shiftwidth=4 tabstop=8: */