2 * windows.c: Windows front end for my puzzle collection.
18 #define IDM_NEW 0x0010
19 #define IDM_RESTART 0x0020
20 #define IDM_UNDO 0x0030
21 #define IDM_REDO 0x0040
22 #define IDM_COPY 0x0050
23 #define IDM_SOLVE 0x0060
24 #define IDM_QUIT 0x0070
25 #define IDM_CONFIG 0x0080
26 #define IDM_DESC 0x0090
27 #define IDM_SEED 0x00A0
28 #define IDM_HELPC 0x00B0
29 #define IDM_GAMEHELP 0x00C0
30 #define IDM_ABOUT 0x00D0
31 #define IDM_SAVE 0x00E0
32 #define IDM_LOAD 0x00F0
33 #define IDM_PRINT 0x0100
34 #define IDM_PRESETS 0x0110
36 #define HELP_FILE_NAME "puzzles.hlp"
37 #define HELP_CNT_NAME "puzzles.cnt"
40 static FILE *debug_fp = NULL;
41 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
42 static int debug_got_console = 0;
48 if (!debug_got_console) {
50 debug_got_console = 1;
51 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
55 debug_fp = fopen("debug.log", "w");
58 if (debug_hdl != INVALID_HANDLE_VALUE) {
59 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
65 void debug_printf(char *fmt, ...)
71 vsprintf(buf, fmt, ap);
93 enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
97 HWND hwnd, statusbar, cfgbox;
99 HBITMAP bitmap, prevbm;
106 DWORD timer_last_tickcount;
108 game_params **presets;
110 int nfonts, fontsize;
112 struct cfg_aux *cfgaux;
113 int cfg_which, dlg_done;
118 int help_has_contents;
120 enum { DRAWING, PRINTING, NOTHING } drawstatus;
122 int printcount, printw, printh, printsolns, printcurr, printcolour;
124 int printoffsetx, printoffsety;
125 float printpixelscale;
131 void fatal(char *fmt, ...)
137 vsprintf(buf, fmt, ap);
140 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
145 char *geterrstr(void)
148 DWORD dw = GetLastError();
152 FORMAT_MESSAGE_ALLOCATE_BUFFER |
153 FORMAT_MESSAGE_FROM_SYSTEM,
156 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
160 ret = dupstr(lpMsgBuf);
167 void get_random_seed(void **randseed, int *randseedsize)
169 time_t *tp = snew(time_t);
171 *randseed = (void *)tp;
172 *randseedsize = sizeof(time_t);
175 static void win_status_bar(void *handle, char *text)
177 frontend *fe = (frontend *)handle;
180 rewritten = midend_rewrite_statusbar(fe->me, text);
181 if (!fe->laststatus || strcmp(rewritten, fe->laststatus)) {
182 SetWindowText(fe->statusbar, rewritten);
183 sfree(fe->laststatus);
184 fe->laststatus = rewritten;
190 static blitter *win_blitter_new(void *handle, int w, int h)
192 blitter *bl = snew(blitter);
194 memset(bl, 0, sizeof(blitter));
202 static void win_blitter_free(void *handle, blitter *bl)
204 if (bl->bitmap) DeleteObject(bl->bitmap);
208 static void blitter_mkbitmap(frontend *fe, blitter *bl)
210 HDC hdc = GetDC(fe->hwnd);
211 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
212 ReleaseDC(fe->hwnd, hdc);
215 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
217 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
219 frontend *fe = (frontend *)handle;
220 HDC hdc_win, hdc_blit;
223 assert(fe->drawstatus == DRAWING);
225 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
227 bl->x = x; bl->y = y;
229 hdc_win = GetDC(fe->hwnd);
230 hdc_blit = CreateCompatibleDC(hdc_win);
231 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
233 prev_blit = SelectObject(hdc_blit, bl->bitmap);
234 if (prev_blit == NULL || prev_blit == HGDI_ERROR)
235 fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
237 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
238 fe->hdc, x, y, SRCCOPY))
239 fatal("BitBlt failed: 0x%x", GetLastError());
241 SelectObject(hdc_blit, prev_blit);
243 ReleaseDC(fe->hwnd, hdc_win);
246 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
248 frontend *fe = (frontend *)handle;
249 HDC hdc_win, hdc_blit;
252 assert(fe->drawstatus == DRAWING);
254 assert(bl->bitmap); /* we should always have saved before loading */
256 if (x == BLITTER_FROMSAVED) x = bl->x;
257 if (y == BLITTER_FROMSAVED) y = bl->y;
259 hdc_win = GetDC(fe->hwnd);
260 hdc_blit = CreateCompatibleDC(hdc_win);
262 prev_blit = SelectObject(hdc_blit, bl->bitmap);
264 BitBlt(fe->hdc, x, y, bl->w, bl->h,
265 hdc_blit, 0, 0, SRCCOPY);
267 SelectObject(hdc_blit, prev_blit);
269 ReleaseDC(fe->hwnd, hdc_win);
272 void frontend_default_colour(frontend *fe, float *output)
274 DWORD c = GetSysColor(COLOR_MENU); /* ick */
276 output[0] = (float)(GetRValue(c) / 255.0);
277 output[1] = (float)(GetGValue(c) / 255.0);
278 output[2] = (float)(GetBValue(c) / 255.0);
281 static POINT win_transform_point(frontend *fe, int x, int y)
285 assert(fe->drawstatus != NOTHING);
287 if (fe->drawstatus == PRINTING) {
288 ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
289 ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
298 static void win_text_colour(frontend *fe, int colour)
300 assert(fe->drawstatus != NOTHING);
302 if (fe->drawstatus == PRINTING) {
305 print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
307 SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
309 SetTextColor(fe->hdc,
310 hatch == HATCH_CLEAR ? RGB(255,255,255) : RGB(0,0,0));
312 SetTextColor(fe->hdc, fe->colours[colour]);
316 static void win_set_brush(frontend *fe, int colour)
319 assert(fe->drawstatus != NOTHING);
321 if (fe->drawstatus == PRINTING) {
324 print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
327 br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
328 else if (hatch == HATCH_SOLID)
329 br = CreateSolidBrush(RGB(0,0,0));
330 else if (hatch == HATCH_CLEAR)
331 br = CreateSolidBrush(RGB(255,255,255));
333 br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
334 hatch == HATCH_SLASH ? HS_BDIAGONAL :
335 hatch == HATCH_HORIZ ? HS_HORIZONTAL :
336 hatch == HATCH_VERT ? HS_VERTICAL :
337 hatch == HATCH_PLUS ? HS_CROSS :
338 /* hatch == HATCH_X ? */ HS_DIAGCROSS,
341 br = fe->brushes[colour];
343 fe->oldbr = SelectObject(fe->hdc, br);
346 static void win_reset_brush(frontend *fe)
350 assert(fe->drawstatus != NOTHING);
352 br = SelectObject(fe->hdc, fe->oldbr);
353 if (fe->drawstatus == PRINTING)
357 static void win_set_pen(frontend *fe, int colour, int thin)
360 assert(fe->drawstatus != NOTHING);
362 if (fe->drawstatus == PRINTING) {
365 int width = thin ? 0 : fe->linewidth;
367 print_get_colour(fe->dr, colour, &hatch, &r, &g, &b);
369 pen = CreatePen(PS_SOLID, width,
370 RGB(r * 255, g * 255, b * 255));
371 else if (hatch == HATCH_SOLID)
372 pen = CreatePen(PS_SOLID, width, RGB(0, 0, 0));
373 else if (hatch == HATCH_CLEAR)
374 pen = CreatePen(PS_SOLID, width, RGB(255,255,255));
376 assert(!"This shouldn't happen");
377 pen = CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
380 pen = fe->pens[colour];
382 fe->oldpen = SelectObject(fe->hdc, pen);
385 static void win_reset_pen(frontend *fe)
389 assert(fe->drawstatus != NOTHING);
391 pen = SelectObject(fe->hdc, fe->oldpen);
392 if (fe->drawstatus == PRINTING)
396 static void win_clip(void *handle, int x, int y, int w, int h)
398 frontend *fe = (frontend *)handle;
401 if (fe->drawstatus == NOTHING)
404 p = win_transform_point(fe, x, y);
405 q = win_transform_point(fe, x+w, y+h);
406 IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
409 static void win_unclip(void *handle)
411 frontend *fe = (frontend *)handle;
413 if (fe->drawstatus == NOTHING)
416 SelectClipRgn(fe->hdc, NULL);
419 static void win_draw_text(void *handle, int x, int y, int fonttype,
420 int fontsize, int align, int colour, char *text)
422 frontend *fe = (frontend *)handle;
426 if (fe->drawstatus == NOTHING)
429 if (fe->drawstatus == PRINTING)
430 fontsize = (int)(fontsize * fe->printpixelscale);
432 xy = win_transform_point(fe, x, y);
435 * Find or create the font.
437 for (i = fe->fontstart; i < fe->nfonts; i++)
438 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
441 if (i == fe->nfonts) {
442 if (fe->fontsize <= fe->nfonts) {
443 fe->fontsize = fe->nfonts + 10;
444 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
449 fe->fonts[i].type = fonttype;
450 fe->fonts[i].size = fontsize;
452 fe->fonts[i].font = CreateFont(-fontsize, 0, 0, 0,
453 fe->drawstatus == PRINTING ? 0 : FW_BOLD,
454 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
455 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
457 (fonttype == FONT_FIXED ?
458 FIXED_PITCH | FF_DONTCARE :
459 VARIABLE_PITCH | FF_SWISS),
464 * Position and draw the text.
471 oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
472 if (GetTextMetrics(fe->hdc, &tm)) {
473 if (align & ALIGN_VCENTRE)
474 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
478 if (GetTextExtentPoint32(fe->hdc, text, strlen(text), &size)) {
479 if (align & ALIGN_HCENTRE)
481 else if (align & ALIGN_HRIGHT)
484 SetBkMode(fe->hdc, TRANSPARENT);
485 win_text_colour(fe, colour);
486 TextOut(fe->hdc, xy.x, xy.y, text, strlen(text));
487 SelectObject(fe->hdc, oldfont);
491 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
493 frontend *fe = (frontend *)handle;
496 if (fe->drawstatus == NOTHING)
499 if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
501 * Rectangle() appears to get uppity if asked to draw a 1x1
502 * rectangle, presumably on the grounds that that's beneath
503 * its dignity and you ought to be using SetPixel instead.
506 SetPixel(fe->hdc, x, y, fe->colours[colour]);
508 win_set_brush(fe, colour);
509 win_set_pen(fe, colour, TRUE);
510 p = win_transform_point(fe, x, y);
511 q = win_transform_point(fe, x+w, y+h);
512 Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
518 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
520 frontend *fe = (frontend *)handle;
523 if (fe->drawstatus == NOTHING)
526 win_set_pen(fe, colour, FALSE);
527 p = win_transform_point(fe, x1, y1);
528 q = win_transform_point(fe, x2, y2);
529 MoveToEx(fe->hdc, p.x, p.y, NULL);
530 LineTo(fe->hdc, q.x, q.y);
531 if (fe->drawstatus == DRAWING)
532 SetPixel(fe->hdc, q.x, q.y, fe->colours[colour]);
536 static void win_draw_circle(void *handle, int cx, int cy, int radius,
537 int fillcolour, int outlinecolour)
539 frontend *fe = (frontend *)handle;
542 assert(outlinecolour >= 0);
544 if (fe->drawstatus == NOTHING)
547 if (fillcolour >= 0) {
548 win_set_brush(fe, fillcolour);
549 win_set_pen(fe, outlinecolour, FALSE);
550 p = win_transform_point(fe, cx - radius, cy - radius);
551 q = win_transform_point(fe, cx + radius, cy + radius);
552 Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
556 win_set_pen(fe, outlinecolour, FALSE);
557 p = win_transform_point(fe, cx - radius, cy - radius);
558 q = win_transform_point(fe, cx + radius, cy + radius);
559 r = win_transform_point(fe, cx - radius, cy);
560 Arc(fe->hdc, p.x, p.y, q.x+1, q.y+1, r.x, r.y, r.x, r.y);
565 static void win_draw_polygon(void *handle, int *coords, int npoints,
566 int fillcolour, int outlinecolour)
568 frontend *fe = (frontend *)handle;
572 if (fe->drawstatus == NOTHING)
575 pts = snewn(npoints+1, POINT);
577 for (i = 0; i <= npoints; i++) {
578 int j = (i < npoints ? i : 0);
579 pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
582 assert(outlinecolour >= 0);
584 if (fillcolour >= 0) {
585 win_set_brush(fe, fillcolour);
586 win_set_pen(fe, outlinecolour, FALSE);
587 Polygon(fe->hdc, pts, npoints);
591 win_set_pen(fe, outlinecolour, FALSE);
592 Polyline(fe->hdc, pts, npoints+1);
599 static void win_start_draw(void *handle)
601 frontend *fe = (frontend *)handle;
604 assert(fe->drawstatus == NOTHING);
606 hdc_win = GetDC(fe->hwnd);
607 fe->hdc = CreateCompatibleDC(hdc_win);
608 fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
609 ReleaseDC(fe->hwnd, hdc_win);
611 SetMapMode(fe->hdc, MM_TEXT);
612 fe->drawstatus = DRAWING;
615 static void win_draw_update(void *handle, int x, int y, int w, int h)
617 frontend *fe = (frontend *)handle;
620 if (fe->drawstatus != DRAWING)
628 InvalidateRect(fe->hwnd, &r, FALSE);
631 static void win_end_draw(void *handle)
633 frontend *fe = (frontend *)handle;
634 assert(fe->drawstatus == DRAWING);
635 SelectObject(fe->hdc, fe->prevbm);
638 DeleteObject(fe->clip);
641 fe->drawstatus = NOTHING;
644 static void win_line_width(void *handle, float width)
646 frontend *fe = (frontend *)handle;
648 assert(fe->drawstatus != DRAWING);
649 if (fe->drawstatus == NOTHING)
652 fe->linewidth = (int)(width * fe->printpixelscale);
655 static void win_begin_doc(void *handle, int pages)
657 frontend *fe = (frontend *)handle;
659 assert(fe->drawstatus != DRAWING);
660 if (fe->drawstatus == NOTHING)
663 if (StartDoc(fe->hdc, &fe->di) <= 0) {
664 char *e = geterrstr();
665 MessageBox(fe->hwnd, e, "Error starting to print",
666 MB_ICONERROR | MB_OK);
668 fe->drawstatus = NOTHING;
672 * Push a marker on the font stack so that we won't use the
673 * same fonts for printing and drawing. (This is because
674 * drawing seems to look generally better in bold, but printing
675 * is better not in bold.)
677 fe->fontstart = fe->nfonts;
680 static void win_begin_page(void *handle, int number)
682 frontend *fe = (frontend *)handle;
684 assert(fe->drawstatus != DRAWING);
685 if (fe->drawstatus == NOTHING)
688 if (StartPage(fe->hdc) <= 0) {
689 char *e = geterrstr();
690 MessageBox(fe->hwnd, e, "Error starting a page",
691 MB_ICONERROR | MB_OK);
693 fe->drawstatus = NOTHING;
697 static void win_begin_puzzle(void *handle, float xm, float xc,
698 float ym, float yc, int pw, int ph, float wmm)
700 frontend *fe = (frontend *)handle;
701 int ppw, pph, pox, poy;
702 float mmpw, mmph, mmox, mmoy;
705 assert(fe->drawstatus != DRAWING);
706 if (fe->drawstatus == NOTHING)
709 ppw = GetDeviceCaps(fe->hdc, HORZRES);
710 pph = GetDeviceCaps(fe->hdc, VERTRES);
711 mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
712 mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
715 * Compute the puzzle's position on the logical page.
717 mmox = xm * mmpw + xc;
718 mmoy = ym * mmph + yc;
721 * Work out what that comes to in pixels.
723 pox = (int)(mmox * (float)ppw / mmpw);
724 poy = (int)(mmoy * (float)ppw / mmpw);
727 * And determine the scale.
729 * I need a scale such that the maximum puzzle-coordinate
730 * extent of the rectangle (pw * scale) is equal to the pixel
731 * equivalent of the puzzle's millimetre width (wmm * ppw /
734 scale = (wmm * ppw) / (mmpw * pw);
737 * Now store pox, poy and scale for use in the main drawing
740 fe->printoffsetx = pox;
741 fe->printoffsety = poy;
742 fe->printpixelscale = scale;
747 static void win_end_puzzle(void *handle)
749 /* Nothing needs to be done here. */
752 static void win_end_page(void *handle, int number)
754 frontend *fe = (frontend *)handle;
756 assert(fe->drawstatus != DRAWING);
758 if (fe->drawstatus == NOTHING)
761 if (EndPage(fe->hdc) <= 0) {
762 char *e = geterrstr();
763 MessageBox(fe->hwnd, e, "Error finishing a page",
764 MB_ICONERROR | MB_OK);
766 fe->drawstatus = NOTHING;
770 static void win_end_doc(void *handle)
772 frontend *fe = (frontend *)handle;
774 assert(fe->drawstatus != DRAWING);
777 * Free all the fonts created since we began printing.
779 while (fe->nfonts > fe->fontstart) {
781 DeleteObject(fe->fonts[fe->nfonts].font);
786 * The MSDN web site sample code doesn't bother to call EndDoc
787 * if an error occurs half way through printing. I expect doing
788 * so would cause the erroneous document to actually be
789 * printed, or something equally undesirable.
791 if (fe->drawstatus == NOTHING)
794 if (EndDoc(fe->hdc) <= 0) {
795 char *e = geterrstr();
796 MessageBox(fe->hwnd, e, "Error finishing printing",
797 MB_ICONERROR | MB_OK);
799 fe->drawstatus = NOTHING;
803 const struct drawing_api win_drawing = {
828 void print(frontend *fe)
833 midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
838 * Create our document structure and fill it up with puzzles.
840 doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
841 for (i = 0; i < fe->printcount; i++) {
842 if (i == 0 && fe->printcurr) {
843 err = midend_print_puzzle(fe->me, doc, fe->printsolns);
848 nme = midend_new(NULL, &thegame, NULL, NULL);
851 * Set the non-interactive mid-end to have the same
852 * parameters as the standard one.
854 params = midend_get_params(fe->me);
855 midend_set_params(nme, params);
856 thegame.free_params(params);
859 midend_new_game(nme);
860 err = midend_print_puzzle(nme, doc, fe->printsolns);
869 MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
870 MB_ICONERROR | MB_OK);
875 memset(&pd, 0, sizeof(pd));
876 pd.lStructSize = sizeof(pd);
877 pd.hwndOwner = fe->hwnd;
880 pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
881 PD_NOPAGENUMS | PD_NOSELECTION;
883 pd.nFromPage = pd.nToPage = 0xFFFF;
884 pd.nMinPage = pd.nMaxPage = 1;
886 if (!PrintDlg(&pd)) {
892 * Now pd.hDC is a device context for the printer.
896 * FIXME: IWBNI we put up an Abort box here.
899 memset(&fe->di, 0, sizeof(fe->di));
900 fe->di.cbSize = sizeof(fe->di);
901 sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
902 " Portable Puzzle Collection)", thegame.name);
903 fe->di.lpszDocName = doctitle;
904 fe->di.lpszOutput = NULL;
905 fe->di.lpszDatatype = NULL;
908 fe->drawstatus = PRINTING;
911 fe->dr = drawing_init(&win_drawing, fe);
912 document_print(doc, fe->dr);
913 drawing_free(fe->dr);
916 fe->drawstatus = NOTHING;
922 void deactivate_timer(frontend *fe)
925 return; /* for non-interactive midend */
926 if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
930 void activate_timer(frontend *fe)
933 return; /* for non-interactive midend */
935 fe->timer = SetTimer(fe->hwnd, fe->timer, 20, NULL);
936 fe->timer_last_tickcount = GetTickCount();
940 void write_clip(HWND hwnd, char *data)
948 * Windows expects CRLF in the clipboard, so we must convert
949 * any \n that has come out of the puzzle backend.
952 for (i = 0; data[i]; i++) {
957 data2 = snewn(len+1, char);
959 for (i = 0; data[i]; i++) {
962 data2[j++] = data[i];
967 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
970 lock = GlobalLock(clipdata);
973 memcpy(lock, data2, len);
974 ((unsigned char *) lock)[len] = 0;
975 GlobalUnlock(clipdata);
977 if (OpenClipboard(hwnd)) {
979 SetClipboardData(CF_TEXT, clipdata);
982 GlobalFree(clipdata);
988 * See if we can find a help file.
990 static void find_help_file(frontend *fe)
992 char b[2048], *p, *q, *r;
994 if (!fe->help_path) {
995 GetModuleFileName(NULL, b, sizeof(b) - 1);
997 p = strrchr(b, '\\');
998 if (p && p >= r) r = p+1;
1000 if (q && q >= r) r = q+1;
1001 strcpy(r, HELP_FILE_NAME);
1002 if ( (fp = fopen(b, "r")) != NULL) {
1003 fe->help_path = dupstr(b);
1006 fe->help_path = NULL;
1007 strcpy(r, HELP_CNT_NAME);
1008 if ( (fp = fopen(b, "r")) != NULL) {
1009 fe->help_has_contents = TRUE;
1012 fe->help_has_contents = FALSE;
1016 static void check_window_size(frontend *fe, int *px, int *py)
1021 if (fe->statusbar) {
1023 GetWindowRect(fe->statusbar, &sr);
1024 sy = sr.bottom - sr.top;
1030 * See if we actually got the window size we wanted, and adjust
1031 * the puzzle size if not.
1033 GetClientRect(fe->hwnd, &r);
1034 x = r.right - r.left;
1035 y = r.bottom - r.top - sy;
1036 midend_size(fe->me, &x, &y, FALSE);
1037 if (x != r.right - r.left || y != r.bottom - r.top) {
1039 * Resize the window, now we know what size we _really_
1045 AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
1046 (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED),
1048 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left, r.bottom - r.top,
1049 SWP_NOMOVE | SWP_NOZORDER);
1052 if (fe->statusbar) {
1053 GetClientRect(fe->hwnd, &r);
1054 SetWindowPos(fe->statusbar, NULL, 0, r.bottom-r.top-sy, r.right-r.left,
1062 static frontend *new_window(HINSTANCE inst, char *game_id, char **error)
1069 fe = snew(frontend);
1071 fe->me = midend_new(fe, &thegame, &win_drawing, fe);
1074 *error = midend_game_id(fe->me, game_id);
1076 midend_free(fe->me);
1082 fe->help_path = NULL;
1090 fe->drawstatus = NOTHING;
1094 midend_new_game(fe->me);
1097 fe->nfonts = fe->fontsize = 0;
1099 fe->laststatus = NULL;
1105 colours = midend_colours(fe->me, &ncolours);
1107 fe->colours = snewn(ncolours, COLORREF);
1108 fe->brushes = snewn(ncolours, HBRUSH);
1109 fe->pens = snewn(ncolours, HPEN);
1111 for (i = 0; i < ncolours; i++) {
1112 fe->colours[i] = RGB(255 * colours[i*3+0],
1113 255 * colours[i*3+1],
1114 255 * colours[i*3+2]);
1115 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1116 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1121 x = y = INT_MAX; /* find puzzle's preferred size */
1122 midend_size(fe->me, &x, &y, FALSE);
1127 AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
1128 (WS_THICKFRAME | WS_MAXIMIZEBOX | WS_OVERLAPPED),
1131 fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
1132 WS_OVERLAPPEDWINDOW &~
1133 (WS_THICKFRAME | WS_MAXIMIZEBOX),
1134 CW_USEDEFAULT, CW_USEDEFAULT,
1135 r.right - r.left, r.bottom - r.top,
1136 NULL, NULL, inst, NULL);
1138 if (midend_wants_statusbar(fe->me)) {
1140 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, "ooh",
1141 WS_CHILD | WS_VISIBLE,
1142 0, 0, 0, 0, /* status bar does these */
1143 fe->hwnd, NULL, inst, NULL);
1145 * Now resize the window to take account of the status bar.
1147 GetWindowRect(fe->statusbar, &sr);
1148 GetWindowRect(fe->hwnd, &r);
1149 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1150 r.bottom - r.top + sr.bottom - sr.top,
1151 SWP_NOMOVE | SWP_NOZORDER);
1153 fe->statusbar = NULL;
1157 HMENU bar = CreateMenu();
1158 HMENU menu = CreateMenu();
1160 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Game");
1161 AppendMenu(menu, MF_ENABLED, IDM_NEW, "New");
1162 AppendMenu(menu, MF_ENABLED, IDM_RESTART, "Restart");
1163 AppendMenu(menu, MF_ENABLED, IDM_DESC, "Specific...");
1164 AppendMenu(menu, MF_ENABLED, IDM_SEED, "Random Seed...");
1166 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1167 thegame.can_configure) {
1168 HMENU sub = CreateMenu();
1171 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "Type");
1173 fe->presets = snewn(fe->npresets, game_params *);
1175 for (i = 0; i < fe->npresets; i++) {
1178 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1181 * FIXME: we ought to go through and do something
1182 * with ampersands here.
1185 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1188 if (thegame.can_configure) {
1189 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, "Custom...");
1193 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1194 AppendMenu(menu, MF_ENABLED, IDM_LOAD, "Load");
1195 AppendMenu(menu, MF_ENABLED, IDM_SAVE, "Save");
1196 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1197 if (thegame.can_print) {
1198 AppendMenu(menu, MF_ENABLED, IDM_PRINT, "Print");
1199 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1201 AppendMenu(menu, MF_ENABLED, IDM_UNDO, "Undo");
1202 AppendMenu(menu, MF_ENABLED, IDM_REDO, "Redo");
1203 if (thegame.can_format_as_text) {
1204 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1205 AppendMenu(menu, MF_ENABLED, IDM_COPY, "Copy");
1207 if (thegame.can_solve) {
1208 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1209 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, "Solve");
1211 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1212 AppendMenu(menu, MF_ENABLED, IDM_QUIT, "Exit");
1213 menu = CreateMenu();
1214 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "Help");
1215 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, "About");
1216 if (fe->help_path) {
1217 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1218 AppendMenu(menu, MF_ENABLED, IDM_HELPC, "Contents");
1219 if (thegame.winhelp_topic) {
1221 assert(thegame.name);
1222 item = snewn(9+strlen(thegame.name), char); /*ick*/
1223 sprintf(item, "Help on %s", thegame.name);
1224 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1228 SetMenu(fe->hwnd, bar);
1231 check_window_size(fe, &x, &y);
1233 hdc = GetDC(fe->hwnd);
1234 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
1235 ReleaseDC(fe->hwnd, hdc);
1237 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1239 ShowWindow(fe->hwnd, SW_NORMAL);
1240 SetForegroundWindow(fe->hwnd);
1242 midend_redraw(fe->me);
1247 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1248 WPARAM wParam, LPARAM lParam)
1250 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1257 if ((HIWORD(wParam) == BN_CLICKED ||
1258 HIWORD(wParam) == BN_DOUBLECLICKED) &&
1259 LOWORD(wParam) == IDOK)
1272 * Wrappers on midend_{get,set}_config, which extend the CFG_*
1273 * enumeration to add CFG_PRINT.
1275 static config_item *frontend_get_config(frontend *fe, int which,
1278 if (which < CFG_FRONTEND_SPECIFIC) {
1279 return midend_get_config(fe->me, which, wintitle);
1280 } else if (which == CFG_PRINT) {
1284 *wintitle = snewn(40 + strlen(thegame.name), char);
1285 sprintf(*wintitle, "%s print setup", thegame.name);
1287 ret = snewn(8, config_item);
1291 ret[i].name = "Number of puzzles to print";
1292 ret[i].type = C_STRING;
1293 ret[i].sval = dupstr("1");
1297 ret[i].name = "Number of puzzles across the page";
1298 ret[i].type = C_STRING;
1299 ret[i].sval = dupstr("1");
1303 ret[i].name = "Number of puzzles down the page";
1304 ret[i].type = C_STRING;
1305 ret[i].sval = dupstr("1");
1309 ret[i].name = "Percentage of standard size";
1310 ret[i].type = C_STRING;
1311 ret[i].sval = dupstr("100.0");
1315 ret[i].name = "Include currently shown puzzle";
1316 ret[i].type = C_BOOLEAN;
1321 ret[i].name = "Print solutions";
1322 ret[i].type = C_BOOLEAN;
1324 ret[i].ival = FALSE;
1327 if (thegame.can_print_in_colour) {
1328 ret[i].name = "Print in colour";
1329 ret[i].type = C_BOOLEAN;
1331 ret[i].ival = FALSE;
1336 ret[i].type = C_END;
1343 assert(!"We should never get here");
1348 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
1350 if (which < CFG_FRONTEND_SPECIFIC) {
1351 return midend_set_config(fe->me, which, cfg);
1352 } else if (which == CFG_PRINT) {
1353 if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
1354 return "Number of puzzles to print should be at least one";
1355 if ((fe->printw = atoi(cfg[1].sval)) <= 0)
1356 return "Number of puzzles across the page should be at least one";
1357 if ((fe->printh = atoi(cfg[2].sval)) <= 0)
1358 return "Number of puzzles down the page should be at least one";
1359 if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
1360 return "Print size should be positive";
1361 fe->printcurr = cfg[4].ival;
1362 fe->printsolns = cfg[5].ival;
1363 fe->printcolour = thegame.can_print_in_colour && cfg[6].ival;
1366 assert(!"We should never get here");
1367 return "Internal error";
1371 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
1372 WPARAM wParam, LPARAM lParam)
1374 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1384 * OK and Cancel are special cases.
1386 if ((HIWORD(wParam) == BN_CLICKED ||
1387 HIWORD(wParam) == BN_DOUBLECLICKED) &&
1388 (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
1389 if (LOWORD(wParam) == IDOK) {
1390 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
1393 MessageBox(hwnd, err, "Validation error",
1394 MB_ICONERROR | MB_OK);
1405 * First find the control whose id this is.
1407 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1408 if (j->ctlid == LOWORD(wParam))
1411 if (i->type == C_END)
1412 return 0; /* not our problem */
1414 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
1416 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
1417 buffer[lenof(buffer)-1] = '\0';
1419 i->sval = dupstr(buffer);
1420 } else if (i->type == C_BOOLEAN &&
1421 (HIWORD(wParam) == BN_CLICKED ||
1422 HIWORD(wParam) == BN_DOUBLECLICKED)) {
1423 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
1424 } else if (i->type == C_CHOICES &&
1425 HIWORD(wParam) == CBN_SELCHANGE) {
1426 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
1427 CB_GETCURSEL, 0, 0);
1440 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
1441 char *wclass, int wstyle,
1442 int exstyle, const char *wtext, int wid)
1445 ret = CreateWindowEx(exstyle, wclass, wtext,
1446 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
1447 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
1448 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
1452 static void about(frontend *fe)
1462 int winwidth, winheight, y;
1463 int height, width, maxwid;
1464 const char *strings[16];
1469 sprintf(titlebuf, "About %.250s", thegame.name);
1471 strings[nstrings++] = thegame.name;
1472 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
1473 strings[nstrings++] = ver;
1475 wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1476 wc.lpfnWndProc = DefDlgProc;
1478 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1479 wc.hInstance = fe->inst;
1481 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1482 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1483 wc.lpszMenuName = NULL;
1484 wc.lpszClassName = "GameAboutBox";
1487 hdc = GetDC(fe->hwnd);
1488 SetMapMode(hdc, MM_TEXT);
1490 fe->dlg_done = FALSE;
1492 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1494 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1495 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1500 oldfont = SelectObject(hdc, fe->cfgfont);
1501 if (GetTextMetrics(hdc, &tm)) {
1502 height = tm.tmAscent + tm.tmDescent;
1503 width = tm.tmAveCharWidth;
1505 height = width = 30;
1509 * Figure out the layout of the About box by measuring the
1510 * length of each piece of text.
1513 winheight = height/2;
1515 for (i = 0; i < nstrings; i++) {
1516 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
1517 lengths[i] = size.cx;
1519 lengths[i] = 0; /* *shrug* */
1520 if (maxwid < lengths[i])
1521 maxwid = lengths[i];
1522 winheight += height * 3 / 2 + (height / 2);
1525 winheight += height + height * 7 / 4; /* OK button */
1526 winwidth = maxwid + 4*width;
1528 SelectObject(hdc, oldfont);
1529 ReleaseDC(fe->hwnd, hdc);
1532 * Create the dialog, now that we know its size.
1539 r.bottom = winheight;
1541 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1542 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1543 WS_CAPTION | WS_SYSMENU*/) &~
1544 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1548 * Centre the dialog on its parent window.
1552 GetWindowRect(fe->hwnd, &r2);
1553 r.left = (r2.left + r2.right - r.right) / 2;
1554 r.top = (r2.top + r2.bottom - r.bottom) / 2;
1558 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
1559 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1560 WS_CAPTION | WS_SYSMENU,
1562 r.right-r.left, r.bottom-r.top,
1563 fe->hwnd, NULL, fe->inst, NULL);
1566 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1568 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1569 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
1573 for (i = 0; i < nstrings; i++) {
1574 int border = width*2 + (maxwid - lengths[i]) / 2;
1575 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
1576 "Static", 0, 0, strings[i], id++);
1579 assert(y < winheight);
1583 y += height/2; /* extra space before OK */
1584 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
1585 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1588 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1590 EnableWindow(fe->hwnd, FALSE);
1591 ShowWindow(fe->cfgbox, SW_NORMAL);
1592 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1593 if (!IsDialogMessage(fe->cfgbox, &msg))
1594 DispatchMessage(&msg);
1598 EnableWindow(fe->hwnd, TRUE);
1599 SetForegroundWindow(fe->hwnd);
1600 DestroyWindow(fe->cfgbox);
1601 DeleteObject(fe->cfgfont);
1604 static int get_config(frontend *fe, int which)
1617 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
1618 int height, width, maxlabel, maxcheckbox;
1620 wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
1621 wc.lpfnWndProc = DefDlgProc;
1623 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
1624 wc.hInstance = fe->inst;
1626 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1627 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
1628 wc.lpszMenuName = NULL;
1629 wc.lpszClassName = "GameConfigBox";
1632 hdc = GetDC(fe->hwnd);
1633 SetMapMode(hdc, MM_TEXT);
1635 fe->dlg_done = FALSE;
1637 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
1639 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
1640 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
1645 oldfont = SelectObject(hdc, fe->cfgfont);
1646 if (GetTextMetrics(hdc, &tm)) {
1647 height = tm.tmAscent + tm.tmDescent;
1648 width = tm.tmAveCharWidth;
1650 height = width = 30;
1653 fe->cfg = frontend_get_config(fe, which, &title);
1654 fe->cfg_which = which;
1657 * Figure out the layout of the config box by measuring the
1658 * length of each piece of text.
1660 maxlabel = maxcheckbox = 0;
1661 winheight = height/2;
1663 for (i = fe->cfg; i->type != C_END; i++) {
1668 * Both these control types have a label filling only
1669 * the left-hand column of the box.
1671 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1674 winheight += height * 3 / 2 + (height / 2);
1679 * Checkboxes take up the whole of the box width.
1681 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
1682 maxcheckbox < size.cx)
1683 maxcheckbox = size.cx;
1684 winheight += height + (height / 2);
1689 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
1692 col1r = col1l + maxlabel;
1693 col2l = col1r + 2*width;
1694 col2r = col2l + 30*width;
1695 if (col2r < col1l+2*height+maxcheckbox)
1696 col2r = col1l+2*height+maxcheckbox;
1697 winwidth = col2r + 2*width;
1699 SelectObject(hdc, oldfont);
1700 ReleaseDC(fe->hwnd, hdc);
1703 * Create the dialog, now that we know its size.
1710 r.bottom = winheight;
1712 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
1713 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1714 WS_CAPTION | WS_SYSMENU*/) &~
1715 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
1719 * Centre the dialog on its parent window.
1723 GetWindowRect(fe->hwnd, &r2);
1724 r.left = (r2.left + r2.right - r.right) / 2;
1725 r.top = (r2.top + r2.bottom - r.bottom) / 2;
1729 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
1730 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
1731 WS_CAPTION | WS_SYSMENU,
1733 r.right-r.left, r.bottom-r.top,
1734 fe->hwnd, NULL, fe->inst, NULL);
1738 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
1740 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
1741 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
1744 * Count the controls so we can allocate cfgaux.
1746 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
1748 fe->cfgaux = snewn(nctrls, struct cfg_aux);
1752 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1756 * Edit box with a label beside it.
1758 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1759 "Static", 0, 0, i->name, id++);
1760 ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
1761 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
1762 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1763 SetWindowText(ctl, i->sval);
1771 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
1772 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
1773 0, i->name, (j->ctlid = id++));
1774 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
1780 * Drop-down list with a label beside it.
1782 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
1783 "STATIC", 0, 0, i->name, id++);
1784 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
1785 "COMBOBOX", WS_TABSTOP |
1786 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
1787 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
1789 char c, *p, *q, *str;
1791 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
1796 while (*q && *q != c) q++;
1797 str = snewn(q-p+1, char);
1798 strncpy(str, p, q-p);
1800 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
1807 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
1813 assert(y < winheight);
1817 y += height/2; /* extra space before OK and Cancel */
1818 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
1819 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
1821 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
1822 BS_PUSHBUTTON | BS_NOTIFY | WS_TABSTOP, 0, "Cancel", IDCANCEL);
1824 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
1826 EnableWindow(fe->hwnd, FALSE);
1827 ShowWindow(fe->cfgbox, SW_NORMAL);
1828 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
1829 if (!IsDialogMessage(fe->cfgbox, &msg))
1830 DispatchMessage(&msg);
1834 EnableWindow(fe->hwnd, TRUE);
1835 SetForegroundWindow(fe->hwnd);
1836 DestroyWindow(fe->cfgbox);
1837 DeleteObject(fe->cfgfont);
1842 return (fe->dlg_done == 2);
1845 static void new_game_size(frontend *fe)
1852 midend_size(fe->me, &x, &y, FALSE);
1857 AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW &~
1858 (WS_THICKFRAME | WS_MAXIMIZEBOX |
1862 if (fe->statusbar != NULL) {
1863 GetWindowRect(fe->statusbar, &sr);
1865 sr.left = sr.right = sr.top = sr.bottom = 0;
1867 SetWindowPos(fe->hwnd, NULL, 0, 0,
1869 r.bottom - r.top + sr.bottom - sr.top,
1870 SWP_NOMOVE | SWP_NOZORDER);
1872 check_window_size(fe, &x, &y);
1874 if (fe->statusbar != NULL)
1875 SetWindowPos(fe->statusbar, NULL, 0, y, x,
1876 sr.bottom - sr.top, SWP_NOZORDER);
1878 DeleteObject(fe->bitmap);
1880 hdc = GetDC(fe->hwnd);
1881 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
1882 ReleaseDC(fe->hwnd, hdc);
1884 midend_redraw(fe->me);
1887 static void new_game_type(frontend *fe)
1889 midend_new_game(fe->me);
1893 static int is_alt_pressed(void)
1896 int r = GetKeyboardState(keystate);
1899 if (keystate[VK_MENU] & 0x80)
1901 if (keystate[VK_RMENU] & 0x80)
1906 static void savefile_write(void *wctx, void *buf, int len)
1908 FILE *fp = (FILE *)wctx;
1909 fwrite(buf, 1, len, fp);
1912 static int savefile_read(void *wctx, void *buf, int len)
1914 FILE *fp = (FILE *)wctx;
1917 ret = fread(buf, 1, len, fp);
1918 return (ret == len);
1921 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1922 WPARAM wParam, LPARAM lParam)
1924 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1929 DestroyWindow(hwnd);
1932 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
1935 if (!midend_process_key(fe->me, 0, 0, 'n'))
1939 midend_restart_game(fe->me);
1942 if (!midend_process_key(fe->me, 0, 0, 'u'))
1946 if (!midend_process_key(fe->me, 0, 0, '\x12'))
1951 char *text = midend_text_format(fe->me);
1953 write_clip(hwnd, text);
1955 MessageBeep(MB_ICONWARNING);
1961 char *msg = midend_solve(fe->me);
1963 MessageBox(hwnd, msg, "Unable to solve",
1964 MB_ICONERROR | MB_OK);
1968 if (!midend_process_key(fe->me, 0, 0, 'q'))
1972 if (get_config(fe, CFG_SETTINGS))
1976 if (get_config(fe, CFG_SEED))
1980 if (get_config(fe, CFG_DESC))
1984 if (get_config(fe, CFG_PRINT))
1994 char filename[FILENAME_MAX];
1997 memset(&of, 0, sizeof(of));
1998 of.hwndOwner = hwnd;
1999 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
2000 of.lpstrCustomFilter = NULL;
2001 of.nFilterIndex = 1;
2002 of.lpstrFile = filename;
2004 of.nMaxFile = lenof(filename);
2005 of.lpstrFileTitle = NULL;
2006 of.lpstrTitle = (cmd == IDM_SAVE ?
2007 "Enter name of game file to save" :
2008 "Enter name of saved game file to load");
2010 #ifdef OPENFILENAME_SIZE_VERSION_400
2011 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2013 of.lStructSize = sizeof(of);
2015 of.lpstrInitialDir = NULL;
2017 if (cmd == IDM_SAVE)
2018 ret = GetSaveFileName(&of);
2020 ret = GetOpenFileName(&of);
2023 if (cmd == IDM_SAVE) {
2026 if ((fp = fopen(filename, "r")) != NULL) {
2027 char buf[256 + FILENAME_MAX];
2031 sprintf(buf, "Are you sure you want to overwrite"
2032 " the file \"%.*s\"?",
2033 FILENAME_MAX, filename);
2034 if (MessageBox(hwnd, buf, "Question",
2035 MB_YESNO | MB_ICONQUESTION)
2040 fp = fopen(filename, "w");
2043 MessageBox(hwnd, "Unable to open save file",
2044 "Error", MB_ICONERROR | MB_OK);
2048 midend_serialise(fe->me, savefile_write, fp);
2052 FILE *fp = fopen(filename, "r");
2056 MessageBox(hwnd, "Unable to open saved game file",
2057 "Error", MB_ICONERROR | MB_OK);
2061 err = midend_deserialise(fe->me, savefile_read, fp);
2066 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
2077 assert(fe->help_path);
2078 WinHelp(hwnd, fe->help_path,
2079 fe->help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
2082 assert(fe->help_path);
2083 assert(thegame.winhelp_topic);
2085 char *cmd = snewn(10+strlen(thegame.winhelp_topic), char);
2086 sprintf(cmd, "JI(`',`%s')", thegame.winhelp_topic);
2087 WinHelp(hwnd, fe->help_path, HELP_COMMAND, (DWORD)cmd);
2093 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
2095 if (p >= 0 && p < fe->npresets) {
2096 midend_set_params(fe->me, fe->presets[p]);
2112 hdc = BeginPaint(hwnd, &p);
2113 hdc2 = CreateCompatibleDC(hdc);
2114 prevbm = SelectObject(hdc2, fe->bitmap);
2116 p.rcPaint.left, p.rcPaint.top,
2117 p.rcPaint.right - p.rcPaint.left,
2118 p.rcPaint.bottom - p.rcPaint.top,
2120 p.rcPaint.left, p.rcPaint.top,
2122 SelectObject(hdc2, prevbm);
2131 int r = GetKeyboardState(keystate);
2132 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
2133 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
2137 if (!(lParam & 0x01000000))
2138 key = MOD_NUM_KEYPAD | '4';
2140 key = shift | ctrl | CURSOR_LEFT;
2143 if (!(lParam & 0x01000000))
2144 key = MOD_NUM_KEYPAD | '6';
2146 key = shift | ctrl | CURSOR_RIGHT;
2149 if (!(lParam & 0x01000000))
2150 key = MOD_NUM_KEYPAD | '8';
2152 key = shift | ctrl | CURSOR_UP;
2155 if (!(lParam & 0x01000000))
2156 key = MOD_NUM_KEYPAD | '2';
2158 key = shift | ctrl | CURSOR_DOWN;
2161 * Diagonal keys on the numeric keypad.
2164 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
2167 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
2170 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
2173 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
2176 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
2179 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
2182 * Numeric keypad keys with Num Lock on.
2184 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
2185 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
2186 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
2187 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
2188 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
2189 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
2190 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
2191 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
2192 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
2193 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
2197 if (!midend_process_key(fe->me, 0, 0, key))
2202 m.message = WM_KEYDOWN;
2204 m.lParam = lParam & 0xdfff;
2205 TranslateMessage(&m);
2209 case WM_LBUTTONDOWN:
2210 case WM_RBUTTONDOWN:
2211 case WM_MBUTTONDOWN:
2216 * Shift-clicks count as middle-clicks, since otherwise
2217 * two-button Windows users won't have any kind of
2218 * middle click to use.
2220 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
2221 button = MIDDLE_BUTTON;
2222 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
2223 button = RIGHT_BUTTON;
2225 button = LEFT_BUTTON;
2227 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2228 (signed short)HIWORD(lParam), button))
2241 * Shift-clicks count as middle-clicks, since otherwise
2242 * two-button Windows users won't have any kind of
2243 * middle click to use.
2245 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
2246 button = MIDDLE_RELEASE;
2247 else if (message == WM_RBUTTONUP || is_alt_pressed())
2248 button = RIGHT_RELEASE;
2250 button = LEFT_RELEASE;
2252 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2253 (signed short)HIWORD(lParam), button))
2263 if (wParam & (MK_MBUTTON | MK_SHIFT))
2264 button = MIDDLE_DRAG;
2265 else if (wParam & MK_RBUTTON || is_alt_pressed())
2266 button = RIGHT_DRAG;
2270 if (!midend_process_key(fe->me, (signed short)LOWORD(lParam),
2271 (signed short)HIWORD(lParam), button))
2276 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
2281 DWORD now = GetTickCount();
2282 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
2283 midend_timer(fe->me, elapsed);
2284 fe->timer_last_tickcount = now;
2289 return DefWindowProc(hwnd, message, wParam, lParam);
2292 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
2297 InitCommonControls();
2303 wndclass.lpfnWndProc = WndProc;
2304 wndclass.cbClsExtra = 0;
2305 wndclass.cbWndExtra = 0;
2306 wndclass.hInstance = inst;
2307 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
2308 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
2309 wndclass.hbrBackground = NULL;
2310 wndclass.lpszMenuName = NULL;
2311 wndclass.lpszClassName = thegame.name;
2313 RegisterClass(&wndclass);
2316 while (*cmdline && isspace((unsigned char)*cmdline))
2319 if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
2321 sprintf(buf, "%.100s Error", thegame.name);
2322 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
2326 while (GetMessage(&msg, NULL, 0, 0)) {
2327 DispatchMessage(&msg);