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 */
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);
226 void fatal(char *fmt, ...)
232 vsprintf(buf, fmt, ap);
235 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
240 char *geterrstr(void)
243 DWORD dw = GetLastError();
247 FORMAT_MESSAGE_ALLOCATE_BUFFER |
248 FORMAT_MESSAGE_FROM_SYSTEM,
251 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
255 ret = dupstr(lpMsgBuf);
262 void get_random_seed(void **randseed, int *randseedsize)
264 SYSTEMTIME *st = snew(SYSTEMTIME);
268 *randseed = (void *)st;
269 *randseedsize = sizeof(SYSTEMTIME);
272 static void win_status_bar(void *handle, char *text)
277 frontend *fe = (frontend *)handle;
280 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 255);
281 SendMessage(fe->statusbar, SB_SETTEXT,
282 (WPARAM) 255 | SBT_NOBORDERS,
285 SetWindowText(fe->statusbar, text);
289 static blitter *win_blitter_new(void *handle, int w, int h)
291 blitter *bl = snew(blitter);
293 memset(bl, 0, sizeof(blitter));
301 static void win_blitter_free(void *handle, blitter *bl)
303 if (bl->bitmap) DeleteObject(bl->bitmap);
307 static void blitter_mkbitmap(frontend *fe, blitter *bl)
309 HDC hdc = GetDC(fe->hwnd);
310 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
311 ReleaseDC(fe->hwnd, hdc);
314 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
316 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
318 frontend *fe = (frontend *)handle;
319 HDC hdc_win, hdc_blit;
322 assert(fe->drawstatus == DRAWING);
324 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
326 bl->x = x; bl->y = y;
328 hdc_win = GetDC(fe->hwnd);
329 hdc_blit = CreateCompatibleDC(hdc_win);
330 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
332 prev_blit = SelectObject(hdc_blit, bl->bitmap);
333 if (prev_blit == NULL || prev_blit == HGDI_ERROR)
334 fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
336 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
337 fe->hdc, x, y, SRCCOPY))
338 fatal("BitBlt failed: 0x%x", GetLastError());
340 SelectObject(hdc_blit, prev_blit);
342 ReleaseDC(fe->hwnd, hdc_win);
345 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
347 frontend *fe = (frontend *)handle;
348 HDC hdc_win, hdc_blit;
351 assert(fe->drawstatus == DRAWING);
353 assert(bl->bitmap); /* we should always have saved before loading */
355 if (x == BLITTER_FROMSAVED) x = bl->x;
356 if (y == BLITTER_FROMSAVED) y = bl->y;
358 hdc_win = GetDC(fe->hwnd);
359 hdc_blit = CreateCompatibleDC(hdc_win);
361 prev_blit = SelectObject(hdc_blit, bl->bitmap);
363 BitBlt(fe->hdc, x, y, bl->w, bl->h,
364 hdc_blit, 0, 0, SRCCOPY);
366 SelectObject(hdc_blit, prev_blit);
368 ReleaseDC(fe->hwnd, hdc_win);
371 void frontend_default_colour(frontend *fe, float *output)
373 DWORD c = GetSysColor(COLOR_MENU); /* ick */
375 output[0] = (float)(GetRValue(c) / 255.0);
376 output[1] = (float)(GetGValue(c) / 255.0);
377 output[2] = (float)(GetBValue(c) / 255.0);
380 static POINT win_transform_point(frontend *fe, int x, int y)
384 assert(fe->drawstatus != NOTHING);
386 if (fe->drawstatus == PRINTING) {
387 ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
388 ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
397 static void win_text_colour(frontend *fe, int colour)
399 assert(fe->drawstatus != NOTHING);
401 if (fe->drawstatus == PRINTING) {
404 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
407 * Displaying text in hatched colours is not permitted.
411 SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
413 SetTextColor(fe->hdc, fe->colours[colour]);
417 static void win_set_brush(frontend *fe, int colour)
420 assert(fe->drawstatus != NOTHING);
422 if (fe->drawstatus == PRINTING) {
425 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
428 br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
432 * This is only ever required during printing, and the
433 * PocketPC port doesn't support printing.
435 fatal("CreateHatchBrush not supported");
437 br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
438 hatch == HATCH_SLASH ? HS_BDIAGONAL :
439 hatch == HATCH_HORIZ ? HS_HORIZONTAL :
440 hatch == HATCH_VERT ? HS_VERTICAL :
441 hatch == HATCH_PLUS ? HS_CROSS :
442 /* hatch == HATCH_X ? */ HS_DIAGCROSS,
447 br = fe->brushes[colour];
449 fe->oldbr = SelectObject(fe->hdc, br);
452 static void win_reset_brush(frontend *fe)
456 assert(fe->drawstatus != NOTHING);
458 br = SelectObject(fe->hdc, fe->oldbr);
459 if (fe->drawstatus == PRINTING)
463 static void win_set_pen(frontend *fe, int colour, int thin)
466 assert(fe->drawstatus != NOTHING);
468 if (fe->drawstatus == PRINTING) {
471 int width = thin ? 0 : fe->linewidth;
473 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
475 * Stroking in hatched colours is not permitted.
478 pen = CreatePen(PS_SOLID, width, RGB(r * 255, g * 255, b * 255));
480 pen = fe->pens[colour];
482 fe->oldpen = SelectObject(fe->hdc, pen);
485 static void win_reset_pen(frontend *fe)
489 assert(fe->drawstatus != NOTHING);
491 pen = SelectObject(fe->hdc, fe->oldpen);
492 if (fe->drawstatus == PRINTING)
496 static void win_clip(void *handle, int x, int y, int w, int h)
498 frontend *fe = (frontend *)handle;
501 if (fe->drawstatus == NOTHING)
504 p = win_transform_point(fe, x, y);
505 q = win_transform_point(fe, x+w, y+h);
506 IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
509 static void win_unclip(void *handle)
511 frontend *fe = (frontend *)handle;
513 if (fe->drawstatus == NOTHING)
516 SelectClipRgn(fe->hdc, NULL);
519 static void win_draw_text(void *handle, int x, int y, int fonttype,
520 int fontsize, int align, int colour, char *text)
522 frontend *fe = (frontend *)handle;
527 if (fe->drawstatus == NOTHING)
530 if (fe->drawstatus == PRINTING)
531 fontsize = (int)(fontsize * fe->printpixelscale);
533 xy = win_transform_point(fe, x, y);
536 * Find or create the font.
538 for (i = fe->fontstart; i < fe->nfonts; i++)
539 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
542 if (i == fe->nfonts) {
543 if (fe->fontsize <= fe->nfonts) {
544 fe->fontsize = fe->nfonts + 10;
545 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
550 fe->fonts[i].type = fonttype;
551 fe->fonts[i].size = fontsize;
553 memset (&lf, 0, sizeof(LOGFONT));
554 lf.lfHeight = -fontsize;
555 lf.lfWeight = (fe->drawstatus == PRINTING ? 0 : FW_BOLD);
556 lf.lfCharSet = DEFAULT_CHARSET;
557 lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
558 lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
559 lf.lfQuality = DEFAULT_QUALITY;
560 lf.lfPitchAndFamily = (fonttype == FONT_FIXED ?
561 FIXED_PITCH | FF_DONTCARE :
562 VARIABLE_PITCH | FF_SWISS);
564 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
567 fe->fonts[i].font = CreateFontIndirect(&lf);
571 * Position and draw the text.
579 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 256);
582 oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
583 if (GetTextMetrics(fe->hdc, &tm)) {
584 if (align & ALIGN_VCENTRE)
585 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
590 if (GetTextExtentPoint32(fe->hdc, text, strlen(text), &size))
592 if (GetTextExtentPoint32(fe->hdc, wText, wcslen(wText), &size))
595 if (align & ALIGN_HCENTRE)
597 else if (align & ALIGN_HRIGHT)
600 SetBkMode(fe->hdc, TRANSPARENT);
601 win_text_colour(fe, colour);
603 TextOut(fe->hdc, xy.x, xy.y, text, strlen(text));
605 ExtTextOut(fe->hdc, xy.x, xy.y, 0, NULL, wText, wcslen(wText), NULL);
607 SelectObject(fe->hdc, oldfont);
611 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
613 frontend *fe = (frontend *)handle;
616 if (fe->drawstatus == NOTHING)
619 if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
621 * Rectangle() appears to get uppity if asked to draw a 1x1
622 * rectangle, presumably on the grounds that that's beneath
623 * its dignity and you ought to be using SetPixel instead.
626 SetPixel(fe->hdc, x, y, fe->colours[colour]);
628 win_set_brush(fe, colour);
629 win_set_pen(fe, colour, TRUE);
630 p = win_transform_point(fe, x, y);
631 q = win_transform_point(fe, x+w, y+h);
632 Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
638 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
640 frontend *fe = (frontend *)handle;
643 if (fe->drawstatus == NOTHING)
646 win_set_pen(fe, colour, FALSE);
647 pp[0] = win_transform_point(fe, x1, y1);
648 pp[1] = win_transform_point(fe, x2, y2);
649 Polyline(fe->hdc, pp, 2);
650 if (fe->drawstatus == DRAWING)
651 SetPixel(fe->hdc, pp[1].x, pp[1].y, fe->colours[colour]);
655 static void win_draw_circle(void *handle, int cx, int cy, int radius,
656 int fillcolour, int outlinecolour)
658 frontend *fe = (frontend *)handle;
661 assert(outlinecolour >= 0);
663 if (fe->drawstatus == NOTHING)
667 win_set_brush(fe, fillcolour);
669 fe->oldbr = SelectObject(fe->hdc, GetStockObject(NULL_BRUSH));
671 win_set_pen(fe, outlinecolour, FALSE);
672 p = win_transform_point(fe, cx - radius, cy - radius);
673 q = win_transform_point(fe, cx + radius, cy + radius);
674 Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
679 static void win_draw_polygon(void *handle, int *coords, int npoints,
680 int fillcolour, int outlinecolour)
682 frontend *fe = (frontend *)handle;
686 if (fe->drawstatus == NOTHING)
689 pts = snewn(npoints+1, POINT);
691 for (i = 0; i <= npoints; i++) {
692 int j = (i < npoints ? i : 0);
693 pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
696 assert(outlinecolour >= 0);
698 if (fillcolour >= 0) {
699 win_set_brush(fe, fillcolour);
700 win_set_pen(fe, outlinecolour, FALSE);
701 Polygon(fe->hdc, pts, npoints);
705 win_set_pen(fe, outlinecolour, FALSE);
706 Polyline(fe->hdc, pts, npoints+1);
713 static void win_start_draw(void *handle)
715 frontend *fe = (frontend *)handle;
718 assert(fe->drawstatus == NOTHING);
720 hdc_win = GetDC(fe->hwnd);
721 fe->hdc = CreateCompatibleDC(hdc_win);
722 fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
723 ReleaseDC(fe->hwnd, hdc_win);
726 SetMapMode(fe->hdc, MM_TEXT);
728 fe->drawstatus = DRAWING;
731 static void win_draw_update(void *handle, int x, int y, int w, int h)
733 frontend *fe = (frontend *)handle;
736 if (fe->drawstatus != DRAWING)
744 OffsetRect(&r, fe->bitmapPosition.left, fe->bitmapPosition.top);
745 InvalidateRect(fe->hwnd, &r, FALSE);
748 static void win_end_draw(void *handle)
750 frontend *fe = (frontend *)handle;
751 assert(fe->drawstatus == DRAWING);
752 SelectObject(fe->hdc, fe->prevbm);
755 DeleteObject(fe->clip);
758 fe->drawstatus = NOTHING;
761 static void win_line_width(void *handle, float width)
763 frontend *fe = (frontend *)handle;
765 assert(fe->drawstatus != DRAWING);
766 if (fe->drawstatus == NOTHING)
769 fe->linewidth = (int)(width * fe->printpixelscale);
772 static void win_begin_doc(void *handle, int pages)
774 frontend *fe = (frontend *)handle;
776 assert(fe->drawstatus != DRAWING);
777 if (fe->drawstatus == NOTHING)
780 if (StartDoc(fe->hdc, &fe->di) <= 0) {
781 char *e = geterrstr();
782 MessageBox(fe->hwnd, e, "Error starting to print",
783 MB_ICONERROR | MB_OK);
785 fe->drawstatus = NOTHING;
789 * Push a marker on the font stack so that we won't use the
790 * same fonts for printing and drawing. (This is because
791 * drawing seems to look generally better in bold, but printing
792 * is better not in bold.)
794 fe->fontstart = fe->nfonts;
797 static void win_begin_page(void *handle, int number)
799 frontend *fe = (frontend *)handle;
801 assert(fe->drawstatus != DRAWING);
802 if (fe->drawstatus == NOTHING)
805 if (StartPage(fe->hdc) <= 0) {
806 char *e = geterrstr();
807 MessageBox(fe->hwnd, e, "Error starting a page",
808 MB_ICONERROR | MB_OK);
810 fe->drawstatus = NOTHING;
814 static void win_begin_puzzle(void *handle, float xm, float xc,
815 float ym, float yc, int pw, int ph, float wmm)
817 frontend *fe = (frontend *)handle;
818 int ppw, pph, pox, poy;
819 float mmpw, mmph, mmox, mmoy;
822 assert(fe->drawstatus != DRAWING);
823 if (fe->drawstatus == NOTHING)
826 ppw = GetDeviceCaps(fe->hdc, HORZRES);
827 pph = GetDeviceCaps(fe->hdc, VERTRES);
828 mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
829 mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
832 * Compute the puzzle's position on the logical page.
834 mmox = xm * mmpw + xc;
835 mmoy = ym * mmph + yc;
838 * Work out what that comes to in pixels.
840 pox = (int)(mmox * (float)ppw / mmpw);
841 poy = (int)(mmoy * (float)ppw / mmpw);
844 * And determine the scale.
846 * I need a scale such that the maximum puzzle-coordinate
847 * extent of the rectangle (pw * scale) is equal to the pixel
848 * equivalent of the puzzle's millimetre width (wmm * ppw /
851 scale = (wmm * ppw) / (mmpw * pw);
854 * Now store pox, poy and scale for use in the main drawing
857 fe->printoffsetx = pox;
858 fe->printoffsety = poy;
859 fe->printpixelscale = scale;
864 static void win_end_puzzle(void *handle)
866 /* Nothing needs to be done here. */
869 static void win_end_page(void *handle, int number)
871 frontend *fe = (frontend *)handle;
873 assert(fe->drawstatus != DRAWING);
875 if (fe->drawstatus == NOTHING)
878 if (EndPage(fe->hdc) <= 0) {
879 char *e = geterrstr();
880 MessageBox(fe->hwnd, e, "Error finishing a page",
881 MB_ICONERROR | MB_OK);
883 fe->drawstatus = NOTHING;
887 static void win_end_doc(void *handle)
889 frontend *fe = (frontend *)handle;
891 assert(fe->drawstatus != DRAWING);
894 * Free all the fonts created since we began printing.
896 while (fe->nfonts > fe->fontstart) {
898 DeleteObject(fe->fonts[fe->nfonts].font);
903 * The MSDN web site sample code doesn't bother to call EndDoc
904 * if an error occurs half way through printing. I expect doing
905 * so would cause the erroneous document to actually be
906 * printed, or something equally undesirable.
908 if (fe->drawstatus == NOTHING)
911 if (EndDoc(fe->hdc) <= 0) {
912 char *e = geterrstr();
913 MessageBox(fe->hwnd, e, "Error finishing printing",
914 MB_ICONERROR | MB_OK);
916 fe->drawstatus = NOTHING;
920 const struct drawing_api win_drawing = {
945 void print(frontend *fe)
951 midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
956 * Create our document structure and fill it up with puzzles.
958 doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
959 for (i = 0; i < fe->printcount; i++) {
960 if (i == 0 && fe->printcurr) {
961 err = midend_print_puzzle(fe->me, doc, fe->printsolns);
966 nme = midend_new(NULL, &thegame, NULL, NULL);
969 * Set the non-interactive mid-end to have the same
970 * parameters as the standard one.
972 params = midend_get_params(fe->me);
973 midend_set_params(nme, params);
974 thegame.free_params(params);
977 midend_new_game(nme);
978 err = midend_print_puzzle(nme, doc, fe->printsolns);
987 MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
988 MB_ICONERROR | MB_OK);
993 memset(&pd, 0, sizeof(pd));
994 pd.lStructSize = sizeof(pd);
995 pd.hwndOwner = fe->hwnd;
998 pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
999 PD_NOPAGENUMS | PD_NOSELECTION;
1001 pd.nFromPage = pd.nToPage = 0xFFFF;
1002 pd.nMinPage = pd.nMaxPage = 1;
1004 if (!PrintDlg(&pd)) {
1010 * Now pd.hDC is a device context for the printer.
1014 * FIXME: IWBNI we put up an Abort box here.
1017 memset(&fe->di, 0, sizeof(fe->di));
1018 fe->di.cbSize = sizeof(fe->di);
1019 sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
1020 " Portable Puzzle Collection)", thegame.name);
1021 fe->di.lpszDocName = doctitle;
1022 fe->di.lpszOutput = NULL;
1023 fe->di.lpszDatatype = NULL;
1026 fe->drawstatus = PRINTING;
1029 fe->dr = drawing_new(&win_drawing, NULL, fe);
1030 document_print(doc, fe->dr);
1031 drawing_free(fe->dr);
1034 fe->drawstatus = NOTHING;
1041 void deactivate_timer(frontend *fe)
1044 return; /* for non-interactive midend */
1045 if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
1049 void activate_timer(frontend *fe)
1052 return; /* for non-interactive midend */
1054 fe->timer = SetTimer(fe->hwnd, 1, 20, NULL);
1055 fe->timer_last_tickcount = GetTickCount();
1059 void write_clip(HWND hwnd, char *data)
1067 * Windows expects CRLF in the clipboard, so we must convert
1068 * any \n that has come out of the puzzle backend.
1071 for (i = 0; data[i]; i++) {
1072 if (data[i] == '\n')
1076 data2 = snewn(len+1, char);
1078 for (i = 0; data[i]; i++) {
1079 if (data[i] == '\n')
1081 data2[j++] = data[i];
1086 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
1089 lock = GlobalLock(clipdata);
1092 memcpy(lock, data2, len);
1093 ((unsigned char *) lock)[len] = 0;
1094 GlobalUnlock(clipdata);
1096 if (OpenClipboard(hwnd)) {
1098 SetClipboardData(CF_TEXT, clipdata);
1101 GlobalFree(clipdata);
1107 * Set up Help and see if we can find a help file.
1109 static void init_help(void)
1112 char b[2048], *p, *q, *r;
1116 * Find the executable file path, so we can look alongside
1117 * it for help files. Trim the filename off the end.
1119 GetModuleFileName(NULL, b, sizeof(b) - 1);
1121 p = strrchr(b, '\\');
1122 if (p && p >= r) r = p+1;
1123 q = strrchr(b, ':');
1124 if (q && q >= r) r = q+1;
1128 * Try HTML Help first.
1130 strcpy(r, CHM_FILE_NAME);
1131 if ( (fp = fopen(b, "r")) != NULL) {
1135 * We have a .CHM. See if we can use it.
1137 hh_dll = LoadLibrary("hhctrl.ocx");
1139 htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
1141 FreeLibrary(hh_dll);
1144 help_path = dupstr(b);
1146 help_topic = thegame.htmlhelp_topic;
1150 #endif /* NO_HTMLHELP */
1153 * Now try old-style .HLP.
1155 strcpy(r, HELP_FILE_NAME);
1156 if ( (fp = fopen(b, "r")) != NULL) {
1159 help_path = dupstr(b);
1162 help_topic = thegame.winhelp_topic;
1165 * See if there's a .CNT file alongside it.
1167 strcpy(r, HELP_CNT_NAME);
1168 if ( (fp = fopen(b, "r")) != NULL) {
1170 help_has_contents = TRUE;
1172 help_has_contents = FALSE;
1177 help_type = NONE; /* didn't find any */
1186 static void start_help(frontend *fe, const char *topic)
1191 switch (help_type) {
1195 str = snewn(10+strlen(topic), char);
1196 sprintf(str, "JI(`',`%s')", topic);
1198 } else if (help_has_contents) {
1201 cmd = HELP_CONTENTS;
1203 WinHelp(fe->hwnd, help_path, cmd, (DWORD)str);
1204 fe->help_running = TRUE;
1211 str = snewn(20 + strlen(topic) + strlen(help_path), char);
1212 sprintf(str, "%s::/%s.html>main", help_path, topic);
1214 str = dupstr(help_path);
1216 htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
1217 fe->help_running = TRUE;
1219 #endif /* NO_HTMLHELP */
1221 assert(!"This shouldn't happen");
1229 * Stop Help on window cleanup.
1231 static void stop_help(frontend *fe)
1233 if (fe->help_running) {
1234 switch (help_type) {
1236 WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
1241 htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
1243 #endif /* NO_HTMLHELP */
1245 assert(!"This shouldn't happen");
1248 fe->help_running = FALSE;
1255 * Terminate Help on process exit.
1257 static void cleanup_help(void)
1259 /* Nothing to do currently.
1260 * (If we were running HTML Help single-threaded, this is where we'd
1261 * call HH_UNINITIALIZE.) */
1264 static int get_statusbar_height(frontend *fe)
1267 if (fe->statusbar) {
1269 GetWindowRect(fe->statusbar, &sr);
1270 sy = sr.bottom - sr.top;
1277 static void adjust_statusbar(frontend *fe, RECT *r)
1281 if (!fe->statusbar) return;
1283 sy = get_statusbar_height(fe);
1285 SetWindowPos(fe->statusbar, NULL, 0, r->bottom-r->top-sy, r->right-r->left,
1290 static void get_menu_size(HWND wh, RECT *r)
1292 HMENU bar = GetMenu(wh);
1296 SetRect(r, 0, 0, 0, 0);
1297 for (i = 0; i < GetMenuItemCount(bar); i++) {
1298 GetMenuItemRect(wh, bar, i, &rect);
1299 UnionRect(r, r, &rect);
1304 * Given a proposed new puzzle size (cx,cy), work out the actual
1305 * puzzle size that would be (px,py) and the window size including
1306 * furniture (wx,wy).
1309 static int check_window_resize(frontend *fe, int cx, int cy,
1311 int *wx, int *wy, int resize)
1314 int x, y, sy = get_statusbar_height(fe), changed = 0;
1316 /* disallow making window thinner than menu bar */
1317 x = max(cx, fe->xmin);
1318 y = max(cy - sy, fe->ymin);
1321 * See if we actually got the window size we wanted, and adjust
1322 * the puzzle size if not.
1324 midend_size(fe->me, &x, &y, resize);
1325 if (x != cx || y != cy) {
1327 * Resize the window, now we know what size we _really_
1333 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1334 *wx = r.right - r.left;
1335 *wy = r.bottom - r.top;
1346 * Given the current window size, make sure it's sane for the
1347 * current puzzle and resize if necessary.
1350 static void check_window_size(frontend *fe, int *px, int *py)
1355 GetClientRect(fe->hwnd, &r);
1356 cx = r.right - r.left;
1357 cy = r.bottom - r.top;
1359 if (check_window_resize(fe, cx, cy, px, py, &wx, &wy, FALSE)) {
1361 SetWindowPos(fe->hwnd, NULL, 0, 0, wx, wy,
1362 SWP_NOMOVE | SWP_NOZORDER);
1367 GetClientRect(fe->hwnd, &r);
1368 adjust_statusbar(fe, &r);
1371 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1375 if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1376 *x = sr.right - sr.left;
1377 *y = sr.bottom - sr.top;
1382 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1383 *x -= r.right - r.left - 100;
1384 *y -= r.bottom - r.top - 100;
1389 if (fe->statusbar != NULL) {
1390 GetWindowRect(fe->statusbar, &sr);
1391 *y -= sr.bottom - sr.top;
1396 /* Toolbar buttons on the numeric pad */
1397 static TBBUTTON tbNumpadButtons[] =
1399 {0, IDM_KEYEMUL + '1', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1400 {1, IDM_KEYEMUL + '2', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1401 {2, IDM_KEYEMUL + '3', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1402 {3, IDM_KEYEMUL + '4', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1403 {4, IDM_KEYEMUL + '5', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1404 {5, IDM_KEYEMUL + '6', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1405 {6, IDM_KEYEMUL + '7', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1406 {7, IDM_KEYEMUL + '8', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1407 {8, IDM_KEYEMUL + '9', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1408 {9, IDM_KEYEMUL + ' ', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1}
1412 static frontend *new_window(HINSTANCE inst, char *game_id, char **error)
1418 fe = snew(frontend);
1420 fe->me = midend_new(fe, &thegame, &win_drawing, fe);
1423 *error = midend_game_id(fe->me, game_id);
1425 midend_free(fe->me);
1436 fe->help_running = FALSE;
1438 fe->drawstatus = NOTHING;
1442 midend_new_game(fe->me);
1445 fe->nfonts = fe->fontsize = 0;
1451 colours = midend_colours(fe->me, &ncolours);
1453 fe->colours = snewn(ncolours, COLORREF);
1454 fe->brushes = snewn(ncolours, HBRUSH);
1455 fe->pens = snewn(ncolours, HPEN);
1457 for (i = 0; i < ncolours; i++) {
1458 fe->colours[i] = RGB(255 * colours[i*3+0],
1459 255 * colours[i*3+1],
1460 255 * colours[i*3+2]);
1461 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1462 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1467 if (midend_wants_statusbar(fe->me)) {
1468 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1469 WS_CHILD | WS_VISIBLE,
1470 0, 0, 0, 0, /* status bar does these */
1471 NULL, NULL, inst, NULL);
1473 fe->statusbar = NULL;
1475 get_max_puzzle_size(fe, &x, &y);
1476 midend_size(fe->me, &x, &y, FALSE);
1481 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1484 fe->hwnd = CreateWindowEx(0, wGameName, wGameName,
1486 CW_USEDEFAULT, CW_USEDEFAULT,
1487 CW_USEDEFAULT, CW_USEDEFAULT,
1488 NULL, NULL, inst, NULL);
1492 RECT rc, rcBar, rcTB, rcClient;
1494 memset (&mbi, 0, sizeof(SHMENUBARINFO));
1495 mbi.cbSize = sizeof(SHMENUBARINFO);
1496 mbi.hwndParent = fe->hwnd;
1497 mbi.nToolBarId = IDR_MENUBAR1;
1498 mbi.hInstRes = inst;
1500 SHCreateMenuBar(&mbi);
1502 GetWindowRect(fe->hwnd, &rc);
1503 GetWindowRect(mbi.hwndMB, &rcBar);
1504 rc.bottom -= rcBar.bottom - rcBar.top;
1505 MoveWindow(fe->hwnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, FALSE);
1507 if (thegame.flags & REQUIRE_NUMPAD)
1509 fe->numpad = CreateToolbarEx (fe->hwnd,
1510 WS_VISIBLE | WS_CHILD | CCS_NOPARENTALIGN | TBSTYLE_FLAT,
1511 0, 10, inst, IDR_PADTOOLBAR,
1512 tbNumpadButtons, sizeof (tbNumpadButtons) / sizeof (TBBUTTON),
1513 0, 0, 14, 15, sizeof (TBBUTTON));
1514 GetWindowRect(fe->numpad, &rcTB);
1515 GetClientRect(fe->hwnd, &rcClient);
1516 MoveWindow(fe->numpad,
1518 rcClient.bottom - (rcTB.bottom - rcTB.top) - 1,
1520 rcTB.bottom - rcTB.top,
1522 SendMessage(fe->numpad, TB_SETINDENT, (rcClient.right - (10 * 21)) / 2, 0);
1528 fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
1529 WS_OVERLAPPEDWINDOW &~
1531 CW_USEDEFAULT, CW_USEDEFAULT,
1532 r.right - r.left, r.bottom - r.top,
1533 NULL, NULL, inst, NULL);
1536 if (midend_wants_statusbar(fe->me)) {
1538 DestroyWindow(fe->statusbar);
1539 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1540 WS_CHILD | WS_VISIBLE,
1541 0, 0, 0, 0, /* status bar does these */
1542 fe->hwnd, NULL, inst, NULL);
1544 /* Flat status bar looks better on the Pocket PC */
1545 SendMessage(fe->statusbar, SB_SIMPLE, (WPARAM) TRUE, 0);
1546 SendMessage(fe->statusbar, SB_SETTEXT,
1547 (WPARAM) 255 | SBT_NOBORDERS,
1552 * Now resize the window to take account of the status bar.
1554 GetWindowRect(fe->statusbar, &sr);
1555 GetWindowRect(fe->hwnd, &r);
1557 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1558 r.bottom - r.top + sr.bottom - sr.top,
1559 SWP_NOMOVE | SWP_NOZORDER);
1562 fe->statusbar = NULL;
1567 HMENU bar = CreateMenu();
1568 HMENU menu = CreateMenu();
1571 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "&Game");
1573 HMENU menu = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_GAME);
1574 DeleteMenu(menu, 0, MF_BYPOSITION);
1576 AppendMenu(menu, MF_ENABLED, IDM_NEW, TEXT("&New"));
1577 AppendMenu(menu, MF_ENABLED, IDM_RESTART, TEXT("&Restart"));
1579 /* ...here I run out of sensible accelerator characters. */
1580 AppendMenu(menu, MF_ENABLED, IDM_DESC, TEXT("Speci&fic..."));
1581 AppendMenu(menu, MF_ENABLED, IDM_SEED, TEXT("Rando&m Seed..."));
1584 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1585 thegame.can_configure) {
1588 HMENU sub = CreateMenu();
1590 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "&Type");
1592 HMENU sub = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_TYPE);
1593 DeleteMenu(sub, 0, MF_BYPOSITION);
1595 fe->presets = snewn(fe->npresets, game_params *);
1597 for (i = 0; i < fe->npresets; i++) {
1603 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1606 * FIXME: we ought to go through and do something
1607 * with ampersands here.
1611 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1613 MultiByteToWideChar (CP_ACP, 0, name, -1, wName, 255);
1614 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, wName);
1617 if (thegame.can_configure) {
1618 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, TEXT("&Custom..."));
1623 fe->typemenu = INVALID_HANDLE_VALUE;
1625 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1627 AppendMenu(menu, MF_ENABLED, IDM_LOAD, TEXT("&Load..."));
1628 AppendMenu(menu, MF_ENABLED, IDM_SAVE, TEXT("&Save..."));
1629 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1630 if (thegame.can_print) {
1631 AppendMenu(menu, MF_ENABLED, IDM_PRINT, TEXT("&Print..."));
1632 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1635 AppendMenu(menu, MF_ENABLED, IDM_UNDO, TEXT("Undo"));
1636 AppendMenu(menu, MF_ENABLED, IDM_REDO, TEXT("Redo"));
1638 if (thegame.can_format_as_text) {
1639 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1640 AppendMenu(menu, MF_ENABLED, IDM_COPY, TEXT("&Copy"));
1643 if (thegame.can_solve) {
1644 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1645 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, TEXT("Sol&ve"));
1647 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1649 AppendMenu(menu, MF_ENABLED, IDM_QUIT, TEXT("E&xit"));
1650 menu = CreateMenu();
1651 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, TEXT("&Help"));
1653 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, TEXT("&About"));
1655 if (help_type != NONE) {
1656 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1657 AppendMenu(menu, MF_ENABLED, IDM_HELPC, TEXT("&Contents"));
1660 assert(thegame.name);
1661 item = snewn(10+strlen(thegame.name), char); /*ick*/
1662 sprintf(item, "&Help on %s", thegame.name);
1663 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1667 SetMenu(fe->hwnd, bar);
1668 get_menu_size(fe->hwnd, &menusize);
1669 fe->xmin = (menusize.right - menusize.left) + 25;
1674 new_game_size(fe); /* initialises fe->bitmap */
1675 check_window_size(fe, &x, &y);
1677 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1679 ShowWindow(fe->hwnd, SW_SHOWNORMAL);
1680 SetForegroundWindow(fe->hwnd);
1682 update_type_menu_tick(fe);
1684 midend_redraw(fe->me);
1690 static HFONT dialog_title_font()
1692 static HFONT hf = NULL;
1698 memset (&lf, 0, sizeof(LOGFONT));
1699 lf.lfHeight = -11; /* - ((8 * GetDeviceCaps(hdc, LOGPIXELSY)) / 72) */
1700 lf.lfWeight = FW_BOLD;
1701 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
1703 return hf = CreateFontIndirect(&lf);
1706 static void make_dialog_full_screen(HWND hwnd)
1708 SHINITDLGINFO shidi;
1710 /* Make dialog full screen */
1711 shidi.dwMask = SHIDIM_FLAGS;
1712 shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIZEDLGFULLSCREEN |
1715 SHInitDialog(&shidi);
1719 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1720 WPARAM wParam, LPARAM lParam)
1722 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1730 make_dialog_full_screen(hwnd);
1732 sprintf(title, "About %.250s", thegame.name);
1733 SetDlgItemTextA(hwnd, IDC_ABOUT_CAPTION, title);
1735 SendDlgItemMessage(hwnd, IDC_ABOUT_CAPTION, WM_SETFONT,
1736 (WPARAM) dialog_title_font(), 0);
1738 SetDlgItemTextA(hwnd, IDC_ABOUT_GAME, thegame.name);
1739 SetDlgItemTextA(hwnd, IDC_ABOUT_VERSION, ver);
1745 if (LOWORD(wParam) == IDOK)
1766 * Wrappers on midend_{get,set}_config, which extend the CFG_*
1767 * enumeration to add CFG_PRINT.
1769 static config_item *frontend_get_config(frontend *fe, int which,
1772 if (which < CFG_FRONTEND_SPECIFIC) {
1773 return midend_get_config(fe->me, which, wintitle);
1774 } else if (which == CFG_PRINT) {
1778 *wintitle = snewn(40 + strlen(thegame.name), char);
1779 sprintf(*wintitle, "%s print setup", thegame.name);
1781 ret = snewn(8, config_item);
1785 ret[i].name = "Number of puzzles to print";
1786 ret[i].type = C_STRING;
1787 ret[i].sval = dupstr("1");
1791 ret[i].name = "Number of puzzles across the page";
1792 ret[i].type = C_STRING;
1793 ret[i].sval = dupstr("1");
1797 ret[i].name = "Number of puzzles down the page";
1798 ret[i].type = C_STRING;
1799 ret[i].sval = dupstr("1");
1803 ret[i].name = "Percentage of standard size";
1804 ret[i].type = C_STRING;
1805 ret[i].sval = dupstr("100.0");
1809 ret[i].name = "Include currently shown puzzle";
1810 ret[i].type = C_BOOLEAN;
1815 ret[i].name = "Print solutions";
1816 ret[i].type = C_BOOLEAN;
1818 ret[i].ival = FALSE;
1821 if (thegame.can_print_in_colour) {
1822 ret[i].name = "Print in colour";
1823 ret[i].type = C_BOOLEAN;
1825 ret[i].ival = FALSE;
1830 ret[i].type = C_END;
1837 assert(!"We should never get here");
1842 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
1844 if (which < CFG_FRONTEND_SPECIFIC) {
1845 return midend_set_config(fe->me, which, cfg);
1846 } else if (which == CFG_PRINT) {
1847 if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
1848 return "Number of puzzles to print should be at least one";
1849 if ((fe->printw = atoi(cfg[1].sval)) <= 0)
1850 return "Number of puzzles across the page should be at least one";
1851 if ((fe->printh = atoi(cfg[2].sval)) <= 0)
1852 return "Number of puzzles down the page should be at least one";
1853 if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
1854 return "Print size should be positive";
1855 fe->printcurr = cfg[4].ival;
1856 fe->printsolns = cfg[5].ival;
1857 fe->printcolour = thegame.can_print_in_colour && cfg[6].ival;
1860 assert(!"We should never get here");
1861 return "Internal error";
1866 /* Separate version of mkctrl function for the Pocket PC. */
1867 /* Control coordinates should be specified in dialog units. */
1868 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
1869 LPCTSTR wclass, int wstyle,
1870 int exstyle, const char *wtext, int wid)
1875 /* Convert dialog units into pixels */
1876 rc.left = x1; rc.right = x2;
1877 rc.top = y1; rc.bottom = y2;
1878 MapDialogRect(fe->cfgbox, &rc);
1880 MultiByteToWideChar (CP_ACP, 0, wtext, -1, wwtext, 256);
1882 return CreateWindowEx(exstyle, wclass, wwtext,
1883 wstyle | WS_CHILD | WS_VISIBLE,
1885 rc.right - rc.left, rc.bottom - rc.top,
1886 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
1889 static void create_config_controls(frontend * fe)
1892 int col1l, col1r, col2l, col2r, y;
1897 /* Control placement done in dialog units */
1898 col1l = 4; col1r = 96; /* Label column */
1899 col2l = 100; col2r = 154; /* Input column (edit boxes and combo boxes) */
1902 * Count the controls so we can allocate cfgaux.
1904 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
1906 fe->cfgaux = snewn(nctrls, struct cfg_aux);
1909 y = 22; /* Leave some room for the dialog title */
1910 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1914 * Edit box with a label beside it.
1916 mkctrl(fe, col1l, col1r, y + 1, y + 11,
1917 TEXT("Static"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
1918 mkctrl(fe, col2l, col2r, y, y + 12,
1919 TEXT("EDIT"), WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
1920 0, "", (j->ctlid = id++));
1921 SetDlgItemTextA(fe->cfgbox, j->ctlid, i->sval);
1928 mkctrl(fe, col1l, col2r, y + 1, y + 11, TEXT("BUTTON"),
1929 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
1930 0, i->name, (j->ctlid = id++));
1931 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
1936 * Drop-down list with a label beside it.
1938 mkctrl(fe, col1l, col1r, y + 1, y + 11,
1939 TEXT("STATIC"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
1940 ctl = mkctrl(fe, col2l, col2r, y, y + 48,
1941 TEXT("COMBOBOX"), WS_BORDER | WS_TABSTOP |
1942 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
1943 0, "", (j->ctlid = id++));
1945 char c, *p, *q, *str;
1951 while (*q && *q != c) q++;
1952 str = snewn(q-p+1, char);
1953 strncpy(str, p, q-p);
1957 MultiByteToWideChar (CP_ACP, 0, str, -1, ws, 50);
1958 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)ws);
1966 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
1976 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
1977 WPARAM wParam, LPARAM lParam)
1979 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1989 fe = (frontend *) lParam;
1990 SetWindowLong(hwnd, GWL_USERDATA, lParam);
1993 fe->cfg = frontend_get_config(fe, fe->cfg_which, &title);
1995 make_dialog_full_screen(hwnd);
1997 SetDlgItemTextA(hwnd, IDC_CONFIG_CAPTION, title);
1998 SendDlgItemMessage(hwnd, IDC_CONFIG_CAPTION, WM_SETFONT,
1999 (WPARAM) dialog_title_font(), 0);
2001 create_config_controls(fe);
2008 * OK and Cancel are special cases.
2010 if ((LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
2011 if (LOWORD(wParam) == IDOK) {
2012 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
2015 MessageBox(hwnd, err, "Validation error",
2016 MB_ICONERROR | MB_OK);
2035 * First find the control whose id this is.
2037 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2038 if (j->ctlid == LOWORD(wParam))
2041 if (i->type == C_END)
2042 return 0; /* not our problem */
2044 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
2047 TCHAR wBuffer[4096];
2048 GetDlgItemText(fe->cfgbox, j->ctlid, wBuffer, 4096);
2049 WideCharToMultiByte(CP_ACP, 0, wBuffer, -1, buffer, 4096, NULL, NULL);
2051 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
2053 buffer[lenof(buffer)-1] = '\0';
2055 i->sval = dupstr(buffer);
2056 } else if (i->type == C_BOOLEAN &&
2057 (HIWORD(wParam) == BN_CLICKED ||
2058 HIWORD(wParam) == BN_DBLCLK)) {
2059 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
2060 } else if (i->type == C_CHOICES &&
2061 HIWORD(wParam) == CBN_SELCHANGE) {
2062 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
2063 CB_GETCURSEL, 0, 0);
2077 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2078 char *wclass, int wstyle,
2079 int exstyle, const char *wtext, int wid)
2082 ret = CreateWindowEx(exstyle, wclass, wtext,
2083 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
2084 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2085 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
2090 static void about(frontend *fe)
2093 DialogBox(fe->inst, MAKEINTRESOURCE(IDD_ABOUT), fe->hwnd, AboutDlgProc);
2103 int winwidth, winheight, y;
2104 int height, width, maxwid;
2105 const char *strings[16];
2110 sprintf(titlebuf, "About %.250s", thegame.name);
2112 strings[nstrings++] = thegame.name;
2113 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
2114 strings[nstrings++] = ver;
2116 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2117 wc.lpfnWndProc = DefDlgProc;
2119 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2120 wc.hInstance = fe->inst;
2122 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2123 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2124 wc.lpszMenuName = NULL;
2125 wc.lpszClassName = "GameAboutBox";
2128 hdc = GetDC(fe->hwnd);
2129 SetMapMode(hdc, MM_TEXT);
2131 fe->dlg_done = FALSE;
2133 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2135 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2136 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2141 oldfont = SelectObject(hdc, fe->cfgfont);
2142 if (GetTextMetrics(hdc, &tm)) {
2143 height = tm.tmAscent + tm.tmDescent;
2144 width = tm.tmAveCharWidth;
2146 height = width = 30;
2150 * Figure out the layout of the About box by measuring the
2151 * length of each piece of text.
2154 winheight = height/2;
2156 for (i = 0; i < nstrings; i++) {
2157 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
2158 lengths[i] = size.cx;
2160 lengths[i] = 0; /* *shrug* */
2161 if (maxwid < lengths[i])
2162 maxwid = lengths[i];
2163 winheight += height * 3 / 2 + (height / 2);
2166 winheight += height + height * 7 / 4; /* OK button */
2167 winwidth = maxwid + 4*width;
2169 SelectObject(hdc, oldfont);
2170 ReleaseDC(fe->hwnd, hdc);
2173 * Create the dialog, now that we know its size.
2180 r.bottom = winheight;
2182 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2183 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2184 WS_CAPTION | WS_SYSMENU*/) &~
2185 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2189 * Centre the dialog on its parent window.
2193 GetWindowRect(fe->hwnd, &r2);
2194 r.left = (r2.left + r2.right - r.right) / 2;
2195 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2199 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
2200 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2201 WS_CAPTION | WS_SYSMENU,
2203 r.right-r.left, r.bottom-r.top,
2204 fe->hwnd, NULL, fe->inst, NULL);
2207 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2209 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2210 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
2214 for (i = 0; i < nstrings; i++) {
2215 int border = width*2 + (maxwid - lengths[i]) / 2;
2216 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
2217 "Static", 0, 0, strings[i], id++);
2220 assert(y < winheight);
2224 y += height/2; /* extra space before OK */
2225 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
2226 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2229 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2231 EnableWindow(fe->hwnd, FALSE);
2232 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2233 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2234 if (!IsDialogMessage(fe->cfgbox, &msg))
2235 DispatchMessage(&msg);
2239 EnableWindow(fe->hwnd, TRUE);
2240 SetForegroundWindow(fe->hwnd);
2241 DestroyWindow(fe->cfgbox);
2242 DeleteObject(fe->cfgfont);
2246 static int get_config(frontend *fe, int which)
2249 fe->cfg_which = which;
2251 return DialogBoxParam(fe->inst,
2252 MAKEINTRESOURCE(IDD_CONFIG),
2253 fe->hwnd, ConfigDlgProc,
2267 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
2268 int height, width, maxlabel, maxcheckbox;
2270 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2271 wc.lpfnWndProc = DefDlgProc;
2273 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2274 wc.hInstance = fe->inst;
2276 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2277 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2278 wc.lpszMenuName = NULL;
2279 wc.lpszClassName = "GameConfigBox";
2282 hdc = GetDC(fe->hwnd);
2283 SetMapMode(hdc, MM_TEXT);
2285 fe->dlg_done = FALSE;
2287 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2289 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2290 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2295 oldfont = SelectObject(hdc, fe->cfgfont);
2296 if (GetTextMetrics(hdc, &tm)) {
2297 height = tm.tmAscent + tm.tmDescent;
2298 width = tm.tmAveCharWidth;
2300 height = width = 30;
2303 fe->cfg = frontend_get_config(fe, which, &title);
2304 fe->cfg_which = which;
2307 * Figure out the layout of the config box by measuring the
2308 * length of each piece of text.
2310 maxlabel = maxcheckbox = 0;
2311 winheight = height/2;
2313 for (i = fe->cfg; i->type != C_END; i++) {
2318 * Both these control types have a label filling only
2319 * the left-hand column of the box.
2321 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2324 winheight += height * 3 / 2 + (height / 2);
2329 * Checkboxes take up the whole of the box width.
2331 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2332 maxcheckbox < size.cx)
2333 maxcheckbox = size.cx;
2334 winheight += height + (height / 2);
2339 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
2342 col1r = col1l + maxlabel;
2343 col2l = col1r + 2*width;
2344 col2r = col2l + 30*width;
2345 if (col2r < col1l+2*height+maxcheckbox)
2346 col2r = col1l+2*height+maxcheckbox;
2347 winwidth = col2r + 2*width;
2349 SelectObject(hdc, oldfont);
2350 ReleaseDC(fe->hwnd, hdc);
2353 * Create the dialog, now that we know its size.
2360 r.bottom = winheight;
2362 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2363 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2364 WS_CAPTION | WS_SYSMENU*/) &~
2365 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2369 * Centre the dialog on its parent window.
2373 GetWindowRect(fe->hwnd, &r2);
2374 r.left = (r2.left + r2.right - r.right) / 2;
2375 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2379 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
2380 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2381 WS_CAPTION | WS_SYSMENU,
2383 r.right-r.left, r.bottom-r.top,
2384 fe->hwnd, NULL, fe->inst, NULL);
2388 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2390 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2391 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
2394 * Count the controls so we can allocate cfgaux.
2396 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2398 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2402 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2406 * Edit box with a label beside it.
2408 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2409 "Static", 0, 0, i->name, id++);
2410 ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
2411 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
2412 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2413 SetWindowText(ctl, i->sval);
2421 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
2422 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2423 0, i->name, (j->ctlid = id++));
2424 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2430 * Drop-down list with a label beside it.
2432 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2433 "STATIC", 0, 0, i->name, id++);
2434 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
2435 "COMBOBOX", WS_TABSTOP |
2436 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2437 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2439 char c, *p, *q, *str;
2441 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
2446 while (*q && *q != c) q++;
2447 str = snewn(q-p+1, char);
2448 strncpy(str, p, q-p);
2450 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
2457 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2463 assert(y < winheight);
2467 y += height/2; /* extra space before OK and Cancel */
2468 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
2469 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2471 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
2472 BS_PUSHBUTTON | WS_TABSTOP, 0, "Cancel", IDCANCEL);
2474 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2476 EnableWindow(fe->hwnd, FALSE);
2477 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2478 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2479 if (!IsDialogMessage(fe->cfgbox, &msg))
2480 DispatchMessage(&msg);
2484 EnableWindow(fe->hwnd, TRUE);
2485 SetForegroundWindow(fe->hwnd);
2486 DestroyWindow(fe->cfgbox);
2487 DeleteObject(fe->cfgfont);
2492 return (fe->dlg_done == 2);
2497 static void calculate_bitmap_position(frontend *fe, int x, int y)
2499 /* Pocket PC - center the game in the full screen window */
2503 GetClientRect(fe->hwnd, &rcClient);
2504 fe->bitmapPosition.left = (rcClient.right - x) / 2;
2505 yMargin = rcClient.bottom - y;
2507 if (fe->numpad != NULL) {
2509 GetWindowRect(fe->numpad, &rcPad);
2510 yMargin -= rcPad.bottom - rcPad.top;
2513 if (fe->statusbar != NULL) {
2515 GetWindowRect(fe->statusbar, &rcStatus);
2516 yMargin -= rcStatus.bottom - rcStatus.top;
2519 fe->bitmapPosition.top = yMargin / 2;
2521 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2522 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2525 static void calculate_bitmap_position(frontend *fe, int x, int y)
2527 /* Plain Windows - position the game in the upper-left corner */
2528 fe->bitmapPosition.left = 0;
2529 fe->bitmapPosition.top = 0;
2530 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2531 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2535 static void new_bitmap(frontend *fe, int x, int y)
2539 if (fe->bitmap) DeleteObject(fe->bitmap);
2541 hdc = GetDC(fe->hwnd);
2542 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2543 calculate_bitmap_position(fe, x, y);
2544 ReleaseDC(fe->hwnd, hdc);
2547 static void new_game_size(frontend *fe)
2552 get_max_puzzle_size(fe, &x, &y);
2553 midend_size(fe->me, &x, &y, FALSE);
2554 fe->ymin = (fe->xmin * y) / x;
2559 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2561 if (fe->statusbar != NULL) {
2562 GetWindowRect(fe->statusbar, &sr);
2564 sr.left = sr.right = sr.top = sr.bottom = 0;
2567 SetWindowPos(fe->hwnd, NULL, 0, 0,
2569 r.bottom - r.top + sr.bottom - sr.top,
2570 SWP_NOMOVE | SWP_NOZORDER);
2573 check_window_size(fe, &x, &y);
2576 if (fe->statusbar != NULL)
2577 SetWindowPos(fe->statusbar, NULL, 0, y, x,
2578 sr.bottom - sr.top, SWP_NOZORDER);
2581 new_bitmap(fe, x, y);
2584 InvalidateRect(fe->hwnd, NULL, TRUE);
2586 midend_redraw(fe->me);
2590 * Given a proposed new window rect, work out the resulting
2591 * difference in client size (from current), and use to try
2592 * and resize the puzzle, returning (wx,wy) as the actual
2596 static void adjust_game_size(frontend *fe, RECT *proposed, int isedge,
2597 int *wx_r, int *wy_r)
2600 int nx, ny, xdiff, ydiff, wx, wy;
2602 /* Work out the current window sizing, and thus the
2603 * difference in size we're asking for. */
2604 GetClientRect(fe->hwnd, &cr);
2606 AdjustWindowRectEx(&wr, WINFLAGS, TRUE, 0);
2608 xdiff = (proposed->right - proposed->left) - (wr.right - wr.left);
2609 ydiff = (proposed->bottom - proposed->top) - (wr.bottom - wr.top);
2612 /* These next four lines work around the fact that midend_size
2613 * is happy to shrink _but not grow_ if you change one dimension
2614 * but not the other. */
2615 if (xdiff > 0 && ydiff == 0)
2616 ydiff = (xdiff * (wr.right - wr.left)) / (wr.bottom - wr.top);
2617 if (xdiff == 0 && ydiff > 0)
2618 xdiff = (ydiff * (wr.bottom - wr.top)) / (wr.right - wr.left);
2621 if (check_window_resize(fe,
2622 (cr.right - cr.left) + xdiff,
2623 (cr.bottom - cr.top) + ydiff,
2624 &nx, &ny, &wx, &wy, TRUE)) {
2625 new_bitmap(fe, nx, ny);
2626 midend_force_redraw(fe->me);
2628 /* reset size to current window size */
2629 wx = wr.right - wr.left;
2630 wy = wr.bottom - wr.top;
2632 /* Re-fetch rectangle; size limits mean we might not have
2633 * taken it quite to the mouse drag positions. */
2634 GetClientRect(fe->hwnd, &cr);
2635 adjust_statusbar(fe, &cr);
2637 *wx_r = wx; *wy_r = wy;
2640 static void update_type_menu_tick(frontend *fe)
2644 if (fe->typemenu == INVALID_HANDLE_VALUE)
2647 total = GetMenuItemCount(fe->typemenu);
2648 n = midend_which_preset(fe->me);
2650 n = total - 1; /* "Custom" item */
2652 for (i = 0; i < total; i++) {
2653 int flag = (i == n ? MF_CHECKED : MF_UNCHECKED);
2654 CheckMenuItem(fe->typemenu, i, MF_BYPOSITION | flag);
2657 DrawMenuBar(fe->hwnd);
2660 static void new_game_type(frontend *fe)
2662 midend_new_game(fe->me);
2664 update_type_menu_tick(fe);
2667 static int is_alt_pressed(void)
2670 int r = GetKeyboardState(keystate);
2673 if (keystate[VK_MENU] & 0x80)
2675 if (keystate[VK_RMENU] & 0x80)
2680 static void savefile_write(void *wctx, void *buf, int len)
2682 FILE *fp = (FILE *)wctx;
2683 fwrite(buf, 1, len, fp);
2686 static int savefile_read(void *wctx, void *buf, int len)
2688 FILE *fp = (FILE *)wctx;
2691 ret = fread(buf, 1, len, fp);
2692 return (ret == len);
2695 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2696 WPARAM wParam, LPARAM lParam)
2698 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2703 DestroyWindow(hwnd);
2707 /* Numeric pad sends WM_COMMAND messages */
2708 if ((wParam >= IDM_KEYEMUL) && (wParam < IDM_KEYEMUL + 256))
2710 midend_process_key(fe->me, 0, 0, wParam - IDM_KEYEMUL);
2713 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
2716 if (!midend_process_key(fe->me, 0, 0, 'n'))
2720 midend_restart_game(fe->me);
2723 if (!midend_process_key(fe->me, 0, 0, 'u'))
2727 if (!midend_process_key(fe->me, 0, 0, '\x12'))
2732 char *text = midend_text_format(fe->me);
2734 write_clip(hwnd, text);
2736 MessageBeep(MB_ICONWARNING);
2742 char *msg = midend_solve(fe->me);
2744 MessageBox(hwnd, msg, "Unable to solve",
2745 MB_ICONERROR | MB_OK);
2749 if (!midend_process_key(fe->me, 0, 0, 'q'))
2753 if (get_config(fe, CFG_SETTINGS))
2757 if (get_config(fe, CFG_SEED))
2761 if (get_config(fe, CFG_DESC))
2765 if (get_config(fe, CFG_PRINT))
2775 char filename[FILENAME_MAX];
2778 memset(&of, 0, sizeof(of));
2779 of.hwndOwner = hwnd;
2780 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
2781 of.lpstrCustomFilter = NULL;
2782 of.nFilterIndex = 1;
2783 of.lpstrFile = filename;
2785 of.nMaxFile = lenof(filename);
2786 of.lpstrFileTitle = NULL;
2787 of.lpstrTitle = (cmd == IDM_SAVE ?
2788 "Enter name of game file to save" :
2789 "Enter name of saved game file to load");
2791 #ifdef OPENFILENAME_SIZE_VERSION_400
2792 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2794 of.lStructSize = sizeof(of);
2796 of.lpstrInitialDir = NULL;
2798 if (cmd == IDM_SAVE)
2799 ret = GetSaveFileName(&of);
2801 ret = GetOpenFileName(&of);
2804 if (cmd == IDM_SAVE) {
2807 if ((fp = fopen(filename, "r")) != NULL) {
2808 char buf[256 + FILENAME_MAX];
2812 sprintf(buf, "Are you sure you want to overwrite"
2813 " the file \"%.*s\"?",
2814 FILENAME_MAX, filename);
2815 if (MessageBox(hwnd, buf, "Question",
2816 MB_YESNO | MB_ICONQUESTION)
2821 fp = fopen(filename, "w");
2824 MessageBox(hwnd, "Unable to open save file",
2825 "Error", MB_ICONERROR | MB_OK);
2829 midend_serialise(fe->me, savefile_write, fp);
2833 FILE *fp = fopen(filename, "r");
2837 MessageBox(hwnd, "Unable to open saved game file",
2838 "Error", MB_ICONERROR | MB_OK);
2842 err = midend_deserialise(fe->me, savefile_read, fp);
2847 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
2859 start_help(fe, NULL);
2862 start_help(fe, help_topic);
2867 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
2869 if (p >= 0 && p < fe->npresets) {
2870 midend_set_params(fe->me, fe->presets[p]);
2890 hdc = BeginPaint(hwnd, &p);
2891 hdc2 = CreateCompatibleDC(hdc);
2892 prevbm = SelectObject(hdc2, fe->bitmap);
2894 FillRect(hdc, &(p.rcPaint), (HBRUSH) GetStockObject(WHITE_BRUSH));
2896 IntersectRect(&rcDest, &(fe->bitmapPosition), &(p.rcPaint));
2898 rcDest.left, rcDest.top,
2899 rcDest.right - rcDest.left,
2900 rcDest.bottom - rcDest.top,
2902 rcDest.left - fe->bitmapPosition.left,
2903 rcDest.top - fe->bitmapPosition.top,
2905 SelectObject(hdc2, prevbm);
2914 int r = GetKeyboardState(keystate);
2915 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
2916 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
2920 if (!(lParam & 0x01000000))
2921 key = MOD_NUM_KEYPAD | '4';
2923 key = shift | ctrl | CURSOR_LEFT;
2926 if (!(lParam & 0x01000000))
2927 key = MOD_NUM_KEYPAD | '6';
2929 key = shift | ctrl | CURSOR_RIGHT;
2932 if (!(lParam & 0x01000000))
2933 key = MOD_NUM_KEYPAD | '8';
2935 key = shift | ctrl | CURSOR_UP;
2938 if (!(lParam & 0x01000000))
2939 key = MOD_NUM_KEYPAD | '2';
2941 key = shift | ctrl | CURSOR_DOWN;
2944 * Diagonal keys on the numeric keypad.
2947 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
2950 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
2953 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
2956 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
2959 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
2962 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
2965 * Numeric keypad keys with Num Lock on.
2967 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
2968 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
2969 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
2970 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
2971 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
2972 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
2973 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
2974 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
2975 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
2976 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
2980 if (!midend_process_key(fe->me, 0, 0, key))
2985 m.message = WM_KEYDOWN;
2987 m.lParam = lParam & 0xdfff;
2988 TranslateMessage(&m);
2992 case WM_LBUTTONDOWN:
2993 case WM_RBUTTONDOWN:
2994 case WM_MBUTTONDOWN:
2999 * Shift-clicks count as middle-clicks, since otherwise
3000 * two-button Windows users won't have any kind of
3001 * middle click to use.
3003 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
3004 button = MIDDLE_BUTTON;
3005 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
3006 button = RIGHT_BUTTON;
3009 button = LEFT_BUTTON;
3011 if ((thegame.flags & REQUIRE_RBUTTON) == 0)
3012 button = LEFT_BUTTON;
3017 shrgi.cbSize = sizeof(SHRGINFO);
3018 shrgi.hwndClient = hwnd;
3019 shrgi.ptDown.x = (signed short)LOWORD(lParam);
3020 shrgi.ptDown.y = (signed short)HIWORD(lParam);
3021 shrgi.dwFlags = SHRG_RETURNCMD;
3023 if (GN_CONTEXTMENU == SHRecognizeGesture(&shrgi))
3024 button = RIGHT_BUTTON;
3026 button = LEFT_BUTTON;
3030 if (!midend_process_key(fe->me,
3031 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3032 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3046 * Shift-clicks count as middle-clicks, since otherwise
3047 * two-button Windows users won't have any kind of
3048 * middle click to use.
3050 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
3051 button = MIDDLE_RELEASE;
3052 else if (message == WM_RBUTTONUP || is_alt_pressed())
3053 button = RIGHT_RELEASE;
3055 button = LEFT_RELEASE;
3057 if (!midend_process_key(fe->me,
3058 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3059 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3070 if (wParam & (MK_MBUTTON | MK_SHIFT))
3071 button = MIDDLE_DRAG;
3072 else if (wParam & MK_RBUTTON || is_alt_pressed())
3073 button = RIGHT_DRAG;
3077 if (!midend_process_key(fe->me,
3078 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3079 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3085 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
3090 DWORD now = GetTickCount();
3091 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
3092 midend_timer(fe->me, elapsed);
3093 fe->timer_last_tickcount = now;
3099 RECT *sr = (RECT *)lParam;
3100 int wx, wy, isedge = 0;
3102 if (wParam == WMSZ_TOP ||
3103 wParam == WMSZ_RIGHT ||
3104 wParam == WMSZ_BOTTOM ||
3105 wParam == WMSZ_LEFT) isedge = 1;
3106 adjust_game_size(fe, sr, isedge, &wx, &wy);
3108 /* Given the window size the puzzles constrain
3109 * us to, work out which edge we should be moving. */
3110 if (wParam == WMSZ_TOP ||
3111 wParam == WMSZ_TOPLEFT ||
3112 wParam == WMSZ_TOPRIGHT) {
3113 sr->top = sr->bottom - wy;
3115 sr->bottom = sr->top + wy;
3117 if (wParam == WMSZ_LEFT ||
3118 wParam == WMSZ_TOPLEFT ||
3119 wParam == WMSZ_BOTTOMLEFT) {
3120 sr->left = sr->right - wx;
3122 sr->right = sr->left + wx;
3130 return DefWindowProc(hwnd, message, wParam, lParam);
3134 static int FindPreviousInstance()
3136 /* Check if application is running. If it's running then focus on the window */
3137 HWND hOtherWnd = NULL;
3139 hOtherWnd = FindWindow (wGameName, wGameName);
3142 SetForegroundWindow (hOtherWnd);
3150 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
3156 MultiByteToWideChar (CP_ACP, 0, thegame.name, -1, wGameName, 256);
3157 if (FindPreviousInstance ())
3161 InitCommonControls();
3167 wndclass.lpfnWndProc = WndProc;
3168 wndclass.cbClsExtra = 0;
3169 wndclass.cbWndExtra = 0;
3170 wndclass.hInstance = inst;
3171 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
3173 if (!wndclass.hIcon) /* in case resource file is absent */
3174 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
3176 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
3177 wndclass.hbrBackground = NULL;
3178 wndclass.lpszMenuName = NULL;
3180 wndclass.lpszClassName = wGameName;
3182 wndclass.lpszClassName = thegame.name;
3185 RegisterClass(&wndclass);
3188 while (*cmdline && isspace((unsigned char)*cmdline))
3193 if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
3195 sprintf(buf, "%.100s Error", thegame.name);
3196 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
3200 while (GetMessage(&msg, NULL, 0, 0)) {
3201 DispatchMessage(&msg);