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
48 #define IDM_KEYEMUL 0x0400
50 #define HELP_FILE_NAME "puzzles.hlp"
51 #define HELP_CNT_NAME "puzzles.cnt"
53 #define CHM_FILE_NAME "puzzles.chm"
54 #endif /* NO_HTMLHELP */
57 typedef HWND (CALLBACK *htmlhelp_t)(HWND, LPCSTR, UINT, DWORD);
58 static htmlhelp_t htmlhelp;
59 static HINSTANCE hh_dll;
60 #endif /* NO_HTMLHELP */
61 enum { NONE, HLP, CHM } help_type;
63 const char *help_topic;
64 int help_has_contents;
67 #define FILENAME_MAX (260)
71 #define HGDI_ERROR ((HANDLE)GDI_ERROR)
77 * Wrapper implementations of functions not supplied by the
81 #define SHGetSubMenu(hWndMB,ID_MENU) (HMENU)SendMessage((hWndMB), SHCMBM_GETSUBMENU, (WPARAM)0, (LPARAM)ID_MENU)
85 int MessageBox(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType)
90 MultiByteToWideChar (CP_ACP, 0, lpText, -1, wText, 2048);
91 MultiByteToWideChar (CP_ACP, 0, lpCaption, -1, wCaption, 2048);
93 return MessageBoxW (hWnd, wText, wCaption, uType);
96 BOOL SetDlgItemTextA(HWND hDlg, int nIDDlgItem, LPCSTR lpString)
100 MultiByteToWideChar (CP_ACP, 0, lpString, -1, wText, 256);
101 return SetDlgItemTextW(hDlg, nIDDlgItem, wText);
104 LPCSTR getenv(LPCSTR buf)
109 BOOL GetKeyboardState(PBYTE pb)
114 static TCHAR wGameName[256];
119 static FILE *debug_fp = NULL;
120 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
121 static int debug_got_console = 0;
123 void dputs(char *buf)
127 if (!debug_got_console) {
128 if (AllocConsole()) {
129 debug_got_console = 1;
130 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
134 debug_fp = fopen("debug.log", "w");
137 if (debug_hdl != INVALID_HANDLE_VALUE) {
138 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
140 fputs(buf, debug_fp);
142 OutputDebugString(buf);
145 void debug_printf(char *fmt, ...)
151 _vsnprintf(buf, 4095, fmt, ap);
158 #define WINFLAGS (WS_OVERLAPPEDWINDOW &~ \
159 (WS_MAXIMIZEBOX | WS_OVERLAPPED))
161 #define WINFLAGS (WS_CAPTION | WS_SYSMENU)
164 static void new_game_size(frontend *fe);
182 enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
186 HWND hwnd, statusbar, cfgbox;
188 HWND numpad; /* window handle for the numeric pad */
191 HBITMAP bitmap, prevbm;
192 RECT bitmapPosition; /* game bitmap position within game window */
198 HMENU gamemenu, typemenu;
200 DWORD timer_last_tickcount;
202 game_params **presets;
204 int nfonts, fontsize;
206 struct cfg_aux *cfgaux;
207 int cfg_which, dlg_done;
212 enum { DRAWING, PRINTING, NOTHING } drawstatus;
214 int printcount, printw, printh, printsolns, printcurr, printcolour;
216 int printoffsetx, printoffsety;
217 float printpixelscale;
224 static void update_type_menu_tick(frontend *fe);
225 static void update_copy_menu_greying(frontend *fe);
227 void fatal(char *fmt, ...)
233 vsprintf(buf, fmt, ap);
236 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
241 char *geterrstr(void)
244 DWORD dw = GetLastError();
248 FORMAT_MESSAGE_ALLOCATE_BUFFER |
249 FORMAT_MESSAGE_FROM_SYSTEM,
252 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
256 ret = dupstr(lpMsgBuf);
263 void get_random_seed(void **randseed, int *randseedsize)
265 SYSTEMTIME *st = snew(SYSTEMTIME);
269 *randseed = (void *)st;
270 *randseedsize = sizeof(SYSTEMTIME);
273 static void win_status_bar(void *handle, char *text)
278 frontend *fe = (frontend *)handle;
281 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 255);
282 SendMessage(fe->statusbar, SB_SETTEXT,
283 (WPARAM) 255 | SBT_NOBORDERS,
286 SetWindowText(fe->statusbar, text);
290 static blitter *win_blitter_new(void *handle, int w, int h)
292 blitter *bl = snew(blitter);
294 memset(bl, 0, sizeof(blitter));
302 static void win_blitter_free(void *handle, blitter *bl)
304 if (bl->bitmap) DeleteObject(bl->bitmap);
308 static void blitter_mkbitmap(frontend *fe, blitter *bl)
310 HDC hdc = GetDC(fe->hwnd);
311 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
312 ReleaseDC(fe->hwnd, hdc);
315 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
317 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
319 frontend *fe = (frontend *)handle;
320 HDC hdc_win, hdc_blit;
323 assert(fe->drawstatus == DRAWING);
325 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
327 bl->x = x; bl->y = y;
329 hdc_win = GetDC(fe->hwnd);
330 hdc_blit = CreateCompatibleDC(hdc_win);
331 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
333 prev_blit = SelectObject(hdc_blit, bl->bitmap);
334 if (prev_blit == NULL || prev_blit == HGDI_ERROR)
335 fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
337 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
338 fe->hdc, x, y, SRCCOPY))
339 fatal("BitBlt failed: 0x%x", GetLastError());
341 SelectObject(hdc_blit, prev_blit);
343 ReleaseDC(fe->hwnd, hdc_win);
346 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
348 frontend *fe = (frontend *)handle;
349 HDC hdc_win, hdc_blit;
352 assert(fe->drawstatus == DRAWING);
354 assert(bl->bitmap); /* we should always have saved before loading */
356 if (x == BLITTER_FROMSAVED) x = bl->x;
357 if (y == BLITTER_FROMSAVED) y = bl->y;
359 hdc_win = GetDC(fe->hwnd);
360 hdc_blit = CreateCompatibleDC(hdc_win);
362 prev_blit = SelectObject(hdc_blit, bl->bitmap);
364 BitBlt(fe->hdc, x, y, bl->w, bl->h,
365 hdc_blit, 0, 0, SRCCOPY);
367 SelectObject(hdc_blit, prev_blit);
369 ReleaseDC(fe->hwnd, hdc_win);
372 void frontend_default_colour(frontend *fe, float *output)
374 DWORD c = GetSysColor(COLOR_MENU); /* ick */
376 output[0] = (float)(GetRValue(c) / 255.0);
377 output[1] = (float)(GetGValue(c) / 255.0);
378 output[2] = (float)(GetBValue(c) / 255.0);
381 static POINT win_transform_point(frontend *fe, int x, int y)
385 assert(fe->drawstatus != NOTHING);
387 if (fe->drawstatus == PRINTING) {
388 ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
389 ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
398 static void win_text_colour(frontend *fe, int colour)
400 assert(fe->drawstatus != NOTHING);
402 if (fe->drawstatus == PRINTING) {
405 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
408 * Displaying text in hatched colours is not permitted.
412 SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
414 SetTextColor(fe->hdc, fe->colours[colour]);
418 static void win_set_brush(frontend *fe, int colour)
421 assert(fe->drawstatus != NOTHING);
423 if (fe->drawstatus == PRINTING) {
426 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
429 br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
433 * This is only ever required during printing, and the
434 * PocketPC port doesn't support printing.
436 fatal("CreateHatchBrush not supported");
438 br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
439 hatch == HATCH_SLASH ? HS_BDIAGONAL :
440 hatch == HATCH_HORIZ ? HS_HORIZONTAL :
441 hatch == HATCH_VERT ? HS_VERTICAL :
442 hatch == HATCH_PLUS ? HS_CROSS :
443 /* hatch == HATCH_X ? */ HS_DIAGCROSS,
448 br = fe->brushes[colour];
450 fe->oldbr = SelectObject(fe->hdc, br);
453 static void win_reset_brush(frontend *fe)
457 assert(fe->drawstatus != NOTHING);
459 br = SelectObject(fe->hdc, fe->oldbr);
460 if (fe->drawstatus == PRINTING)
464 static void win_set_pen(frontend *fe, int colour, int thin)
467 assert(fe->drawstatus != NOTHING);
469 if (fe->drawstatus == PRINTING) {
472 int width = thin ? 0 : fe->linewidth;
474 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
476 * Stroking in hatched colours is not permitted.
479 pen = CreatePen(PS_SOLID, width, RGB(r * 255, g * 255, b * 255));
481 pen = fe->pens[colour];
483 fe->oldpen = SelectObject(fe->hdc, pen);
486 static void win_reset_pen(frontend *fe)
490 assert(fe->drawstatus != NOTHING);
492 pen = SelectObject(fe->hdc, fe->oldpen);
493 if (fe->drawstatus == PRINTING)
497 static void win_clip(void *handle, int x, int y, int w, int h)
499 frontend *fe = (frontend *)handle;
502 if (fe->drawstatus == NOTHING)
505 p = win_transform_point(fe, x, y);
506 q = win_transform_point(fe, x+w, y+h);
507 IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
510 static void win_unclip(void *handle)
512 frontend *fe = (frontend *)handle;
514 if (fe->drawstatus == NOTHING)
517 SelectClipRgn(fe->hdc, NULL);
520 static void win_draw_text(void *handle, int x, int y, int fonttype,
521 int fontsize, int align, int colour, char *text)
523 frontend *fe = (frontend *)handle;
528 if (fe->drawstatus == NOTHING)
531 if (fe->drawstatus == PRINTING)
532 fontsize = (int)(fontsize * fe->printpixelscale);
534 xy = win_transform_point(fe, x, y);
537 * Find or create the font.
539 for (i = fe->fontstart; i < fe->nfonts; i++)
540 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
543 if (i == fe->nfonts) {
544 if (fe->fontsize <= fe->nfonts) {
545 fe->fontsize = fe->nfonts + 10;
546 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
551 fe->fonts[i].type = fonttype;
552 fe->fonts[i].size = fontsize;
554 memset (&lf, 0, sizeof(LOGFONT));
555 lf.lfHeight = -fontsize;
556 lf.lfWeight = (fe->drawstatus == PRINTING ? 0 : FW_BOLD);
557 lf.lfCharSet = DEFAULT_CHARSET;
558 lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
559 lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
560 lf.lfQuality = DEFAULT_QUALITY;
561 lf.lfPitchAndFamily = (fonttype == FONT_FIXED ?
562 FIXED_PITCH | FF_DONTCARE :
563 VARIABLE_PITCH | FF_SWISS);
565 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
568 fe->fonts[i].font = CreateFontIndirect(&lf);
572 * Position and draw the text.
580 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 256);
583 oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
584 if (GetTextMetrics(fe->hdc, &tm)) {
585 if (align & ALIGN_VCENTRE)
586 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
591 if (GetTextExtentPoint32(fe->hdc, text, strlen(text), &size))
593 if (GetTextExtentPoint32(fe->hdc, wText, wcslen(wText), &size))
596 if (align & ALIGN_HCENTRE)
598 else if (align & ALIGN_HRIGHT)
601 SetBkMode(fe->hdc, TRANSPARENT);
602 win_text_colour(fe, colour);
604 TextOut(fe->hdc, xy.x, xy.y, text, strlen(text));
606 ExtTextOut(fe->hdc, xy.x, xy.y, 0, NULL, wText, wcslen(wText), NULL);
608 SelectObject(fe->hdc, oldfont);
612 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
614 frontend *fe = (frontend *)handle;
617 if (fe->drawstatus == NOTHING)
620 if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
622 * Rectangle() appears to get uppity if asked to draw a 1x1
623 * rectangle, presumably on the grounds that that's beneath
624 * its dignity and you ought to be using SetPixel instead.
627 SetPixel(fe->hdc, x, y, fe->colours[colour]);
629 win_set_brush(fe, colour);
630 win_set_pen(fe, colour, TRUE);
631 p = win_transform_point(fe, x, y);
632 q = win_transform_point(fe, x+w, y+h);
633 Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
639 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
641 frontend *fe = (frontend *)handle;
644 if (fe->drawstatus == NOTHING)
647 win_set_pen(fe, colour, FALSE);
648 pp[0] = win_transform_point(fe, x1, y1);
649 pp[1] = win_transform_point(fe, x2, y2);
650 Polyline(fe->hdc, pp, 2);
651 if (fe->drawstatus == DRAWING)
652 SetPixel(fe->hdc, pp[1].x, pp[1].y, fe->colours[colour]);
656 static void win_draw_circle(void *handle, int cx, int cy, int radius,
657 int fillcolour, int outlinecolour)
659 frontend *fe = (frontend *)handle;
662 assert(outlinecolour >= 0);
664 if (fe->drawstatus == NOTHING)
668 win_set_brush(fe, fillcolour);
670 fe->oldbr = SelectObject(fe->hdc, GetStockObject(NULL_BRUSH));
672 win_set_pen(fe, outlinecolour, FALSE);
673 p = win_transform_point(fe, cx - radius, cy - radius);
674 q = win_transform_point(fe, cx + radius, cy + radius);
675 Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
680 static void win_draw_polygon(void *handle, int *coords, int npoints,
681 int fillcolour, int outlinecolour)
683 frontend *fe = (frontend *)handle;
687 if (fe->drawstatus == NOTHING)
690 pts = snewn(npoints+1, POINT);
692 for (i = 0; i <= npoints; i++) {
693 int j = (i < npoints ? i : 0);
694 pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
697 assert(outlinecolour >= 0);
699 if (fillcolour >= 0) {
700 win_set_brush(fe, fillcolour);
701 win_set_pen(fe, outlinecolour, FALSE);
702 Polygon(fe->hdc, pts, npoints);
706 win_set_pen(fe, outlinecolour, FALSE);
707 Polyline(fe->hdc, pts, npoints+1);
714 static void win_start_draw(void *handle)
716 frontend *fe = (frontend *)handle;
719 assert(fe->drawstatus == NOTHING);
721 hdc_win = GetDC(fe->hwnd);
722 fe->hdc = CreateCompatibleDC(hdc_win);
723 fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
724 ReleaseDC(fe->hwnd, hdc_win);
727 SetMapMode(fe->hdc, MM_TEXT);
729 fe->drawstatus = DRAWING;
732 static void win_draw_update(void *handle, int x, int y, int w, int h)
734 frontend *fe = (frontend *)handle;
737 if (fe->drawstatus != DRAWING)
745 OffsetRect(&r, fe->bitmapPosition.left, fe->bitmapPosition.top);
746 InvalidateRect(fe->hwnd, &r, FALSE);
749 static void win_end_draw(void *handle)
751 frontend *fe = (frontend *)handle;
752 assert(fe->drawstatus == DRAWING);
753 SelectObject(fe->hdc, fe->prevbm);
756 DeleteObject(fe->clip);
759 fe->drawstatus = NOTHING;
762 static void win_line_width(void *handle, float width)
764 frontend *fe = (frontend *)handle;
766 assert(fe->drawstatus != DRAWING);
767 if (fe->drawstatus == NOTHING)
770 fe->linewidth = (int)(width * fe->printpixelscale);
773 static void win_begin_doc(void *handle, int pages)
775 frontend *fe = (frontend *)handle;
777 assert(fe->drawstatus != DRAWING);
778 if (fe->drawstatus == NOTHING)
781 if (StartDoc(fe->hdc, &fe->di) <= 0) {
782 char *e = geterrstr();
783 MessageBox(fe->hwnd, e, "Error starting to print",
784 MB_ICONERROR | MB_OK);
786 fe->drawstatus = NOTHING;
790 * Push a marker on the font stack so that we won't use the
791 * same fonts for printing and drawing. (This is because
792 * drawing seems to look generally better in bold, but printing
793 * is better not in bold.)
795 fe->fontstart = fe->nfonts;
798 static void win_begin_page(void *handle, int number)
800 frontend *fe = (frontend *)handle;
802 assert(fe->drawstatus != DRAWING);
803 if (fe->drawstatus == NOTHING)
806 if (StartPage(fe->hdc) <= 0) {
807 char *e = geterrstr();
808 MessageBox(fe->hwnd, e, "Error starting a page",
809 MB_ICONERROR | MB_OK);
811 fe->drawstatus = NOTHING;
815 static void win_begin_puzzle(void *handle, float xm, float xc,
816 float ym, float yc, int pw, int ph, float wmm)
818 frontend *fe = (frontend *)handle;
819 int ppw, pph, pox, poy;
820 float mmpw, mmph, mmox, mmoy;
823 assert(fe->drawstatus != DRAWING);
824 if (fe->drawstatus == NOTHING)
827 ppw = GetDeviceCaps(fe->hdc, HORZRES);
828 pph = GetDeviceCaps(fe->hdc, VERTRES);
829 mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
830 mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
833 * Compute the puzzle's position on the logical page.
835 mmox = xm * mmpw + xc;
836 mmoy = ym * mmph + yc;
839 * Work out what that comes to in pixels.
841 pox = (int)(mmox * (float)ppw / mmpw);
842 poy = (int)(mmoy * (float)pph / mmph);
845 * And determine the scale.
847 * I need a scale such that the maximum puzzle-coordinate
848 * extent of the rectangle (pw * scale) is equal to the pixel
849 * equivalent of the puzzle's millimetre width (wmm * ppw /
852 scale = (wmm * ppw) / (mmpw * pw);
855 * Now store pox, poy and scale for use in the main drawing
858 fe->printoffsetx = pox;
859 fe->printoffsety = poy;
860 fe->printpixelscale = scale;
865 static void win_end_puzzle(void *handle)
867 /* Nothing needs to be done here. */
870 static void win_end_page(void *handle, int number)
872 frontend *fe = (frontend *)handle;
874 assert(fe->drawstatus != DRAWING);
876 if (fe->drawstatus == NOTHING)
879 if (EndPage(fe->hdc) <= 0) {
880 char *e = geterrstr();
881 MessageBox(fe->hwnd, e, "Error finishing a page",
882 MB_ICONERROR | MB_OK);
884 fe->drawstatus = NOTHING;
888 static void win_end_doc(void *handle)
890 frontend *fe = (frontend *)handle;
892 assert(fe->drawstatus != DRAWING);
895 * Free all the fonts created since we began printing.
897 while (fe->nfonts > fe->fontstart) {
899 DeleteObject(fe->fonts[fe->nfonts].font);
904 * The MSDN web site sample code doesn't bother to call EndDoc
905 * if an error occurs half way through printing. I expect doing
906 * so would cause the erroneous document to actually be
907 * printed, or something equally undesirable.
909 if (fe->drawstatus == NOTHING)
912 if (EndDoc(fe->hdc) <= 0) {
913 char *e = geterrstr();
914 MessageBox(fe->hwnd, e, "Error finishing printing",
915 MB_ICONERROR | MB_OK);
917 fe->drawstatus = NOTHING;
921 const struct drawing_api win_drawing = {
946 void print(frontend *fe)
952 midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
957 * Create our document structure and fill it up with puzzles.
959 doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
960 for (i = 0; i < fe->printcount; i++) {
961 if (i == 0 && fe->printcurr) {
962 err = midend_print_puzzle(fe->me, doc, fe->printsolns);
967 nme = midend_new(NULL, &thegame, NULL, NULL);
970 * Set the non-interactive mid-end to have the same
971 * parameters as the standard one.
973 params = midend_get_params(fe->me);
974 midend_set_params(nme, params);
975 thegame.free_params(params);
978 midend_new_game(nme);
979 err = midend_print_puzzle(nme, doc, fe->printsolns);
988 MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
989 MB_ICONERROR | MB_OK);
994 memset(&pd, 0, sizeof(pd));
995 pd.lStructSize = sizeof(pd);
996 pd.hwndOwner = fe->hwnd;
999 pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
1000 PD_NOPAGENUMS | PD_NOSELECTION;
1002 pd.nFromPage = pd.nToPage = 0xFFFF;
1003 pd.nMinPage = pd.nMaxPage = 1;
1005 if (!PrintDlg(&pd)) {
1011 * Now pd.hDC is a device context for the printer.
1015 * FIXME: IWBNI we put up an Abort box here.
1018 memset(&fe->di, 0, sizeof(fe->di));
1019 fe->di.cbSize = sizeof(fe->di);
1020 sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
1021 " Portable Puzzle Collection)", thegame.name);
1022 fe->di.lpszDocName = doctitle;
1023 fe->di.lpszOutput = NULL;
1024 fe->di.lpszDatatype = NULL;
1027 fe->drawstatus = PRINTING;
1030 fe->dr = drawing_new(&win_drawing, NULL, fe);
1031 document_print(doc, fe->dr);
1032 drawing_free(fe->dr);
1035 fe->drawstatus = NOTHING;
1042 void deactivate_timer(frontend *fe)
1045 return; /* for non-interactive midend */
1046 if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
1050 void activate_timer(frontend *fe)
1053 return; /* for non-interactive midend */
1055 fe->timer = SetTimer(fe->hwnd, 1, 20, NULL);
1056 fe->timer_last_tickcount = GetTickCount();
1060 void write_clip(HWND hwnd, char *data)
1068 * Windows expects CRLF in the clipboard, so we must convert
1069 * any \n that has come out of the puzzle backend.
1072 for (i = 0; data[i]; i++) {
1073 if (data[i] == '\n')
1077 data2 = snewn(len+1, char);
1079 for (i = 0; data[i]; i++) {
1080 if (data[i] == '\n')
1082 data2[j++] = data[i];
1087 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
1090 lock = GlobalLock(clipdata);
1093 memcpy(lock, data2, len);
1094 ((unsigned char *) lock)[len] = 0;
1095 GlobalUnlock(clipdata);
1097 if (OpenClipboard(hwnd)) {
1099 SetClipboardData(CF_TEXT, clipdata);
1102 GlobalFree(clipdata);
1108 * Set up Help and see if we can find a help file.
1110 static void init_help(void)
1113 char b[2048], *p, *q, *r;
1117 * Find the executable file path, so we can look alongside
1118 * it for help files. Trim the filename off the end.
1120 GetModuleFileName(NULL, b, sizeof(b) - 1);
1122 p = strrchr(b, '\\');
1123 if (p && p >= r) r = p+1;
1124 q = strrchr(b, ':');
1125 if (q && q >= r) r = q+1;
1129 * Try HTML Help first.
1131 strcpy(r, CHM_FILE_NAME);
1132 if ( (fp = fopen(b, "r")) != NULL) {
1136 * We have a .CHM. See if we can use it.
1138 hh_dll = LoadLibrary("hhctrl.ocx");
1140 htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
1142 FreeLibrary(hh_dll);
1145 help_path = dupstr(b);
1147 help_topic = thegame.htmlhelp_topic;
1151 #endif /* NO_HTMLHELP */
1154 * Now try old-style .HLP.
1156 strcpy(r, HELP_FILE_NAME);
1157 if ( (fp = fopen(b, "r")) != NULL) {
1160 help_path = dupstr(b);
1163 help_topic = thegame.winhelp_topic;
1166 * See if there's a .CNT file alongside it.
1168 strcpy(r, HELP_CNT_NAME);
1169 if ( (fp = fopen(b, "r")) != NULL) {
1171 help_has_contents = TRUE;
1173 help_has_contents = FALSE;
1178 help_type = NONE; /* didn't find any */
1187 static void start_help(frontend *fe, const char *topic)
1192 switch (help_type) {
1196 str = snewn(10+strlen(topic), char);
1197 sprintf(str, "JI(`',`%s')", topic);
1199 } else if (help_has_contents) {
1202 cmd = HELP_CONTENTS;
1204 WinHelp(fe->hwnd, help_path, cmd, (DWORD)str);
1205 fe->help_running = TRUE;
1212 str = snewn(20 + strlen(topic) + strlen(help_path), char);
1213 sprintf(str, "%s::/%s.html>main", help_path, topic);
1215 str = dupstr(help_path);
1217 htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
1218 fe->help_running = TRUE;
1220 #endif /* NO_HTMLHELP */
1222 assert(!"This shouldn't happen");
1230 * Stop Help on window cleanup.
1232 static void stop_help(frontend *fe)
1234 if (fe->help_running) {
1235 switch (help_type) {
1237 WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
1242 htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
1244 #endif /* NO_HTMLHELP */
1246 assert(!"This shouldn't happen");
1249 fe->help_running = FALSE;
1256 * Terminate Help on process exit.
1258 static void cleanup_help(void)
1260 /* Nothing to do currently.
1261 * (If we were running HTML Help single-threaded, this is where we'd
1262 * call HH_UNINITIALIZE.) */
1265 static int get_statusbar_height(frontend *fe)
1268 if (fe->statusbar) {
1270 GetWindowRect(fe->statusbar, &sr);
1271 sy = sr.bottom - sr.top;
1278 static void adjust_statusbar(frontend *fe, RECT *r)
1282 if (!fe->statusbar) return;
1284 sy = get_statusbar_height(fe);
1286 SetWindowPos(fe->statusbar, NULL, 0, r->bottom-r->top-sy, r->right-r->left,
1291 static void get_menu_size(HWND wh, RECT *r)
1293 HMENU bar = GetMenu(wh);
1297 SetRect(r, 0, 0, 0, 0);
1298 for (i = 0; i < GetMenuItemCount(bar); i++) {
1299 GetMenuItemRect(wh, bar, i, &rect);
1300 UnionRect(r, r, &rect);
1305 * Given a proposed new puzzle size (cx,cy), work out the actual
1306 * puzzle size that would be (px,py) and the window size including
1307 * furniture (wx,wy).
1310 static int check_window_resize(frontend *fe, int cx, int cy,
1312 int *wx, int *wy, int resize)
1315 int x, y, sy = get_statusbar_height(fe), changed = 0;
1317 /* disallow making window thinner than menu bar */
1318 x = max(cx, fe->xmin);
1319 y = max(cy - sy, fe->ymin);
1322 * See if we actually got the window size we wanted, and adjust
1323 * the puzzle size if not.
1325 midend_size(fe->me, &x, &y, resize);
1326 if (x != cx || y != cy) {
1328 * Resize the window, now we know what size we _really_
1334 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1335 *wx = r.right - r.left;
1336 *wy = r.bottom - r.top;
1347 * Given the current window size, make sure it's sane for the
1348 * current puzzle and resize if necessary.
1351 static void check_window_size(frontend *fe, int *px, int *py)
1356 GetClientRect(fe->hwnd, &r);
1357 cx = r.right - r.left;
1358 cy = r.bottom - r.top;
1360 if (check_window_resize(fe, cx, cy, px, py, &wx, &wy, FALSE)) {
1362 SetWindowPos(fe->hwnd, NULL, 0, 0, wx, wy,
1363 SWP_NOMOVE | SWP_NOZORDER);
1368 GetClientRect(fe->hwnd, &r);
1369 adjust_statusbar(fe, &r);
1372 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1376 if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1377 *x = sr.right - sr.left;
1378 *y = sr.bottom - sr.top;
1383 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1384 *x -= r.right - r.left - 100;
1385 *y -= r.bottom - r.top - 100;
1390 if (fe->statusbar != NULL) {
1391 GetWindowRect(fe->statusbar, &sr);
1392 *y -= sr.bottom - sr.top;
1397 /* Toolbar buttons on the numeric pad */
1398 static TBBUTTON tbNumpadButtons[] =
1400 {0, IDM_KEYEMUL + '1', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1401 {1, IDM_KEYEMUL + '2', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1402 {2, IDM_KEYEMUL + '3', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1403 {3, IDM_KEYEMUL + '4', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1404 {4, IDM_KEYEMUL + '5', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1405 {5, IDM_KEYEMUL + '6', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1406 {6, IDM_KEYEMUL + '7', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1407 {7, IDM_KEYEMUL + '8', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1408 {8, IDM_KEYEMUL + '9', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1409 {9, IDM_KEYEMUL + ' ', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1}
1413 static frontend *new_window(HINSTANCE inst, char *game_id, char **error)
1419 fe = snew(frontend);
1421 fe->me = midend_new(fe, &thegame, &win_drawing, fe);
1424 *error = midend_game_id(fe->me, game_id);
1426 midend_free(fe->me);
1437 fe->help_running = FALSE;
1439 fe->drawstatus = NOTHING;
1443 midend_new_game(fe->me);
1446 fe->nfonts = fe->fontsize = 0;
1452 colours = midend_colours(fe->me, &ncolours);
1454 fe->colours = snewn(ncolours, COLORREF);
1455 fe->brushes = snewn(ncolours, HBRUSH);
1456 fe->pens = snewn(ncolours, HPEN);
1458 for (i = 0; i < ncolours; i++) {
1459 fe->colours[i] = RGB(255 * colours[i*3+0],
1460 255 * colours[i*3+1],
1461 255 * colours[i*3+2]);
1462 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1463 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1468 if (midend_wants_statusbar(fe->me)) {
1469 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1470 WS_CHILD | WS_VISIBLE,
1471 0, 0, 0, 0, /* status bar does these */
1472 NULL, NULL, inst, NULL);
1474 fe->statusbar = NULL;
1476 get_max_puzzle_size(fe, &x, &y);
1477 midend_size(fe->me, &x, &y, FALSE);
1482 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1485 fe->hwnd = CreateWindowEx(0, wGameName, wGameName,
1487 CW_USEDEFAULT, CW_USEDEFAULT,
1488 CW_USEDEFAULT, CW_USEDEFAULT,
1489 NULL, NULL, inst, NULL);
1493 RECT rc, rcBar, rcTB, rcClient;
1495 memset (&mbi, 0, sizeof(SHMENUBARINFO));
1496 mbi.cbSize = sizeof(SHMENUBARINFO);
1497 mbi.hwndParent = fe->hwnd;
1498 mbi.nToolBarId = IDR_MENUBAR1;
1499 mbi.hInstRes = inst;
1501 SHCreateMenuBar(&mbi);
1503 GetWindowRect(fe->hwnd, &rc);
1504 GetWindowRect(mbi.hwndMB, &rcBar);
1505 rc.bottom -= rcBar.bottom - rcBar.top;
1506 MoveWindow(fe->hwnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, FALSE);
1508 if (thegame.flags & REQUIRE_NUMPAD)
1510 fe->numpad = CreateToolbarEx (fe->hwnd,
1511 WS_VISIBLE | WS_CHILD | CCS_NOPARENTALIGN | TBSTYLE_FLAT,
1512 0, 10, inst, IDR_PADTOOLBAR,
1513 tbNumpadButtons, sizeof (tbNumpadButtons) / sizeof (TBBUTTON),
1514 0, 0, 14, 15, sizeof (TBBUTTON));
1515 GetWindowRect(fe->numpad, &rcTB);
1516 GetClientRect(fe->hwnd, &rcClient);
1517 MoveWindow(fe->numpad,
1519 rcClient.bottom - (rcTB.bottom - rcTB.top) - 1,
1521 rcTB.bottom - rcTB.top,
1523 SendMessage(fe->numpad, TB_SETINDENT, (rcClient.right - (10 * 21)) / 2, 0);
1529 fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
1530 WS_OVERLAPPEDWINDOW &~
1532 CW_USEDEFAULT, CW_USEDEFAULT,
1533 r.right - r.left, r.bottom - r.top,
1534 NULL, NULL, inst, NULL);
1537 if (midend_wants_statusbar(fe->me)) {
1539 DestroyWindow(fe->statusbar);
1540 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1541 WS_CHILD | WS_VISIBLE,
1542 0, 0, 0, 0, /* status bar does these */
1543 fe->hwnd, NULL, inst, NULL);
1545 /* Flat status bar looks better on the Pocket PC */
1546 SendMessage(fe->statusbar, SB_SIMPLE, (WPARAM) TRUE, 0);
1547 SendMessage(fe->statusbar, SB_SETTEXT,
1548 (WPARAM) 255 | SBT_NOBORDERS,
1553 * Now resize the window to take account of the status bar.
1555 GetWindowRect(fe->statusbar, &sr);
1556 GetWindowRect(fe->hwnd, &r);
1558 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1559 r.bottom - r.top + sr.bottom - sr.top,
1560 SWP_NOMOVE | SWP_NOZORDER);
1563 fe->statusbar = NULL;
1568 HMENU bar = CreateMenu();
1569 HMENU menu = CreateMenu();
1572 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "&Game");
1574 HMENU menu = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_GAME);
1575 DeleteMenu(menu, 0, MF_BYPOSITION);
1577 fe->gamemenu = menu;
1578 AppendMenu(menu, MF_ENABLED, IDM_NEW, TEXT("&New"));
1579 AppendMenu(menu, MF_ENABLED, IDM_RESTART, TEXT("&Restart"));
1581 /* ...here I run out of sensible accelerator characters. */
1582 AppendMenu(menu, MF_ENABLED, IDM_DESC, TEXT("Speci&fic..."));
1583 AppendMenu(menu, MF_ENABLED, IDM_SEED, TEXT("Rando&m Seed..."));
1586 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1587 thegame.can_configure) {
1590 HMENU sub = CreateMenu();
1592 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "&Type");
1594 HMENU sub = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_TYPE);
1595 DeleteMenu(sub, 0, MF_BYPOSITION);
1597 fe->presets = snewn(fe->npresets, game_params *);
1599 for (i = 0; i < fe->npresets; i++) {
1605 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1608 * FIXME: we ought to go through and do something
1609 * with ampersands here.
1613 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1615 MultiByteToWideChar (CP_ACP, 0, name, -1, wName, 255);
1616 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, wName);
1619 if (thegame.can_configure) {
1620 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, TEXT("&Custom..."));
1625 fe->typemenu = INVALID_HANDLE_VALUE;
1627 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1629 AppendMenu(menu, MF_ENABLED, IDM_LOAD, TEXT("&Load..."));
1630 AppendMenu(menu, MF_ENABLED, IDM_SAVE, TEXT("&Save..."));
1631 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1632 if (thegame.can_print) {
1633 AppendMenu(menu, MF_ENABLED, IDM_PRINT, TEXT("&Print..."));
1634 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1637 AppendMenu(menu, MF_ENABLED, IDM_UNDO, TEXT("Undo"));
1638 AppendMenu(menu, MF_ENABLED, IDM_REDO, TEXT("Redo"));
1640 if (thegame.can_format_as_text_ever) {
1641 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1642 AppendMenu(menu, MF_ENABLED, IDM_COPY, TEXT("&Copy"));
1645 if (thegame.can_solve) {
1646 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1647 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, TEXT("Sol&ve"));
1649 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1651 AppendMenu(menu, MF_ENABLED, IDM_QUIT, TEXT("E&xit"));
1652 menu = CreateMenu();
1653 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, TEXT("&Help"));
1655 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, TEXT("&About"));
1657 if (help_type != NONE) {
1658 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1659 AppendMenu(menu, MF_ENABLED, IDM_HELPC, TEXT("&Contents"));
1662 assert(thegame.name);
1663 item = snewn(10+strlen(thegame.name), char); /*ick*/
1664 sprintf(item, "&Help on %s", thegame.name);
1665 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1669 SetMenu(fe->hwnd, bar);
1670 get_menu_size(fe->hwnd, &menusize);
1671 fe->xmin = (menusize.right - menusize.left) + 25;
1676 new_game_size(fe); /* initialises fe->bitmap */
1677 check_window_size(fe, &x, &y);
1679 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1681 ShowWindow(fe->hwnd, SW_SHOWNORMAL);
1682 SetForegroundWindow(fe->hwnd);
1684 update_type_menu_tick(fe);
1685 update_copy_menu_greying(fe);
1687 midend_redraw(fe->me);
1693 static HFONT dialog_title_font()
1695 static HFONT hf = NULL;
1701 memset (&lf, 0, sizeof(LOGFONT));
1702 lf.lfHeight = -11; /* - ((8 * GetDeviceCaps(hdc, LOGPIXELSY)) / 72) */
1703 lf.lfWeight = FW_BOLD;
1704 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
1706 return hf = CreateFontIndirect(&lf);
1709 static void make_dialog_full_screen(HWND hwnd)
1711 SHINITDLGINFO shidi;
1713 /* Make dialog full screen */
1714 shidi.dwMask = SHIDIM_FLAGS;
1715 shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIZEDLGFULLSCREEN |
1718 SHInitDialog(&shidi);
1722 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1723 WPARAM wParam, LPARAM lParam)
1725 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1733 make_dialog_full_screen(hwnd);
1735 sprintf(title, "About %.250s", thegame.name);
1736 SetDlgItemTextA(hwnd, IDC_ABOUT_CAPTION, title);
1738 SendDlgItemMessage(hwnd, IDC_ABOUT_CAPTION, WM_SETFONT,
1739 (WPARAM) dialog_title_font(), 0);
1741 SetDlgItemTextA(hwnd, IDC_ABOUT_GAME, thegame.name);
1742 SetDlgItemTextA(hwnd, IDC_ABOUT_VERSION, ver);
1748 if (LOWORD(wParam) == IDOK)
1769 * Wrappers on midend_{get,set}_config, which extend the CFG_*
1770 * enumeration to add CFG_PRINT.
1772 static config_item *frontend_get_config(frontend *fe, int which,
1775 if (which < CFG_FRONTEND_SPECIFIC) {
1776 return midend_get_config(fe->me, which, wintitle);
1777 } else if (which == CFG_PRINT) {
1781 *wintitle = snewn(40 + strlen(thegame.name), char);
1782 sprintf(*wintitle, "%s print setup", thegame.name);
1784 ret = snewn(8, config_item);
1788 ret[i].name = "Number of puzzles to print";
1789 ret[i].type = C_STRING;
1790 ret[i].sval = dupstr("1");
1794 ret[i].name = "Number of puzzles across the page";
1795 ret[i].type = C_STRING;
1796 ret[i].sval = dupstr("1");
1800 ret[i].name = "Number of puzzles down the page";
1801 ret[i].type = C_STRING;
1802 ret[i].sval = dupstr("1");
1806 ret[i].name = "Percentage of standard size";
1807 ret[i].type = C_STRING;
1808 ret[i].sval = dupstr("100.0");
1812 ret[i].name = "Include currently shown puzzle";
1813 ret[i].type = C_BOOLEAN;
1818 ret[i].name = "Print solutions";
1819 ret[i].type = C_BOOLEAN;
1821 ret[i].ival = FALSE;
1824 if (thegame.can_print_in_colour) {
1825 ret[i].name = "Print in colour";
1826 ret[i].type = C_BOOLEAN;
1828 ret[i].ival = FALSE;
1833 ret[i].type = C_END;
1840 assert(!"We should never get here");
1845 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
1847 if (which < CFG_FRONTEND_SPECIFIC) {
1848 return midend_set_config(fe->me, which, cfg);
1849 } else if (which == CFG_PRINT) {
1850 if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
1851 return "Number of puzzles to print should be at least one";
1852 if ((fe->printw = atoi(cfg[1].sval)) <= 0)
1853 return "Number of puzzles across the page should be at least one";
1854 if ((fe->printh = atoi(cfg[2].sval)) <= 0)
1855 return "Number of puzzles down the page should be at least one";
1856 if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
1857 return "Print size should be positive";
1858 fe->printcurr = cfg[4].ival;
1859 fe->printsolns = cfg[5].ival;
1860 fe->printcolour = thegame.can_print_in_colour && cfg[6].ival;
1863 assert(!"We should never get here");
1864 return "Internal error";
1869 /* Separate version of mkctrl function for the Pocket PC. */
1870 /* Control coordinates should be specified in dialog units. */
1871 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
1872 LPCTSTR wclass, int wstyle,
1873 int exstyle, const char *wtext, int wid)
1878 /* Convert dialog units into pixels */
1879 rc.left = x1; rc.right = x2;
1880 rc.top = y1; rc.bottom = y2;
1881 MapDialogRect(fe->cfgbox, &rc);
1883 MultiByteToWideChar (CP_ACP, 0, wtext, -1, wwtext, 256);
1885 return CreateWindowEx(exstyle, wclass, wwtext,
1886 wstyle | WS_CHILD | WS_VISIBLE,
1888 rc.right - rc.left, rc.bottom - rc.top,
1889 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
1892 static void create_config_controls(frontend * fe)
1895 int col1l, col1r, col2l, col2r, y;
1900 /* Control placement done in dialog units */
1901 col1l = 4; col1r = 96; /* Label column */
1902 col2l = 100; col2r = 154; /* Input column (edit boxes and combo boxes) */
1905 * Count the controls so we can allocate cfgaux.
1907 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
1909 fe->cfgaux = snewn(nctrls, struct cfg_aux);
1912 y = 22; /* Leave some room for the dialog title */
1913 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1917 * Edit box with a label beside it.
1919 mkctrl(fe, col1l, col1r, y + 1, y + 11,
1920 TEXT("Static"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
1921 mkctrl(fe, col2l, col2r, y, y + 12,
1922 TEXT("EDIT"), WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
1923 0, "", (j->ctlid = id++));
1924 SetDlgItemTextA(fe->cfgbox, j->ctlid, i->sval);
1931 mkctrl(fe, col1l, col2r, y + 1, y + 11, TEXT("BUTTON"),
1932 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
1933 0, i->name, (j->ctlid = id++));
1934 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
1939 * Drop-down list with a label beside it.
1941 mkctrl(fe, col1l, col1r, y + 1, y + 11,
1942 TEXT("STATIC"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
1943 ctl = mkctrl(fe, col2l, col2r, y, y + 48,
1944 TEXT("COMBOBOX"), WS_BORDER | WS_TABSTOP |
1945 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
1946 0, "", (j->ctlid = id++));
1948 char c, *p, *q, *str;
1954 while (*q && *q != c) q++;
1955 str = snewn(q-p+1, char);
1956 strncpy(str, p, q-p);
1960 MultiByteToWideChar (CP_ACP, 0, str, -1, ws, 50);
1961 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)ws);
1969 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
1979 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
1980 WPARAM wParam, LPARAM lParam)
1982 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1992 fe = (frontend *) lParam;
1993 SetWindowLong(hwnd, GWL_USERDATA, lParam);
1996 fe->cfg = frontend_get_config(fe, fe->cfg_which, &title);
1998 make_dialog_full_screen(hwnd);
2000 SetDlgItemTextA(hwnd, IDC_CONFIG_CAPTION, title);
2001 SendDlgItemMessage(hwnd, IDC_CONFIG_CAPTION, WM_SETFONT,
2002 (WPARAM) dialog_title_font(), 0);
2004 create_config_controls(fe);
2011 * OK and Cancel are special cases.
2013 if ((LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
2014 if (LOWORD(wParam) == IDOK) {
2015 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
2018 MessageBox(hwnd, err, "Validation error",
2019 MB_ICONERROR | MB_OK);
2038 * First find the control whose id this is.
2040 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2041 if (j->ctlid == LOWORD(wParam))
2044 if (i->type == C_END)
2045 return 0; /* not our problem */
2047 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
2050 TCHAR wBuffer[4096];
2051 GetDlgItemText(fe->cfgbox, j->ctlid, wBuffer, 4096);
2052 WideCharToMultiByte(CP_ACP, 0, wBuffer, -1, buffer, 4096, NULL, NULL);
2054 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
2056 buffer[lenof(buffer)-1] = '\0';
2058 i->sval = dupstr(buffer);
2059 } else if (i->type == C_BOOLEAN &&
2060 (HIWORD(wParam) == BN_CLICKED ||
2061 HIWORD(wParam) == BN_DBLCLK)) {
2062 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
2063 } else if (i->type == C_CHOICES &&
2064 HIWORD(wParam) == CBN_SELCHANGE) {
2065 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
2066 CB_GETCURSEL, 0, 0);
2080 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2081 char *wclass, int wstyle,
2082 int exstyle, const char *wtext, int wid)
2085 ret = CreateWindowEx(exstyle, wclass, wtext,
2086 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
2087 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2088 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
2093 static void about(frontend *fe)
2096 DialogBox(fe->inst, MAKEINTRESOURCE(IDD_ABOUT), fe->hwnd, AboutDlgProc);
2106 int winwidth, winheight, y;
2107 int height, width, maxwid;
2108 const char *strings[16];
2113 sprintf(titlebuf, "About %.250s", thegame.name);
2115 strings[nstrings++] = thegame.name;
2116 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
2117 strings[nstrings++] = ver;
2119 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2120 wc.lpfnWndProc = DefDlgProc;
2122 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2123 wc.hInstance = fe->inst;
2125 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2126 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2127 wc.lpszMenuName = NULL;
2128 wc.lpszClassName = "GameAboutBox";
2131 hdc = GetDC(fe->hwnd);
2132 SetMapMode(hdc, MM_TEXT);
2134 fe->dlg_done = FALSE;
2136 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2138 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2139 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2144 oldfont = SelectObject(hdc, fe->cfgfont);
2145 if (GetTextMetrics(hdc, &tm)) {
2146 height = tm.tmAscent + tm.tmDescent;
2147 width = tm.tmAveCharWidth;
2149 height = width = 30;
2153 * Figure out the layout of the About box by measuring the
2154 * length of each piece of text.
2157 winheight = height/2;
2159 for (i = 0; i < nstrings; i++) {
2160 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
2161 lengths[i] = size.cx;
2163 lengths[i] = 0; /* *shrug* */
2164 if (maxwid < lengths[i])
2165 maxwid = lengths[i];
2166 winheight += height * 3 / 2 + (height / 2);
2169 winheight += height + height * 7 / 4; /* OK button */
2170 winwidth = maxwid + 4*width;
2172 SelectObject(hdc, oldfont);
2173 ReleaseDC(fe->hwnd, hdc);
2176 * Create the dialog, now that we know its size.
2183 r.bottom = winheight;
2185 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2186 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2187 WS_CAPTION | WS_SYSMENU*/) &~
2188 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2192 * Centre the dialog on its parent window.
2196 GetWindowRect(fe->hwnd, &r2);
2197 r.left = (r2.left + r2.right - r.right) / 2;
2198 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2202 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
2203 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2204 WS_CAPTION | WS_SYSMENU,
2206 r.right-r.left, r.bottom-r.top,
2207 fe->hwnd, NULL, fe->inst, NULL);
2210 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2212 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2213 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
2217 for (i = 0; i < nstrings; i++) {
2218 int border = width*2 + (maxwid - lengths[i]) / 2;
2219 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
2220 "Static", 0, 0, strings[i], id++);
2223 assert(y < winheight);
2227 y += height/2; /* extra space before OK */
2228 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
2229 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2232 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2234 EnableWindow(fe->hwnd, FALSE);
2235 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2236 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2237 if (!IsDialogMessage(fe->cfgbox, &msg))
2238 DispatchMessage(&msg);
2242 EnableWindow(fe->hwnd, TRUE);
2243 SetForegroundWindow(fe->hwnd);
2244 DestroyWindow(fe->cfgbox);
2245 DeleteObject(fe->cfgfont);
2249 static int get_config(frontend *fe, int which)
2252 fe->cfg_which = which;
2254 return DialogBoxParam(fe->inst,
2255 MAKEINTRESOURCE(IDD_CONFIG),
2256 fe->hwnd, ConfigDlgProc,
2270 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
2271 int height, width, maxlabel, maxcheckbox;
2273 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2274 wc.lpfnWndProc = DefDlgProc;
2276 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2277 wc.hInstance = fe->inst;
2279 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2280 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2281 wc.lpszMenuName = NULL;
2282 wc.lpszClassName = "GameConfigBox";
2285 hdc = GetDC(fe->hwnd);
2286 SetMapMode(hdc, MM_TEXT);
2288 fe->dlg_done = FALSE;
2290 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2292 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2293 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2298 oldfont = SelectObject(hdc, fe->cfgfont);
2299 if (GetTextMetrics(hdc, &tm)) {
2300 height = tm.tmAscent + tm.tmDescent;
2301 width = tm.tmAveCharWidth;
2303 height = width = 30;
2306 fe->cfg = frontend_get_config(fe, which, &title);
2307 fe->cfg_which = which;
2310 * Figure out the layout of the config box by measuring the
2311 * length of each piece of text.
2313 maxlabel = maxcheckbox = 0;
2314 winheight = height/2;
2316 for (i = fe->cfg; i->type != C_END; i++) {
2321 * Both these control types have a label filling only
2322 * the left-hand column of the box.
2324 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2327 winheight += height * 3 / 2 + (height / 2);
2332 * Checkboxes take up the whole of the box width.
2334 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2335 maxcheckbox < size.cx)
2336 maxcheckbox = size.cx;
2337 winheight += height + (height / 2);
2342 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
2345 col1r = col1l + maxlabel;
2346 col2l = col1r + 2*width;
2347 col2r = col2l + 30*width;
2348 if (col2r < col1l+2*height+maxcheckbox)
2349 col2r = col1l+2*height+maxcheckbox;
2350 winwidth = col2r + 2*width;
2352 SelectObject(hdc, oldfont);
2353 ReleaseDC(fe->hwnd, hdc);
2356 * Create the dialog, now that we know its size.
2363 r.bottom = winheight;
2365 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2366 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2367 WS_CAPTION | WS_SYSMENU*/) &~
2368 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2372 * Centre the dialog on its parent window.
2376 GetWindowRect(fe->hwnd, &r2);
2377 r.left = (r2.left + r2.right - r.right) / 2;
2378 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2382 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
2383 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2384 WS_CAPTION | WS_SYSMENU,
2386 r.right-r.left, r.bottom-r.top,
2387 fe->hwnd, NULL, fe->inst, NULL);
2391 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2393 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2394 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
2397 * Count the controls so we can allocate cfgaux.
2399 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2401 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2405 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2409 * Edit box with a label beside it.
2411 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2412 "Static", 0, 0, i->name, id++);
2413 ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
2414 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
2415 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2416 SetWindowText(ctl, i->sval);
2424 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
2425 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2426 0, i->name, (j->ctlid = id++));
2427 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2433 * Drop-down list with a label beside it.
2435 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2436 "STATIC", 0, 0, i->name, id++);
2437 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
2438 "COMBOBOX", WS_TABSTOP |
2439 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2440 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2442 char c, *p, *q, *str;
2444 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
2449 while (*q && *q != c) q++;
2450 str = snewn(q-p+1, char);
2451 strncpy(str, p, q-p);
2453 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
2460 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2466 assert(y < winheight);
2470 y += height/2; /* extra space before OK and Cancel */
2471 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
2472 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2474 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
2475 BS_PUSHBUTTON | WS_TABSTOP, 0, "Cancel", IDCANCEL);
2477 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2479 EnableWindow(fe->hwnd, FALSE);
2480 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2481 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2482 if (!IsDialogMessage(fe->cfgbox, &msg))
2483 DispatchMessage(&msg);
2487 EnableWindow(fe->hwnd, TRUE);
2488 SetForegroundWindow(fe->hwnd);
2489 DestroyWindow(fe->cfgbox);
2490 DeleteObject(fe->cfgfont);
2495 return (fe->dlg_done == 2);
2500 static void calculate_bitmap_position(frontend *fe, int x, int y)
2502 /* Pocket PC - center the game in the full screen window */
2506 GetClientRect(fe->hwnd, &rcClient);
2507 fe->bitmapPosition.left = (rcClient.right - x) / 2;
2508 yMargin = rcClient.bottom - y;
2510 if (fe->numpad != NULL) {
2512 GetWindowRect(fe->numpad, &rcPad);
2513 yMargin -= rcPad.bottom - rcPad.top;
2516 if (fe->statusbar != NULL) {
2518 GetWindowRect(fe->statusbar, &rcStatus);
2519 yMargin -= rcStatus.bottom - rcStatus.top;
2522 fe->bitmapPosition.top = yMargin / 2;
2524 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2525 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2528 static void calculate_bitmap_position(frontend *fe, int x, int y)
2530 /* Plain Windows - position the game in the upper-left corner */
2531 fe->bitmapPosition.left = 0;
2532 fe->bitmapPosition.top = 0;
2533 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2534 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2538 static void new_bitmap(frontend *fe, int x, int y)
2542 if (fe->bitmap) DeleteObject(fe->bitmap);
2544 hdc = GetDC(fe->hwnd);
2545 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2546 calculate_bitmap_position(fe, x, y);
2547 ReleaseDC(fe->hwnd, hdc);
2550 static void new_game_size(frontend *fe)
2555 get_max_puzzle_size(fe, &x, &y);
2556 midend_size(fe->me, &x, &y, FALSE);
2557 fe->ymin = (fe->xmin * y) / x;
2562 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2564 if (fe->statusbar != NULL) {
2565 GetWindowRect(fe->statusbar, &sr);
2567 sr.left = sr.right = sr.top = sr.bottom = 0;
2570 SetWindowPos(fe->hwnd, NULL, 0, 0,
2572 r.bottom - r.top + sr.bottom - sr.top,
2573 SWP_NOMOVE | SWP_NOZORDER);
2576 check_window_size(fe, &x, &y);
2579 if (fe->statusbar != NULL)
2580 SetWindowPos(fe->statusbar, NULL, 0, y, x,
2581 sr.bottom - sr.top, SWP_NOZORDER);
2584 new_bitmap(fe, x, y);
2587 InvalidateRect(fe->hwnd, NULL, TRUE);
2589 midend_redraw(fe->me);
2593 * Given a proposed new window rect, work out the resulting
2594 * difference in client size (from current), and use to try
2595 * and resize the puzzle, returning (wx,wy) as the actual
2599 static void adjust_game_size(frontend *fe, RECT *proposed, int isedge,
2600 int *wx_r, int *wy_r)
2603 int nx, ny, xdiff, ydiff, wx, wy;
2605 /* Work out the current window sizing, and thus the
2606 * difference in size we're asking for. */
2607 GetClientRect(fe->hwnd, &cr);
2609 AdjustWindowRectEx(&wr, WINFLAGS, TRUE, 0);
2611 xdiff = (proposed->right - proposed->left) - (wr.right - wr.left);
2612 ydiff = (proposed->bottom - proposed->top) - (wr.bottom - wr.top);
2615 /* These next four lines work around the fact that midend_size
2616 * is happy to shrink _but not grow_ if you change one dimension
2617 * but not the other. */
2618 if (xdiff > 0 && ydiff == 0)
2619 ydiff = (xdiff * (wr.right - wr.left)) / (wr.bottom - wr.top);
2620 if (xdiff == 0 && ydiff > 0)
2621 xdiff = (ydiff * (wr.bottom - wr.top)) / (wr.right - wr.left);
2624 if (check_window_resize(fe,
2625 (cr.right - cr.left) + xdiff,
2626 (cr.bottom - cr.top) + ydiff,
2627 &nx, &ny, &wx, &wy, TRUE)) {
2628 new_bitmap(fe, nx, ny);
2629 midend_force_redraw(fe->me);
2631 /* reset size to current window size */
2632 wx = wr.right - wr.left;
2633 wy = wr.bottom - wr.top;
2635 /* Re-fetch rectangle; size limits mean we might not have
2636 * taken it quite to the mouse drag positions. */
2637 GetClientRect(fe->hwnd, &cr);
2638 adjust_statusbar(fe, &cr);
2640 *wx_r = wx; *wy_r = wy;
2643 static void update_type_menu_tick(frontend *fe)
2647 if (fe->typemenu == INVALID_HANDLE_VALUE)
2650 total = GetMenuItemCount(fe->typemenu);
2651 n = midend_which_preset(fe->me);
2653 n = total - 1; /* "Custom" item */
2655 for (i = 0; i < total; i++) {
2656 int flag = (i == n ? MF_CHECKED : MF_UNCHECKED);
2657 CheckMenuItem(fe->typemenu, i, MF_BYPOSITION | flag);
2660 DrawMenuBar(fe->hwnd);
2663 static void update_copy_menu_greying(frontend *fe)
2665 UINT enable = (midend_can_format_as_text_now(fe->me) ?
2666 MF_ENABLED : MF_GRAYED);
2667 EnableMenuItem(fe->gamemenu, IDM_COPY, MF_BYCOMMAND | enable);
2670 static void new_game_type(frontend *fe)
2672 midend_new_game(fe->me);
2674 update_type_menu_tick(fe);
2675 update_copy_menu_greying(fe);
2678 static int is_alt_pressed(void)
2681 int r = GetKeyboardState(keystate);
2684 if (keystate[VK_MENU] & 0x80)
2686 if (keystate[VK_RMENU] & 0x80)
2691 static void savefile_write(void *wctx, void *buf, int len)
2693 FILE *fp = (FILE *)wctx;
2694 fwrite(buf, 1, len, fp);
2697 static int savefile_read(void *wctx, void *buf, int len)
2699 FILE *fp = (FILE *)wctx;
2702 ret = fread(buf, 1, len, fp);
2703 return (ret == len);
2706 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2707 WPARAM wParam, LPARAM lParam)
2709 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2714 DestroyWindow(hwnd);
2718 /* Numeric pad sends WM_COMMAND messages */
2719 if ((wParam >= IDM_KEYEMUL) && (wParam < IDM_KEYEMUL + 256))
2721 midend_process_key(fe->me, 0, 0, wParam - IDM_KEYEMUL);
2724 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
2727 if (!midend_process_key(fe->me, 0, 0, 'n'))
2731 midend_restart_game(fe->me);
2734 if (!midend_process_key(fe->me, 0, 0, 'u'))
2738 if (!midend_process_key(fe->me, 0, 0, '\x12'))
2743 char *text = midend_text_format(fe->me);
2745 write_clip(hwnd, text);
2747 MessageBeep(MB_ICONWARNING);
2753 char *msg = midend_solve(fe->me);
2755 MessageBox(hwnd, msg, "Unable to solve",
2756 MB_ICONERROR | MB_OK);
2760 if (!midend_process_key(fe->me, 0, 0, 'q'))
2764 if (get_config(fe, CFG_SETTINGS))
2768 if (get_config(fe, CFG_SEED))
2772 if (get_config(fe, CFG_DESC))
2776 if (get_config(fe, CFG_PRINT))
2786 char filename[FILENAME_MAX];
2789 memset(&of, 0, sizeof(of));
2790 of.hwndOwner = hwnd;
2791 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
2792 of.lpstrCustomFilter = NULL;
2793 of.nFilterIndex = 1;
2794 of.lpstrFile = filename;
2796 of.nMaxFile = lenof(filename);
2797 of.lpstrFileTitle = NULL;
2798 of.lpstrTitle = (cmd == IDM_SAVE ?
2799 "Enter name of game file to save" :
2800 "Enter name of saved game file to load");
2802 #ifdef OPENFILENAME_SIZE_VERSION_400
2803 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2805 of.lStructSize = sizeof(of);
2807 of.lpstrInitialDir = NULL;
2809 if (cmd == IDM_SAVE)
2810 ret = GetSaveFileName(&of);
2812 ret = GetOpenFileName(&of);
2815 if (cmd == IDM_SAVE) {
2818 if ((fp = fopen(filename, "r")) != NULL) {
2819 char buf[256 + FILENAME_MAX];
2823 sprintf(buf, "Are you sure you want to overwrite"
2824 " the file \"%.*s\"?",
2825 FILENAME_MAX, filename);
2826 if (MessageBox(hwnd, buf, "Question",
2827 MB_YESNO | MB_ICONQUESTION)
2832 fp = fopen(filename, "w");
2835 MessageBox(hwnd, "Unable to open save file",
2836 "Error", MB_ICONERROR | MB_OK);
2840 midend_serialise(fe->me, savefile_write, fp);
2844 FILE *fp = fopen(filename, "r");
2848 MessageBox(hwnd, "Unable to open saved game file",
2849 "Error", MB_ICONERROR | MB_OK);
2853 err = midend_deserialise(fe->me, savefile_read, fp);
2858 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
2870 start_help(fe, NULL);
2873 start_help(fe, help_topic);
2878 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
2880 if (p >= 0 && p < fe->npresets) {
2881 midend_set_params(fe->me, fe->presets[p]);
2901 hdc = BeginPaint(hwnd, &p);
2902 hdc2 = CreateCompatibleDC(hdc);
2903 prevbm = SelectObject(hdc2, fe->bitmap);
2905 FillRect(hdc, &(p.rcPaint), (HBRUSH) GetStockObject(WHITE_BRUSH));
2907 IntersectRect(&rcDest, &(fe->bitmapPosition), &(p.rcPaint));
2909 rcDest.left, rcDest.top,
2910 rcDest.right - rcDest.left,
2911 rcDest.bottom - rcDest.top,
2913 rcDest.left - fe->bitmapPosition.left,
2914 rcDest.top - fe->bitmapPosition.top,
2916 SelectObject(hdc2, prevbm);
2925 int r = GetKeyboardState(keystate);
2926 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
2927 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
2931 if (!(lParam & 0x01000000))
2932 key = MOD_NUM_KEYPAD | '4';
2934 key = shift | ctrl | CURSOR_LEFT;
2937 if (!(lParam & 0x01000000))
2938 key = MOD_NUM_KEYPAD | '6';
2940 key = shift | ctrl | CURSOR_RIGHT;
2943 if (!(lParam & 0x01000000))
2944 key = MOD_NUM_KEYPAD | '8';
2946 key = shift | ctrl | CURSOR_UP;
2949 if (!(lParam & 0x01000000))
2950 key = MOD_NUM_KEYPAD | '2';
2952 key = shift | ctrl | CURSOR_DOWN;
2955 * Diagonal keys on the numeric keypad.
2958 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
2961 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
2964 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
2967 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
2970 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
2973 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
2976 * Numeric keypad keys with Num Lock on.
2978 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
2979 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
2980 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
2981 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
2982 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
2983 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
2984 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
2985 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
2986 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
2987 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
2991 if (!midend_process_key(fe->me, 0, 0, key))
2996 m.message = WM_KEYDOWN;
2998 m.lParam = lParam & 0xdfff;
2999 TranslateMessage(&m);
3003 case WM_LBUTTONDOWN:
3004 case WM_RBUTTONDOWN:
3005 case WM_MBUTTONDOWN:
3010 * Shift-clicks count as middle-clicks, since otherwise
3011 * two-button Windows users won't have any kind of
3012 * middle click to use.
3014 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
3015 button = MIDDLE_BUTTON;
3016 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
3017 button = RIGHT_BUTTON;
3020 button = LEFT_BUTTON;
3022 if ((thegame.flags & REQUIRE_RBUTTON) == 0)
3023 button = LEFT_BUTTON;
3028 shrgi.cbSize = sizeof(SHRGINFO);
3029 shrgi.hwndClient = hwnd;
3030 shrgi.ptDown.x = (signed short)LOWORD(lParam);
3031 shrgi.ptDown.y = (signed short)HIWORD(lParam);
3032 shrgi.dwFlags = SHRG_RETURNCMD;
3034 if (GN_CONTEXTMENU == SHRecognizeGesture(&shrgi))
3035 button = RIGHT_BUTTON;
3037 button = LEFT_BUTTON;
3041 if (!midend_process_key(fe->me,
3042 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3043 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3057 * Shift-clicks count as middle-clicks, since otherwise
3058 * two-button Windows users won't have any kind of
3059 * middle click to use.
3061 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
3062 button = MIDDLE_RELEASE;
3063 else if (message == WM_RBUTTONUP || is_alt_pressed())
3064 button = RIGHT_RELEASE;
3066 button = LEFT_RELEASE;
3068 if (!midend_process_key(fe->me,
3069 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3070 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3081 if (wParam & (MK_MBUTTON | MK_SHIFT))
3082 button = MIDDLE_DRAG;
3083 else if (wParam & MK_RBUTTON || is_alt_pressed())
3084 button = RIGHT_DRAG;
3088 if (!midend_process_key(fe->me,
3089 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3090 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3096 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
3101 DWORD now = GetTickCount();
3102 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
3103 midend_timer(fe->me, elapsed);
3104 fe->timer_last_tickcount = now;
3110 RECT *sr = (RECT *)lParam;
3111 int wx, wy, isedge = 0;
3113 if (wParam == WMSZ_TOP ||
3114 wParam == WMSZ_RIGHT ||
3115 wParam == WMSZ_BOTTOM ||
3116 wParam == WMSZ_LEFT) isedge = 1;
3117 adjust_game_size(fe, sr, isedge, &wx, &wy);
3119 /* Given the window size the puzzles constrain
3120 * us to, work out which edge we should be moving. */
3121 if (wParam == WMSZ_TOP ||
3122 wParam == WMSZ_TOPLEFT ||
3123 wParam == WMSZ_TOPRIGHT) {
3124 sr->top = sr->bottom - wy;
3126 sr->bottom = sr->top + wy;
3128 if (wParam == WMSZ_LEFT ||
3129 wParam == WMSZ_TOPLEFT ||
3130 wParam == WMSZ_BOTTOMLEFT) {
3131 sr->left = sr->right - wx;
3133 sr->right = sr->left + wx;
3141 return DefWindowProc(hwnd, message, wParam, lParam);
3145 static int FindPreviousInstance()
3147 /* Check if application is running. If it's running then focus on the window */
3148 HWND hOtherWnd = NULL;
3150 hOtherWnd = FindWindow (wGameName, wGameName);
3153 SetForegroundWindow (hOtherWnd);
3161 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
3167 MultiByteToWideChar (CP_ACP, 0, thegame.name, -1, wGameName, 256);
3168 if (FindPreviousInstance ())
3172 InitCommonControls();
3178 wndclass.lpfnWndProc = WndProc;
3179 wndclass.cbClsExtra = 0;
3180 wndclass.cbWndExtra = 0;
3181 wndclass.hInstance = inst;
3182 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
3184 if (!wndclass.hIcon) /* in case resource file is absent */
3185 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
3187 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
3188 wndclass.hbrBackground = NULL;
3189 wndclass.lpszMenuName = NULL;
3191 wndclass.lpszClassName = wGameName;
3193 wndclass.lpszClassName = thegame.name;
3196 RegisterClass(&wndclass);
3199 while (*cmdline && isspace((unsigned char)*cmdline))
3204 if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
3206 sprintf(buf, "%.100s Error", thegame.name);
3207 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
3211 while (GetMessage(&msg, NULL, 0, 0)) {
3212 DispatchMessage(&msg);