Keyboard control patch for Solo, from James H.
[sgt-puzzles/ydirson.git] / windows.c
blob6bcf895ed8310130a1e8f1ccb15ef5835d12644b
1 /*
2 * windows.c: Windows front end for my puzzle collection.
3 */
5 #include <windows.h>
6 #include <commctrl.h>
7 #ifndef NO_HTMLHELP
8 #include <htmlhelp.h>
9 #endif /* NO_HTMLHELP */
11 #ifdef _WIN32_WCE
12 #include <commdlg.h>
13 #include <aygshell.h>
14 #endif
16 #include <stdio.h>
17 #include <assert.h>
18 #include <ctype.h>
19 #include <stdarg.h>
20 #include <stdlib.h>
21 #include <limits.h>
22 #include <time.h>
24 #include "puzzles.h"
26 #ifdef _WIN32_WCE
27 #include "resource.h"
28 #endif
30 #define IDM_NEW 0x0010
31 #define IDM_RESTART 0x0020
32 #define IDM_UNDO 0x0030
33 #define IDM_REDO 0x0040
34 #define IDM_COPY 0x0050
35 #define IDM_SOLVE 0x0060
36 #define IDM_QUIT 0x0070
37 #define IDM_CONFIG 0x0080
38 #define IDM_DESC 0x0090
39 #define IDM_SEED 0x00A0
40 #define IDM_HELPC 0x00B0
41 #define IDM_GAMEHELP 0x00C0
42 #define IDM_ABOUT 0x00D0
43 #define IDM_SAVE 0x00E0
44 #define IDM_LOAD 0x00F0
45 #define IDM_PRINT 0x0100
46 #define IDM_PRESETS 0x0110
47 #define IDM_GAMES 0x0300
49 #define IDM_KEYEMUL 0x0400
51 #define HELP_FILE_NAME "puzzles.hlp"
52 #define HELP_CNT_NAME "puzzles.cnt"
53 #ifndef NO_HTMLHELP
54 #define CHM_FILE_NAME "puzzles.chm"
55 #endif /* NO_HTMLHELP */
57 #ifndef NO_HTMLHELP
58 typedef HWND (CALLBACK *htmlhelp_t)(HWND, LPCSTR, UINT, DWORD);
59 static htmlhelp_t htmlhelp;
60 static HINSTANCE hh_dll;
61 #endif /* NO_HTMLHELP */
62 enum { NONE, HLP, CHM } help_type;
63 char *help_path;
64 int help_has_contents;
66 #ifndef FILENAME_MAX
67 #define FILENAME_MAX (260)
68 #endif
70 #ifndef HGDI_ERROR
71 #define HGDI_ERROR ((HANDLE)GDI_ERROR)
72 #endif
74 #ifdef COMBINED
75 #define CLASSNAME "Puzzles"
76 #else
77 #define CLASSNAME thegame.name
78 #endif
80 #ifdef _WIN32_WCE
83 * Wrapper implementations of functions not supplied by the
84 * PocketPC API.
87 #define SHGetSubMenu(hWndMB,ID_MENU) (HMENU)SendMessage((hWndMB), SHCMBM_GETSUBMENU, (WPARAM)0, (LPARAM)ID_MENU)
89 #undef MessageBox
91 int MessageBox(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType)
93 TCHAR wText[2048];
94 TCHAR wCaption[2048];
96 MultiByteToWideChar (CP_ACP, 0, lpText, -1, wText, 2048);
97 MultiByteToWideChar (CP_ACP, 0, lpCaption, -1, wCaption, 2048);
99 return MessageBoxW (hWnd, wText, wCaption, uType);
102 BOOL SetDlgItemTextA(HWND hDlg, int nIDDlgItem, LPCSTR lpString)
104 TCHAR wText[256];
106 MultiByteToWideChar (CP_ACP, 0, lpString, -1, wText, 256);
107 return SetDlgItemTextW(hDlg, nIDDlgItem, wText);
110 LPCSTR getenv(LPCSTR buf)
112 return NULL;
115 BOOL GetKeyboardState(PBYTE pb)
117 return FALSE;
120 static TCHAR wClassName[256], wGameName[256];
122 #endif
124 #ifdef DEBUGGING
125 static FILE *debug_fp = NULL;
126 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
127 static int debug_got_console = 0;
129 void dputs(char *buf)
131 /*DWORD dw;
133 if (!debug_got_console) {
134 if (AllocConsole()) {
135 debug_got_console = 1;
136 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
139 if (!debug_fp) {
140 debug_fp = fopen("debug.log", "w");
143 if (debug_hdl != INVALID_HANDLE_VALUE) {
144 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
146 if (debug_fp) {
147 fputs(buf, debug_fp);
148 fflush(debug_fp);
150 OutputDebugString(buf);
153 void debug_printf(char *fmt, ...)
155 char buf[4096];
156 va_list ap;
158 va_start(ap, fmt);
159 _vsnprintf(buf, 4095, fmt, ap);
160 dputs(buf);
161 va_end(ap);
163 #endif
165 #ifndef _WIN32_WCE
166 #define WINFLAGS (WS_OVERLAPPEDWINDOW &~ \
167 (WS_MAXIMIZEBOX | WS_OVERLAPPED))
168 #else
169 #define WINFLAGS (WS_CAPTION | WS_SYSMENU)
170 #endif
172 static void new_game_size(frontend *fe, float scale);
174 struct font {
175 HFONT font;
176 int type;
177 int size;
180 struct cfg_aux {
181 int ctlid;
184 struct blitter {
185 HBITMAP bitmap;
186 frontend *fe;
187 int x, y, w, h;
190 enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
192 struct frontend {
193 const game *game;
194 midend *me;
195 HWND hwnd, statusbar, cfgbox;
196 #ifdef _WIN32_WCE
197 HWND numpad; /* window handle for the numeric pad */
198 #endif
199 HINSTANCE inst;
200 HBITMAP bitmap, prevbm;
201 RECT bitmapPosition; /* game bitmap position within game window */
202 HDC hdc;
203 COLORREF *colours;
204 HBRUSH *brushes;
205 HPEN *pens;
206 HRGN clip;
207 HMENU gamemenu, typemenu;
208 UINT timer;
209 DWORD timer_last_tickcount;
210 int npresets;
211 game_params **presets;
212 struct font *fonts;
213 int nfonts, fontsize;
214 config_item *cfg;
215 struct cfg_aux *cfgaux;
216 int cfg_which, dlg_done;
217 HFONT cfgfont;
218 HBRUSH oldbr;
219 HPEN oldpen;
220 int help_running;
221 enum { DRAWING, PRINTING, NOTHING } drawstatus;
222 DOCINFO di;
223 int printcount, printw, printh, printsolns, printcurr, printcolour;
224 float printscale;
225 int printoffsetx, printoffsety;
226 float printpixelscale;
227 int fontstart;
228 int linewidth;
229 drawing *dr;
230 int xmin, ymin;
231 float puzz_scale;
234 void frontend_free(frontend *fe)
236 midend_free(fe->me);
238 sfree(fe->colours);
239 sfree(fe->brushes);
240 sfree(fe->pens);
241 sfree(fe->presets);
243 sfree(fe);
246 static void update_type_menu_tick(frontend *fe);
247 static void update_copy_menu_greying(frontend *fe);
249 void fatal(char *fmt, ...)
251 char buf[2048];
252 va_list ap;
254 va_start(ap, fmt);
255 vsprintf(buf, fmt, ap);
256 va_end(ap);
258 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
260 exit(1);
263 char *geterrstr(void)
265 LPVOID lpMsgBuf;
266 DWORD dw = GetLastError();
267 char *ret;
269 FormatMessage(
270 FORMAT_MESSAGE_ALLOCATE_BUFFER |
271 FORMAT_MESSAGE_FROM_SYSTEM,
272 NULL,
274 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
275 (LPTSTR) &lpMsgBuf,
276 0, NULL );
278 ret = dupstr(lpMsgBuf);
280 LocalFree(lpMsgBuf);
282 return ret;
285 void get_random_seed(void **randseed, int *randseedsize)
287 SYSTEMTIME *st = snew(SYSTEMTIME);
289 GetLocalTime(st);
291 *randseed = (void *)st;
292 *randseedsize = sizeof(SYSTEMTIME);
295 static void win_status_bar(void *handle, char *text)
297 #ifdef _WIN32_WCE
298 TCHAR wText[255];
299 #endif
300 frontend *fe = (frontend *)handle;
302 #ifdef _WIN32_WCE
303 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 255);
304 SendMessage(fe->statusbar, SB_SETTEXT,
305 (WPARAM) 255 | SBT_NOBORDERS,
306 (LPARAM) wText);
307 #else
308 SetWindowText(fe->statusbar, text);
309 #endif
312 static blitter *win_blitter_new(void *handle, int w, int h)
314 blitter *bl = snew(blitter);
316 memset(bl, 0, sizeof(blitter));
317 bl->w = w;
318 bl->h = h;
319 bl->bitmap = 0;
321 return bl;
324 static void win_blitter_free(void *handle, blitter *bl)
326 if (bl->bitmap) DeleteObject(bl->bitmap);
327 sfree(bl);
330 static void blitter_mkbitmap(frontend *fe, blitter *bl)
332 HDC hdc = GetDC(fe->hwnd);
333 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
334 ReleaseDC(fe->hwnd, hdc);
337 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
339 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
341 frontend *fe = (frontend *)handle;
342 HDC hdc_win, hdc_blit;
343 HBITMAP prev_blit;
345 assert(fe->drawstatus == DRAWING);
347 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
349 bl->x = x; bl->y = y;
351 hdc_win = GetDC(fe->hwnd);
352 hdc_blit = CreateCompatibleDC(hdc_win);
353 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
355 prev_blit = SelectObject(hdc_blit, bl->bitmap);
356 if (prev_blit == NULL || prev_blit == HGDI_ERROR)
357 fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
359 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
360 fe->hdc, x, y, SRCCOPY))
361 fatal("BitBlt failed: 0x%x", GetLastError());
363 SelectObject(hdc_blit, prev_blit);
364 DeleteDC(hdc_blit);
365 ReleaseDC(fe->hwnd, hdc_win);
368 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
370 frontend *fe = (frontend *)handle;
371 HDC hdc_win, hdc_blit;
372 HBITMAP prev_blit;
374 assert(fe->drawstatus == DRAWING);
376 assert(bl->bitmap); /* we should always have saved before loading */
378 if (x == BLITTER_FROMSAVED) x = bl->x;
379 if (y == BLITTER_FROMSAVED) y = bl->y;
381 hdc_win = GetDC(fe->hwnd);
382 hdc_blit = CreateCompatibleDC(hdc_win);
384 prev_blit = SelectObject(hdc_blit, bl->bitmap);
386 BitBlt(fe->hdc, x, y, bl->w, bl->h,
387 hdc_blit, 0, 0, SRCCOPY);
389 SelectObject(hdc_blit, prev_blit);
390 DeleteDC(hdc_blit);
391 ReleaseDC(fe->hwnd, hdc_win);
394 void frontend_default_colour(frontend *fe, float *output)
396 DWORD c = GetSysColor(COLOR_MENU); /* ick */
398 output[0] = (float)(GetRValue(c) / 255.0);
399 output[1] = (float)(GetGValue(c) / 255.0);
400 output[2] = (float)(GetBValue(c) / 255.0);
403 static POINT win_transform_point(frontend *fe, int x, int y)
405 POINT ret;
407 assert(fe->drawstatus != NOTHING);
409 if (fe->drawstatus == PRINTING) {
410 ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
411 ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
412 } else {
413 ret.x = x;
414 ret.y = y;
417 return ret;
420 static void win_text_colour(frontend *fe, int colour)
422 assert(fe->drawstatus != NOTHING);
424 if (fe->drawstatus == PRINTING) {
425 int hatch;
426 float r, g, b;
427 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
430 * Displaying text in hatched colours is not permitted.
432 assert(hatch < 0);
434 SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
435 } else {
436 SetTextColor(fe->hdc, fe->colours[colour]);
440 static void win_set_brush(frontend *fe, int colour)
442 HBRUSH br;
443 assert(fe->drawstatus != NOTHING);
445 if (fe->drawstatus == PRINTING) {
446 int hatch;
447 float r, g, b;
448 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
450 if (hatch < 0) {
451 br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
452 } else {
453 #ifdef _WIN32_WCE
455 * This is only ever required during printing, and the
456 * PocketPC port doesn't support printing.
458 fatal("CreateHatchBrush not supported");
459 #else
460 br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
461 hatch == HATCH_SLASH ? HS_BDIAGONAL :
462 hatch == HATCH_HORIZ ? HS_HORIZONTAL :
463 hatch == HATCH_VERT ? HS_VERTICAL :
464 hatch == HATCH_PLUS ? HS_CROSS :
465 /* hatch == HATCH_X ? */ HS_DIAGCROSS,
466 RGB(0,0,0));
467 #endif
469 } else {
470 br = fe->brushes[colour];
472 fe->oldbr = SelectObject(fe->hdc, br);
475 static void win_reset_brush(frontend *fe)
477 HBRUSH br;
479 assert(fe->drawstatus != NOTHING);
481 br = SelectObject(fe->hdc, fe->oldbr);
482 if (fe->drawstatus == PRINTING)
483 DeleteObject(br);
486 static void win_set_pen(frontend *fe, int colour, int thin)
488 HPEN pen;
489 assert(fe->drawstatus != NOTHING);
491 if (fe->drawstatus == PRINTING) {
492 int hatch;
493 float r, g, b;
494 int width = thin ? 0 : fe->linewidth;
496 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
498 * Stroking in hatched colours is not permitted.
500 assert(hatch < 0);
501 pen = CreatePen(PS_SOLID, width, RGB(r * 255, g * 255, b * 255));
502 } else {
503 pen = fe->pens[colour];
505 fe->oldpen = SelectObject(fe->hdc, pen);
508 static void win_reset_pen(frontend *fe)
510 HPEN pen;
512 assert(fe->drawstatus != NOTHING);
514 pen = SelectObject(fe->hdc, fe->oldpen);
515 if (fe->drawstatus == PRINTING)
516 DeleteObject(pen);
519 static void win_clip(void *handle, int x, int y, int w, int h)
521 frontend *fe = (frontend *)handle;
522 POINT p, q;
524 if (fe->drawstatus == NOTHING)
525 return;
527 p = win_transform_point(fe, x, y);
528 q = win_transform_point(fe, x+w, y+h);
529 IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
532 static void win_unclip(void *handle)
534 frontend *fe = (frontend *)handle;
536 if (fe->drawstatus == NOTHING)
537 return;
539 SelectClipRgn(fe->hdc, NULL);
542 static void win_draw_text(void *handle, int x, int y, int fonttype,
543 int fontsize, int align, int colour, char *text)
545 frontend *fe = (frontend *)handle;
546 POINT xy;
547 int i;
548 LOGFONT lf;
550 if (fe->drawstatus == NOTHING)
551 return;
553 if (fe->drawstatus == PRINTING)
554 fontsize = (int)(fontsize * fe->printpixelscale);
556 xy = win_transform_point(fe, x, y);
559 * Find or create the font.
561 for (i = fe->fontstart; i < fe->nfonts; i++)
562 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
563 break;
565 if (i == fe->nfonts) {
566 if (fe->fontsize <= fe->nfonts) {
567 fe->fontsize = fe->nfonts + 10;
568 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
571 fe->nfonts++;
573 fe->fonts[i].type = fonttype;
574 fe->fonts[i].size = fontsize;
576 memset (&lf, 0, sizeof(LOGFONT));
577 lf.lfHeight = -fontsize;
578 lf.lfWeight = (fe->drawstatus == PRINTING ? 0 : FW_BOLD);
579 lf.lfCharSet = DEFAULT_CHARSET;
580 lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
581 lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
582 lf.lfQuality = DEFAULT_QUALITY;
583 lf.lfPitchAndFamily = (fonttype == FONT_FIXED ?
584 FIXED_PITCH | FF_DONTCARE :
585 VARIABLE_PITCH | FF_SWISS);
586 #ifdef _WIN32_WCE
587 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
588 #endif
590 fe->fonts[i].font = CreateFontIndirect(&lf);
594 * Position and draw the text.
597 HFONT oldfont;
598 TEXTMETRIC tm;
599 SIZE size;
600 #ifdef _WIN32_WCE
601 TCHAR wText[256];
602 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 256);
603 #endif
605 oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
606 if (GetTextMetrics(fe->hdc, &tm)) {
607 if (align & ALIGN_VCENTRE)
608 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
609 else
610 xy.y -= tm.tmAscent;
612 #ifndef _WIN32_WCE
613 if (GetTextExtentPoint32(fe->hdc, text, strlen(text), &size))
614 #else
615 if (GetTextExtentPoint32(fe->hdc, wText, wcslen(wText), &size))
616 #endif
618 if (align & ALIGN_HCENTRE)
619 xy.x -= size.cx / 2;
620 else if (align & ALIGN_HRIGHT)
621 xy.x -= size.cx;
623 SetBkMode(fe->hdc, TRANSPARENT);
624 win_text_colour(fe, colour);
625 #ifndef _WIN32_WCE
626 TextOut(fe->hdc, xy.x, xy.y, text, strlen(text));
627 #else
628 ExtTextOut(fe->hdc, xy.x, xy.y, 0, NULL, wText, wcslen(wText), NULL);
629 #endif
630 SelectObject(fe->hdc, oldfont);
634 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
636 frontend *fe = (frontend *)handle;
637 POINT p, q;
639 if (fe->drawstatus == NOTHING)
640 return;
642 if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
644 * Rectangle() appears to get uppity if asked to draw a 1x1
645 * rectangle, presumably on the grounds that that's beneath
646 * its dignity and you ought to be using SetPixel instead.
647 * So I will.
649 SetPixel(fe->hdc, x, y, fe->colours[colour]);
650 } else {
651 win_set_brush(fe, colour);
652 win_set_pen(fe, colour, TRUE);
653 p = win_transform_point(fe, x, y);
654 q = win_transform_point(fe, x+w, y+h);
655 Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
656 win_reset_brush(fe);
657 win_reset_pen(fe);
661 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
663 frontend *fe = (frontend *)handle;
664 POINT pp[2];
666 if (fe->drawstatus == NOTHING)
667 return;
669 win_set_pen(fe, colour, FALSE);
670 pp[0] = win_transform_point(fe, x1, y1);
671 pp[1] = win_transform_point(fe, x2, y2);
672 Polyline(fe->hdc, pp, 2);
673 if (fe->drawstatus == DRAWING)
674 SetPixel(fe->hdc, pp[1].x, pp[1].y, fe->colours[colour]);
675 win_reset_pen(fe);
678 static void win_draw_circle(void *handle, int cx, int cy, int radius,
679 int fillcolour, int outlinecolour)
681 frontend *fe = (frontend *)handle;
682 POINT p, q;
684 assert(outlinecolour >= 0);
686 if (fe->drawstatus == NOTHING)
687 return;
689 if (fillcolour >= 0)
690 win_set_brush(fe, fillcolour);
691 else
692 fe->oldbr = SelectObject(fe->hdc, GetStockObject(NULL_BRUSH));
694 win_set_pen(fe, outlinecolour, FALSE);
695 p = win_transform_point(fe, cx - radius, cy - radius);
696 q = win_transform_point(fe, cx + radius, cy + radius);
697 Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
698 win_reset_brush(fe);
699 win_reset_pen(fe);
702 static void win_draw_polygon(void *handle, int *coords, int npoints,
703 int fillcolour, int outlinecolour)
705 frontend *fe = (frontend *)handle;
706 POINT *pts;
707 int i;
709 if (fe->drawstatus == NOTHING)
710 return;
712 pts = snewn(npoints+1, POINT);
714 for (i = 0; i <= npoints; i++) {
715 int j = (i < npoints ? i : 0);
716 pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
719 assert(outlinecolour >= 0);
721 if (fillcolour >= 0) {
722 win_set_brush(fe, fillcolour);
723 win_set_pen(fe, outlinecolour, FALSE);
724 Polygon(fe->hdc, pts, npoints);
725 win_reset_brush(fe);
726 win_reset_pen(fe);
727 } else {
728 win_set_pen(fe, outlinecolour, FALSE);
729 Polyline(fe->hdc, pts, npoints+1);
730 win_reset_pen(fe);
733 sfree(pts);
736 static void win_start_draw(void *handle)
738 frontend *fe = (frontend *)handle;
739 HDC hdc_win;
741 assert(fe->drawstatus == NOTHING);
743 hdc_win = GetDC(fe->hwnd);
744 fe->hdc = CreateCompatibleDC(hdc_win);
745 fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
746 ReleaseDC(fe->hwnd, hdc_win);
747 fe->clip = NULL;
748 #ifndef _WIN32_WCE
749 SetMapMode(fe->hdc, MM_TEXT);
750 #endif
751 fe->drawstatus = DRAWING;
754 static void win_draw_update(void *handle, int x, int y, int w, int h)
756 frontend *fe = (frontend *)handle;
757 RECT r;
759 if (fe->drawstatus != DRAWING)
760 return;
762 r.left = x;
763 r.top = y;
764 r.right = x + w;
765 r.bottom = y + h;
767 OffsetRect(&r, fe->bitmapPosition.left, fe->bitmapPosition.top);
768 InvalidateRect(fe->hwnd, &r, FALSE);
771 static void win_end_draw(void *handle)
773 frontend *fe = (frontend *)handle;
774 assert(fe->drawstatus == DRAWING);
775 SelectObject(fe->hdc, fe->prevbm);
776 DeleteDC(fe->hdc);
777 if (fe->clip) {
778 DeleteObject(fe->clip);
779 fe->clip = NULL;
781 fe->drawstatus = NOTHING;
784 static void win_line_width(void *handle, float width)
786 frontend *fe = (frontend *)handle;
788 assert(fe->drawstatus != DRAWING);
789 if (fe->drawstatus == NOTHING)
790 return;
792 fe->linewidth = (int)(width * fe->printpixelscale);
795 static void win_begin_doc(void *handle, int pages)
797 frontend *fe = (frontend *)handle;
799 assert(fe->drawstatus != DRAWING);
800 if (fe->drawstatus == NOTHING)
801 return;
803 if (StartDoc(fe->hdc, &fe->di) <= 0) {
804 char *e = geterrstr();
805 MessageBox(fe->hwnd, e, "Error starting to print",
806 MB_ICONERROR | MB_OK);
807 sfree(e);
808 fe->drawstatus = NOTHING;
812 * Push a marker on the font stack so that we won't use the
813 * same fonts for printing and drawing. (This is because
814 * drawing seems to look generally better in bold, but printing
815 * is better not in bold.)
817 fe->fontstart = fe->nfonts;
820 static void win_begin_page(void *handle, int number)
822 frontend *fe = (frontend *)handle;
824 assert(fe->drawstatus != DRAWING);
825 if (fe->drawstatus == NOTHING)
826 return;
828 if (StartPage(fe->hdc) <= 0) {
829 char *e = geterrstr();
830 MessageBox(fe->hwnd, e, "Error starting a page",
831 MB_ICONERROR | MB_OK);
832 sfree(e);
833 fe->drawstatus = NOTHING;
837 static void win_begin_puzzle(void *handle, float xm, float xc,
838 float ym, float yc, int pw, int ph, float wmm)
840 frontend *fe = (frontend *)handle;
841 int ppw, pph, pox, poy;
842 float mmpw, mmph, mmox, mmoy;
843 float scale;
845 assert(fe->drawstatus != DRAWING);
846 if (fe->drawstatus == NOTHING)
847 return;
849 ppw = GetDeviceCaps(fe->hdc, HORZRES);
850 pph = GetDeviceCaps(fe->hdc, VERTRES);
851 mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
852 mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
855 * Compute the puzzle's position on the logical page.
857 mmox = xm * mmpw + xc;
858 mmoy = ym * mmph + yc;
861 * Work out what that comes to in pixels.
863 pox = (int)(mmox * (float)ppw / mmpw);
864 poy = (int)(mmoy * (float)pph / mmph);
867 * And determine the scale.
869 * I need a scale such that the maximum puzzle-coordinate
870 * extent of the rectangle (pw * scale) is equal to the pixel
871 * equivalent of the puzzle's millimetre width (wmm * ppw /
872 * mmpw).
874 scale = (wmm * ppw) / (mmpw * pw);
877 * Now store pox, poy and scale for use in the main drawing
878 * functions.
880 fe->printoffsetx = pox;
881 fe->printoffsety = poy;
882 fe->printpixelscale = scale;
884 fe->linewidth = 1;
887 static void win_end_puzzle(void *handle)
889 /* Nothing needs to be done here. */
892 static void win_end_page(void *handle, int number)
894 frontend *fe = (frontend *)handle;
896 assert(fe->drawstatus != DRAWING);
898 if (fe->drawstatus == NOTHING)
899 return;
901 if (EndPage(fe->hdc) <= 0) {
902 char *e = geterrstr();
903 MessageBox(fe->hwnd, e, "Error finishing a page",
904 MB_ICONERROR | MB_OK);
905 sfree(e);
906 fe->drawstatus = NOTHING;
910 static void win_end_doc(void *handle)
912 frontend *fe = (frontend *)handle;
914 assert(fe->drawstatus != DRAWING);
917 * Free all the fonts created since we began printing.
919 while (fe->nfonts > fe->fontstart) {
920 fe->nfonts--;
921 DeleteObject(fe->fonts[fe->nfonts].font);
923 fe->fontstart = 0;
926 * The MSDN web site sample code doesn't bother to call EndDoc
927 * if an error occurs half way through printing. I expect doing
928 * so would cause the erroneous document to actually be
929 * printed, or something equally undesirable.
931 if (fe->drawstatus == NOTHING)
932 return;
934 if (EndDoc(fe->hdc) <= 0) {
935 char *e = geterrstr();
936 MessageBox(fe->hwnd, e, "Error finishing printing",
937 MB_ICONERROR | MB_OK);
938 sfree(e);
939 fe->drawstatus = NOTHING;
943 const struct drawing_api win_drawing = {
944 win_draw_text,
945 win_draw_rect,
946 win_draw_line,
947 win_draw_polygon,
948 win_draw_circle,
949 win_draw_update,
950 win_clip,
951 win_unclip,
952 win_start_draw,
953 win_end_draw,
954 win_status_bar,
955 win_blitter_new,
956 win_blitter_free,
957 win_blitter_save,
958 win_blitter_load,
959 win_begin_doc,
960 win_begin_page,
961 win_begin_puzzle,
962 win_end_puzzle,
963 win_end_page,
964 win_end_doc,
965 win_line_width,
968 void print(frontend *fe)
970 #ifndef _WIN32_WCE
971 PRINTDLG pd;
972 char doctitle[256];
973 document *doc;
974 midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
975 int i;
976 char *err = NULL;
979 * Create our document structure and fill it up with puzzles.
981 doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
982 for (i = 0; i < fe->printcount; i++) {
983 if (i == 0 && fe->printcurr) {
984 err = midend_print_puzzle(fe->me, doc, fe->printsolns);
985 } else {
986 if (!nme) {
987 game_params *params;
989 nme = midend_new(NULL, fe->game, NULL, NULL);
992 * Set the non-interactive mid-end to have the same
993 * parameters as the standard one.
995 params = midend_get_params(fe->me);
996 midend_set_params(nme, params);
997 fe->game->free_params(params);
1000 midend_new_game(nme);
1001 err = midend_print_puzzle(nme, doc, fe->printsolns);
1003 if (err)
1004 break;
1006 if (nme)
1007 midend_free(nme);
1009 if (err) {
1010 MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
1011 MB_ICONERROR | MB_OK);
1012 document_free(doc);
1013 return;
1016 memset(&pd, 0, sizeof(pd));
1017 pd.lStructSize = sizeof(pd);
1018 pd.hwndOwner = fe->hwnd;
1019 pd.hDevMode = NULL;
1020 pd.hDevNames = NULL;
1021 pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
1022 PD_NOPAGENUMS | PD_NOSELECTION;
1023 pd.nCopies = 1;
1024 pd.nFromPage = pd.nToPage = 0xFFFF;
1025 pd.nMinPage = pd.nMaxPage = 1;
1027 if (!PrintDlg(&pd)) {
1028 document_free(doc);
1029 return;
1033 * Now pd.hDC is a device context for the printer.
1037 * FIXME: IWBNI we put up an Abort box here.
1040 memset(&fe->di, 0, sizeof(fe->di));
1041 fe->di.cbSize = sizeof(fe->di);
1042 sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
1043 " Portable Puzzle Collection)", fe->game->name);
1044 fe->di.lpszDocName = doctitle;
1045 fe->di.lpszOutput = NULL;
1046 fe->di.lpszDatatype = NULL;
1047 fe->di.fwType = 0;
1049 fe->drawstatus = PRINTING;
1050 fe->hdc = pd.hDC;
1052 fe->dr = drawing_new(&win_drawing, NULL, fe);
1053 document_print(doc, fe->dr);
1054 drawing_free(fe->dr);
1055 fe->dr = NULL;
1057 fe->drawstatus = NOTHING;
1059 DeleteDC(pd.hDC);
1060 document_free(doc);
1061 #endif
1064 void deactivate_timer(frontend *fe)
1066 if (!fe)
1067 return; /* for non-interactive midend */
1068 if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
1069 fe->timer = 0;
1072 void activate_timer(frontend *fe)
1074 if (!fe)
1075 return; /* for non-interactive midend */
1076 if (!fe->timer) {
1077 fe->timer = SetTimer(fe->hwnd, 1, 20, NULL);
1078 fe->timer_last_tickcount = GetTickCount();
1082 void write_clip(HWND hwnd, char *data)
1084 HGLOBAL clipdata;
1085 int len, i, j;
1086 char *data2;
1087 void *lock;
1090 * Windows expects CRLF in the clipboard, so we must convert
1091 * any \n that has come out of the puzzle backend.
1093 len = 0;
1094 for (i = 0; data[i]; i++) {
1095 if (data[i] == '\n')
1096 len++;
1097 len++;
1099 data2 = snewn(len+1, char);
1100 j = 0;
1101 for (i = 0; data[i]; i++) {
1102 if (data[i] == '\n')
1103 data2[j++] = '\r';
1104 data2[j++] = data[i];
1106 assert(j == len);
1107 data2[j] = '\0';
1109 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
1110 if (!clipdata) {
1111 sfree(data2);
1112 return;
1114 lock = GlobalLock(clipdata);
1115 if (!lock) {
1116 GlobalFree(clipdata);
1117 sfree(data2);
1118 return;
1120 memcpy(lock, data2, len);
1121 ((unsigned char *) lock)[len] = 0;
1122 GlobalUnlock(clipdata);
1124 if (OpenClipboard(hwnd)) {
1125 EmptyClipboard();
1126 SetClipboardData(CF_TEXT, clipdata);
1127 CloseClipboard();
1128 } else
1129 GlobalFree(clipdata);
1131 sfree(data2);
1135 * Set up Help and see if we can find a help file.
1137 static void init_help(void)
1139 #ifndef _WIN32_WCE
1140 char b[2048], *p, *q, *r;
1141 FILE *fp;
1144 * Find the executable file path, so we can look alongside
1145 * it for help files. Trim the filename off the end.
1147 GetModuleFileName(NULL, b, sizeof(b) - 1);
1148 r = b;
1149 p = strrchr(b, '\\');
1150 if (p && p >= r) r = p+1;
1151 q = strrchr(b, ':');
1152 if (q && q >= r) r = q+1;
1154 #ifndef NO_HTMLHELP
1156 * Try HTML Help first.
1158 strcpy(r, CHM_FILE_NAME);
1159 if ( (fp = fopen(b, "r")) != NULL) {
1160 fclose(fp);
1163 * We have a .CHM. See if we can use it.
1165 hh_dll = LoadLibrary("hhctrl.ocx");
1166 if (hh_dll) {
1167 htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
1168 if (!htmlhelp)
1169 FreeLibrary(hh_dll);
1171 if (htmlhelp) {
1172 help_path = dupstr(b);
1173 help_type = CHM;
1174 return;
1177 #endif /* NO_HTMLHELP */
1180 * Now try old-style .HLP.
1182 strcpy(r, HELP_FILE_NAME);
1183 if ( (fp = fopen(b, "r")) != NULL) {
1184 fclose(fp);
1186 help_path = dupstr(b);
1187 help_type = HLP;
1190 * See if there's a .CNT file alongside it.
1192 strcpy(r, HELP_CNT_NAME);
1193 if ( (fp = fopen(b, "r")) != NULL) {
1194 fclose(fp);
1195 help_has_contents = TRUE;
1196 } else
1197 help_has_contents = FALSE;
1199 return;
1202 help_type = NONE; /* didn't find any */
1203 #endif
1206 #ifndef _WIN32_WCE
1209 * Start Help.
1211 static void start_help(frontend *fe, const char *topic)
1213 char *str = NULL;
1214 int cmd;
1216 switch (help_type) {
1217 case HLP:
1218 assert(help_path);
1219 if (topic) {
1220 str = snewn(10+strlen(topic), char);
1221 sprintf(str, "JI(`',`%s')", topic);
1222 cmd = HELP_COMMAND;
1223 } else if (help_has_contents) {
1224 cmd = HELP_FINDER;
1225 } else {
1226 cmd = HELP_CONTENTS;
1228 WinHelp(fe->hwnd, help_path, cmd, (DWORD)str);
1229 fe->help_running = TRUE;
1230 break;
1231 case CHM:
1232 #ifndef NO_HTMLHELP
1233 assert(help_path);
1234 assert(htmlhelp);
1235 if (topic) {
1236 str = snewn(20 + strlen(topic) + strlen(help_path), char);
1237 sprintf(str, "%s::/%s.html>main", help_path, topic);
1238 } else {
1239 str = dupstr(help_path);
1241 htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
1242 fe->help_running = TRUE;
1243 break;
1244 #endif /* NO_HTMLHELP */
1245 case NONE:
1246 assert(!"This shouldn't happen");
1247 break;
1250 sfree(str);
1254 * Stop Help on window cleanup.
1256 static void stop_help(frontend *fe)
1258 if (fe->help_running) {
1259 switch (help_type) {
1260 case HLP:
1261 WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
1262 break;
1263 case CHM:
1264 #ifndef NO_HTMLHELP
1265 assert(htmlhelp);
1266 htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
1267 break;
1268 #endif /* NO_HTMLHELP */
1269 case NONE:
1270 assert(!"This shouldn't happen");
1271 break;
1273 fe->help_running = FALSE;
1277 #endif
1280 * Terminate Help on process exit.
1282 static void cleanup_help(void)
1284 /* Nothing to do currently.
1285 * (If we were running HTML Help single-threaded, this is where we'd
1286 * call HH_UNINITIALIZE.) */
1289 static int get_statusbar_height(frontend *fe)
1291 int sy;
1292 if (fe->statusbar) {
1293 RECT sr;
1294 GetWindowRect(fe->statusbar, &sr);
1295 sy = sr.bottom - sr.top;
1296 } else {
1297 sy = 0;
1299 return sy;
1302 static void adjust_statusbar(frontend *fe, RECT *r)
1304 int sy;
1306 if (!fe->statusbar) return;
1308 sy = get_statusbar_height(fe);
1309 #ifndef _WIN32_WCE
1310 SetWindowPos(fe->statusbar, NULL, 0, r->bottom-r->top-sy, r->right-r->left,
1311 sy, SWP_NOZORDER);
1312 #endif
1315 static void get_menu_size(HWND wh, RECT *r)
1317 HMENU bar = GetMenu(wh);
1318 RECT rect;
1319 int i;
1321 SetRect(r, 0, 0, 0, 0);
1322 for (i = 0; i < GetMenuItemCount(bar); i++) {
1323 GetMenuItemRect(wh, bar, i, &rect);
1324 UnionRect(r, r, &rect);
1329 * Given a proposed new puzzle size (cx,cy), work out the actual
1330 * puzzle size that would be (px,py) and the window size including
1331 * furniture (wx,wy).
1334 static int check_window_resize(frontend *fe, int cx, int cy,
1335 int *px, int *py,
1336 int *wx, int *wy)
1338 RECT r;
1339 int x, y, sy = get_statusbar_height(fe), changed = 0;
1341 /* disallow making window thinner than menu bar */
1342 x = max(cx, fe->xmin);
1343 y = max(cy - sy, fe->ymin);
1346 * See if we actually got the window size we wanted, and adjust
1347 * the puzzle size if not.
1349 midend_size(fe->me, &x, &y, TRUE);
1350 if (x != cx || y != cy) {
1352 * Resize the window, now we know what size we _really_
1353 * want it to be.
1355 r.left = r.top = 0;
1356 r.right = x;
1357 r.bottom = y + sy;
1358 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1359 *wx = r.right - r.left;
1360 *wy = r.bottom - r.top;
1361 changed = 1;
1364 *px = x;
1365 *py = y;
1367 fe->puzz_scale =
1368 (float)midend_tilesize(fe->me) / (float)fe->game->preferred_tilesize;
1370 return changed;
1374 * Given the current window size, make sure it's sane for the
1375 * current puzzle and resize if necessary.
1378 static void check_window_size(frontend *fe, int *px, int *py)
1380 RECT r;
1381 int wx, wy, cx, cy;
1383 GetClientRect(fe->hwnd, &r);
1384 cx = r.right - r.left;
1385 cy = r.bottom - r.top;
1387 if (check_window_resize(fe, cx, cy, px, py, &wx, &wy)) {
1388 #ifdef _WIN32_WCE
1389 SetWindowPos(fe->hwnd, NULL, 0, 0, wx, wy,
1390 SWP_NOMOVE | SWP_NOZORDER);
1391 #endif
1395 GetClientRect(fe->hwnd, &r);
1396 adjust_statusbar(fe, &r);
1399 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1401 RECT r, sr;
1403 if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1404 *x = sr.right - sr.left;
1405 *y = sr.bottom - sr.top;
1406 r.left = 100;
1407 r.right = 200;
1408 r.top = 100;
1409 r.bottom = 200;
1410 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1411 *x -= r.right - r.left - 100;
1412 *y -= r.bottom - r.top - 100;
1413 } else {
1414 *x = *y = INT_MAX;
1417 if (fe->statusbar != NULL) {
1418 GetWindowRect(fe->statusbar, &sr);
1419 *y -= sr.bottom - sr.top;
1423 #ifdef _WIN32_WCE
1424 /* Toolbar buttons on the numeric pad */
1425 static TBBUTTON tbNumpadButtons[] =
1427 {0, IDM_KEYEMUL + '1', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1428 {1, IDM_KEYEMUL + '2', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1429 {2, IDM_KEYEMUL + '3', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1430 {3, IDM_KEYEMUL + '4', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1431 {4, IDM_KEYEMUL + '5', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1432 {5, IDM_KEYEMUL + '6', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1433 {6, IDM_KEYEMUL + '7', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1434 {7, IDM_KEYEMUL + '8', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1435 {8, IDM_KEYEMUL + '9', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1436 {9, IDM_KEYEMUL + ' ', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1}
1438 #endif
1441 * Allocate a new frontend structure and create its main window.
1443 static frontend *frontend_new(HINSTANCE inst)
1445 frontend *fe;
1446 const char *nogame = "Puzzles (no game selected)";
1448 fe = snew(frontend);
1450 fe->inst = inst;
1452 fe->game = NULL;
1453 fe->me = NULL;
1455 fe->timer = 0;
1456 fe->hwnd = NULL;
1458 fe->help_running = FALSE;
1460 fe->drawstatus = NOTHING;
1461 fe->dr = NULL;
1462 fe->fontstart = 0;
1464 fe->fonts = NULL;
1465 fe->nfonts = fe->fontsize = 0;
1467 fe->colours = NULL;
1468 fe->brushes = NULL;
1469 fe->pens = NULL;
1471 fe->puzz_scale = 1.0;
1473 #ifdef _WIN32_WCE
1474 MultiByteToWideChar (CP_ACP, 0, nogame, -1, wGameName, 256);
1475 fe->hwnd = CreateWindowEx(0, wClassName, wGameName,
1476 WS_VISIBLE,
1477 CW_USEDEFAULT, CW_USEDEFAULT,
1478 CW_USEDEFAULT, CW_USEDEFAULT,
1479 NULL, NULL, inst, NULL);
1482 SHMENUBARINFO mbi;
1483 RECT rc, rcBar, rcTB, rcClient;
1485 memset (&mbi, 0, sizeof(SHMENUBARINFO));
1486 mbi.cbSize = sizeof(SHMENUBARINFO);
1487 mbi.hwndParent = fe->hwnd;
1488 mbi.nToolBarId = IDR_MENUBAR1;
1489 mbi.hInstRes = inst;
1491 SHCreateMenuBar(&mbi);
1493 GetWindowRect(fe->hwnd, &rc);
1494 GetWindowRect(mbi.hwndMB, &rcBar);
1495 rc.bottom -= rcBar.bottom - rcBar.top;
1496 MoveWindow(fe->hwnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, FALSE);
1498 fe->numpad = NULL;
1500 #else
1501 fe->hwnd = CreateWindowEx(0, CLASSNAME, nogame,
1502 WS_OVERLAPPEDWINDOW &~
1503 (WS_MAXIMIZEBOX),
1504 CW_USEDEFAULT, CW_USEDEFAULT,
1505 CW_USEDEFAULT, CW_USEDEFAULT,
1506 NULL, NULL, inst, NULL);
1507 if (!fe->hwnd) {
1508 DWORD lerr = GetLastError();
1509 printf("no window: 0x%x\n", lerr);
1511 #endif
1513 fe->gamemenu = NULL;
1514 fe->presets = NULL;
1516 fe->statusbar = NULL;
1517 fe->bitmap = NULL;
1519 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1521 return fe;
1525 * Populate a frontend structure with a (new) game and midend structure, and
1526 * create any window furniture that it needs.
1528 * Previously-allocated memory and window furniture will be freed by this function.
1530 static int new_game(frontend *fe, const game *game, char *game_id, char **error)
1532 int x, y;
1533 RECT r;
1535 fe->game = game;
1537 if (fe->me) midend_free(fe->me);
1538 fe->me = midend_new(fe, fe->game, &win_drawing, fe);
1540 if (game_id) {
1541 *error = midend_game_id(fe->me, game_id);
1542 if (*error) {
1543 midend_free(fe->me);
1544 sfree(fe);
1545 return -1;
1549 midend_new_game(fe->me);
1552 int i, ncolours;
1553 float *colours;
1555 colours = midend_colours(fe->me, &ncolours);
1557 if (fe->colours) sfree(fe->colours);
1558 if (fe->brushes) sfree(fe->brushes);
1559 if (fe->pens) sfree(fe->pens);
1561 fe->colours = snewn(ncolours, COLORREF);
1562 fe->brushes = snewn(ncolours, HBRUSH);
1563 fe->pens = snewn(ncolours, HPEN);
1565 for (i = 0; i < ncolours; i++) {
1566 fe->colours[i] = RGB(255 * colours[i*3+0],
1567 255 * colours[i*3+1],
1568 255 * colours[i*3+2]);
1569 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1570 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1572 sfree(colours);
1575 if (fe->statusbar)
1576 DestroyWindow(fe->statusbar);
1577 if (midend_wants_statusbar(fe->me)) {
1578 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1579 WS_CHILD | WS_VISIBLE,
1580 0, 0, 0, 0, /* status bar does these */
1581 NULL, NULL, fe->inst, NULL);
1582 } else
1583 fe->statusbar = NULL;
1585 get_max_puzzle_size(fe, &x, &y);
1586 midend_size(fe->me, &x, &y, FALSE);
1588 r.left = r.top = 0;
1589 r.right = x;
1590 r.bottom = y;
1591 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1593 #ifdef _WIN32_WCE
1594 if (fe->numpad)
1595 DestroyWindow(fe->numpad);
1596 if (fe->game->flags & REQUIRE_NUMPAD)
1598 fe->numpad = CreateToolbarEx (fe->hwnd,
1599 WS_VISIBLE | WS_CHILD | CCS_NOPARENTALIGN | TBSTYLE_FLAT,
1600 0, 10, fe->inst, IDR_PADTOOLBAR,
1601 tbNumpadButtons, sizeof (tbNumpadButtons) / sizeof (TBBUTTON),
1602 0, 0, 14, 15, sizeof (TBBUTTON));
1603 GetWindowRect(fe->numpad, &rcTB);
1604 GetClientRect(fe->hwnd, &rcClient);
1605 MoveWindow(fe->numpad,
1607 rcClient.bottom - (rcTB.bottom - rcTB.top) - 1,
1608 rcClient.right,
1609 rcTB.bottom - rcTB.top,
1610 FALSE);
1611 SendMessage(fe->numpad, TB_SETINDENT, (rcClient.right - (10 * 21)) / 2, 0);
1613 else {
1614 fe->numpad = NULL;
1616 MultiByteToWideChar (CP_ACP, 0, fe->game->name, -1, wGameName, 256);
1617 SetWindowText(fe->hwnd, wGameName);
1618 #else
1619 SetWindowText(fe->hwnd, fe->game->name);
1620 #endif
1622 if (fe->statusbar)
1623 DestroyWindow(fe->statusbar);
1624 if (midend_wants_statusbar(fe->me)) {
1625 RECT sr;
1626 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1627 WS_CHILD | WS_VISIBLE,
1628 0, 0, 0, 0, /* status bar does these */
1629 fe->hwnd, NULL, fe->inst, NULL);
1630 #ifdef _WIN32_WCE
1631 /* Flat status bar looks better on the Pocket PC */
1632 SendMessage(fe->statusbar, SB_SIMPLE, (WPARAM) TRUE, 0);
1633 SendMessage(fe->statusbar, SB_SETTEXT,
1634 (WPARAM) 255 | SBT_NOBORDERS,
1635 (LPARAM) L"");
1636 #endif
1639 * Now resize the window to take account of the status bar.
1641 GetWindowRect(fe->statusbar, &sr);
1642 GetWindowRect(fe->hwnd, &r);
1643 #ifndef _WIN32_WCE
1644 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1645 r.bottom - r.top + sr.bottom - sr.top,
1646 SWP_NOMOVE | SWP_NOZORDER);
1647 #endif
1648 } else {
1649 fe->statusbar = NULL;
1653 HMENU oldmenu = GetMenu(fe->hwnd);
1655 #ifndef _WIN32_WCE
1656 HMENU bar = CreateMenu();
1657 HMENU menu = CreateMenu();
1658 RECT menusize;
1660 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "&Game");
1661 #else
1662 HMENU menu = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_GAME);
1663 DeleteMenu(menu, 0, MF_BYPOSITION);
1664 #endif
1665 fe->gamemenu = menu;
1666 AppendMenu(menu, MF_ENABLED, IDM_NEW, TEXT("&New"));
1667 AppendMenu(menu, MF_ENABLED, IDM_RESTART, TEXT("&Restart"));
1668 #ifndef _WIN32_WCE
1669 /* ...here I run out of sensible accelerator characters. */
1670 AppendMenu(menu, MF_ENABLED, IDM_DESC, TEXT("Speci&fic..."));
1671 AppendMenu(menu, MF_ENABLED, IDM_SEED, TEXT("Rando&m Seed..."));
1672 #endif
1674 if (fe->presets)
1675 sfree(fe->presets);
1676 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1677 fe->game->can_configure) {
1678 int i;
1679 #ifndef _WIN32_WCE
1680 HMENU sub = CreateMenu();
1682 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "&Type");
1683 #else
1684 HMENU sub = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_TYPE);
1685 DeleteMenu(sub, 0, MF_BYPOSITION);
1686 #endif
1687 fe->presets = snewn(fe->npresets, game_params *);
1689 for (i = 0; i < fe->npresets; i++) {
1690 char *name;
1691 #ifdef _WIN32_WCE
1692 TCHAR wName[255];
1693 #endif
1695 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1698 * FIXME: we ought to go through and do something
1699 * with ampersands here.
1702 #ifndef _WIN32_WCE
1703 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1704 #else
1705 MultiByteToWideChar (CP_ACP, 0, name, -1, wName, 255);
1706 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, wName);
1707 #endif
1709 if (fe->game->can_configure) {
1710 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, TEXT("&Custom..."));
1713 fe->typemenu = sub;
1714 } else {
1715 fe->typemenu = INVALID_HANDLE_VALUE;
1716 fe->presets = NULL;
1719 #ifdef COMBINED
1720 #ifdef _WIN32_WCE
1721 #error Windows CE does not support COMBINED build.
1722 #endif
1724 HMENU games = CreateMenu();
1725 int i;
1727 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1728 AppendMenu(menu, MF_ENABLED|MF_POPUP, (UINT)games, "&Other");
1729 for (i = 0; i < gamecount; i++) {
1730 if (strcmp(gamelist[i]->name, fe->game->name) != 0) {
1731 /* only include those games that aren't the same as the
1732 * game we're currently playing. */
1733 AppendMenu(games, MF_ENABLED, IDM_GAMES + i, gamelist[i]->name);
1737 #endif
1739 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1740 #ifndef _WIN32_WCE
1741 AppendMenu(menu, MF_ENABLED, IDM_LOAD, TEXT("&Load..."));
1742 AppendMenu(menu, MF_ENABLED, IDM_SAVE, TEXT("&Save..."));
1743 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1744 if (fe->game->can_print) {
1745 AppendMenu(menu, MF_ENABLED, IDM_PRINT, TEXT("&Print..."));
1746 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1748 #endif
1749 AppendMenu(menu, MF_ENABLED, IDM_UNDO, TEXT("Undo"));
1750 AppendMenu(menu, MF_ENABLED, IDM_REDO, TEXT("Redo"));
1751 #ifndef _WIN32_WCE
1752 if (fe->game->can_format_as_text_ever) {
1753 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1754 AppendMenu(menu, MF_ENABLED, IDM_COPY, TEXT("&Copy"));
1756 #endif
1757 if (fe->game->can_solve) {
1758 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1759 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, TEXT("Sol&ve"));
1761 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1762 #ifndef _WIN32_WCE
1763 AppendMenu(menu, MF_ENABLED, IDM_QUIT, TEXT("E&xit"));
1764 menu = CreateMenu();
1765 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, TEXT("&Help"));
1766 #endif
1767 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, TEXT("&About"));
1768 #ifndef _WIN32_WCE
1769 if (help_type != NONE) {
1770 char *item;
1771 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1772 AppendMenu(menu, MF_ENABLED, IDM_HELPC, TEXT("&Contents"));
1773 assert(fe->game->name);
1774 item = snewn(10+strlen(fe->game->name), char); /*ick*/
1775 sprintf(item, "&Help on %s", fe->game->name);
1776 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1777 sfree(item);
1779 DestroyMenu(oldmenu);
1780 SetMenu(fe->hwnd, bar);
1781 get_menu_size(fe->hwnd, &menusize);
1782 fe->xmin = (menusize.right - menusize.left) + 25;
1783 #endif
1786 if (fe->bitmap) DeleteObject(fe->bitmap);
1787 fe->bitmap = NULL;
1788 new_game_size(fe, fe->puzz_scale); /* initialises fe->bitmap */
1790 return 0;
1793 static void show_window(frontend *fe)
1795 ShowWindow(fe->hwnd, SW_SHOWNORMAL);
1796 SetForegroundWindow(fe->hwnd);
1798 update_type_menu_tick(fe);
1799 update_copy_menu_greying(fe);
1801 midend_redraw(fe->me);
1804 #ifdef _WIN32_WCE
1805 static HFONT dialog_title_font()
1807 static HFONT hf = NULL;
1808 LOGFONT lf;
1810 if (hf)
1811 return hf;
1813 memset (&lf, 0, sizeof(LOGFONT));
1814 lf.lfHeight = -11; /* - ((8 * GetDeviceCaps(hdc, LOGPIXELSY)) / 72) */
1815 lf.lfWeight = FW_BOLD;
1816 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
1818 return hf = CreateFontIndirect(&lf);
1821 static void make_dialog_full_screen(HWND hwnd)
1823 SHINITDLGINFO shidi;
1825 /* Make dialog full screen */
1826 shidi.dwMask = SHIDIM_FLAGS;
1827 shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIZEDLGFULLSCREEN |
1828 SHIDIF_EMPTYMENU;
1829 shidi.hDlg = hwnd;
1830 SHInitDialog(&shidi);
1832 #endif
1834 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1835 WPARAM wParam, LPARAM lParam)
1837 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1839 switch (msg) {
1840 case WM_INITDIALOG:
1841 #ifdef _WIN32_WCE
1843 char title[256];
1845 make_dialog_full_screen(hwnd);
1847 sprintf(title, "About %.250s", fe->game->name);
1848 SetDlgItemTextA(hwnd, IDC_ABOUT_CAPTION, title);
1850 SendDlgItemMessage(hwnd, IDC_ABOUT_CAPTION, WM_SETFONT,
1851 (WPARAM) dialog_title_font(), 0);
1853 SetDlgItemTextA(hwnd, IDC_ABOUT_GAME, fe->game->name);
1854 SetDlgItemTextA(hwnd, IDC_ABOUT_VERSION, ver);
1856 #endif
1857 return TRUE;
1859 case WM_COMMAND:
1860 if (LOWORD(wParam) == IDOK)
1861 #ifdef _WIN32_WCE
1862 EndDialog(hwnd, 1);
1863 #else
1864 fe->dlg_done = 1;
1865 #endif
1866 return 0;
1868 case WM_CLOSE:
1869 #ifdef _WIN32_WCE
1870 EndDialog(hwnd, 1);
1871 #else
1872 fe->dlg_done = 1;
1873 #endif
1874 return 0;
1877 return 0;
1881 * Wrappers on midend_{get,set}_config, which extend the CFG_*
1882 * enumeration to add CFG_PRINT.
1884 static config_item *frontend_get_config(frontend *fe, int which,
1885 char **wintitle)
1887 if (which < CFG_FRONTEND_SPECIFIC) {
1888 return midend_get_config(fe->me, which, wintitle);
1889 } else if (which == CFG_PRINT) {
1890 config_item *ret;
1891 int i;
1893 *wintitle = snewn(40 + strlen(fe->game->name), char);
1894 sprintf(*wintitle, "%s print setup", fe->game->name);
1896 ret = snewn(8, config_item);
1898 i = 0;
1900 ret[i].name = "Number of puzzles to print";
1901 ret[i].type = C_STRING;
1902 ret[i].sval = dupstr("1");
1903 ret[i].ival = 0;
1904 i++;
1906 ret[i].name = "Number of puzzles across the page";
1907 ret[i].type = C_STRING;
1908 ret[i].sval = dupstr("1");
1909 ret[i].ival = 0;
1910 i++;
1912 ret[i].name = "Number of puzzles down the page";
1913 ret[i].type = C_STRING;
1914 ret[i].sval = dupstr("1");
1915 ret[i].ival = 0;
1916 i++;
1918 ret[i].name = "Percentage of standard size";
1919 ret[i].type = C_STRING;
1920 ret[i].sval = dupstr("100.0");
1921 ret[i].ival = 0;
1922 i++;
1924 ret[i].name = "Include currently shown puzzle";
1925 ret[i].type = C_BOOLEAN;
1926 ret[i].sval = NULL;
1927 ret[i].ival = TRUE;
1928 i++;
1930 ret[i].name = "Print solutions";
1931 ret[i].type = C_BOOLEAN;
1932 ret[i].sval = NULL;
1933 ret[i].ival = FALSE;
1934 i++;
1936 if (fe->game->can_print_in_colour) {
1937 ret[i].name = "Print in colour";
1938 ret[i].type = C_BOOLEAN;
1939 ret[i].sval = NULL;
1940 ret[i].ival = FALSE;
1941 i++;
1944 ret[i].name = NULL;
1945 ret[i].type = C_END;
1946 ret[i].sval = NULL;
1947 ret[i].ival = 0;
1948 i++;
1950 return ret;
1951 } else {
1952 assert(!"We should never get here");
1953 return NULL;
1957 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
1959 if (which < CFG_FRONTEND_SPECIFIC) {
1960 return midend_set_config(fe->me, which, cfg);
1961 } else if (which == CFG_PRINT) {
1962 if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
1963 return "Number of puzzles to print should be at least one";
1964 if ((fe->printw = atoi(cfg[1].sval)) <= 0)
1965 return "Number of puzzles across the page should be at least one";
1966 if ((fe->printh = atoi(cfg[2].sval)) <= 0)
1967 return "Number of puzzles down the page should be at least one";
1968 if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
1969 return "Print size should be positive";
1970 fe->printcurr = cfg[4].ival;
1971 fe->printsolns = cfg[5].ival;
1972 fe->printcolour = fe->game->can_print_in_colour && cfg[6].ival;
1973 return NULL;
1974 } else {
1975 assert(!"We should never get here");
1976 return "Internal error";
1980 #ifdef _WIN32_WCE
1981 /* Separate version of mkctrl function for the Pocket PC. */
1982 /* Control coordinates should be specified in dialog units. */
1983 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
1984 LPCTSTR wclass, int wstyle,
1985 int exstyle, const char *wtext, int wid)
1987 RECT rc;
1988 TCHAR wwtext[256];
1990 /* Convert dialog units into pixels */
1991 rc.left = x1; rc.right = x2;
1992 rc.top = y1; rc.bottom = y2;
1993 MapDialogRect(fe->cfgbox, &rc);
1995 MultiByteToWideChar (CP_ACP, 0, wtext, -1, wwtext, 256);
1997 return CreateWindowEx(exstyle, wclass, wwtext,
1998 wstyle | WS_CHILD | WS_VISIBLE,
1999 rc.left, rc.top,
2000 rc.right - rc.left, rc.bottom - rc.top,
2001 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2004 static void create_config_controls(frontend * fe)
2006 int id, nctrls;
2007 int col1l, col1r, col2l, col2r, y;
2008 config_item *i;
2009 struct cfg_aux *j;
2010 HWND ctl;
2012 /* Control placement done in dialog units */
2013 col1l = 4; col1r = 96; /* Label column */
2014 col2l = 100; col2r = 154; /* Input column (edit boxes and combo boxes) */
2017 * Count the controls so we can allocate cfgaux.
2019 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2020 nctrls++;
2021 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2023 id = 1000;
2024 y = 22; /* Leave some room for the dialog title */
2025 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2026 switch (i->type) {
2027 case C_STRING:
2029 * Edit box with a label beside it.
2031 mkctrl(fe, col1l, col1r, y + 1, y + 11,
2032 TEXT("Static"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
2033 mkctrl(fe, col2l, col2r, y, y + 12,
2034 TEXT("EDIT"), WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
2035 0, "", (j->ctlid = id++));
2036 SetDlgItemTextA(fe->cfgbox, j->ctlid, i->sval);
2037 break;
2039 case C_BOOLEAN:
2041 * Simple checkbox.
2043 mkctrl(fe, col1l, col2r, y + 1, y + 11, TEXT("BUTTON"),
2044 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2045 0, i->name, (j->ctlid = id++));
2046 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2047 break;
2049 case C_CHOICES:
2051 * Drop-down list with a label beside it.
2053 mkctrl(fe, col1l, col1r, y + 1, y + 11,
2054 TEXT("STATIC"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
2055 ctl = mkctrl(fe, col2l, col2r, y, y + 48,
2056 TEXT("COMBOBOX"), WS_BORDER | WS_TABSTOP |
2057 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2058 0, "", (j->ctlid = id++));
2060 char c, *p, *q, *str;
2062 p = i->sval;
2063 c = *p++;
2064 while (*p) {
2065 q = p;
2066 while (*q && *q != c) q++;
2067 str = snewn(q-p+1, char);
2068 strncpy(str, p, q-p);
2069 str[q-p] = '\0';
2071 TCHAR ws[50];
2072 MultiByteToWideChar (CP_ACP, 0, str, -1, ws, 50);
2073 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)ws);
2076 sfree(str);
2077 if (*q) q++;
2078 p = q;
2081 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2082 break;
2085 y += 15;
2089 #endif
2091 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
2092 WPARAM wParam, LPARAM lParam)
2094 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2095 config_item *i;
2096 struct cfg_aux *j;
2098 switch (msg) {
2099 case WM_INITDIALOG:
2100 #ifdef _WIN32_WCE
2102 char *title;
2104 fe = (frontend *) lParam;
2105 SetWindowLong(hwnd, GWL_USERDATA, lParam);
2106 fe->cfgbox = hwnd;
2108 fe->cfg = frontend_get_config(fe, fe->cfg_which, &title);
2110 make_dialog_full_screen(hwnd);
2112 SetDlgItemTextA(hwnd, IDC_CONFIG_CAPTION, title);
2113 SendDlgItemMessage(hwnd, IDC_CONFIG_CAPTION, WM_SETFONT,
2114 (WPARAM) dialog_title_font(), 0);
2116 create_config_controls(fe);
2118 #endif
2119 return TRUE;
2121 case WM_COMMAND:
2123 * OK and Cancel are special cases.
2125 if ((LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
2126 if (LOWORD(wParam) == IDOK) {
2127 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
2129 if (err) {
2130 MessageBox(hwnd, err, "Validation error",
2131 MB_ICONERROR | MB_OK);
2132 } else {
2133 #ifdef _WIN32_WCE
2134 EndDialog(hwnd, 2);
2135 #else
2136 fe->dlg_done = 2;
2137 #endif
2139 } else {
2140 #ifdef _WIN32_WCE
2141 EndDialog(hwnd, 1);
2142 #else
2143 fe->dlg_done = 1;
2144 #endif
2146 return 0;
2150 * First find the control whose id this is.
2152 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2153 if (j->ctlid == LOWORD(wParam))
2154 break;
2156 if (i->type == C_END)
2157 return 0; /* not our problem */
2159 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
2160 char buffer[4096];
2161 #ifdef _WIN32_WCE
2162 TCHAR wBuffer[4096];
2163 GetDlgItemText(fe->cfgbox, j->ctlid, wBuffer, 4096);
2164 WideCharToMultiByte(CP_ACP, 0, wBuffer, -1, buffer, 4096, NULL, NULL);
2165 #else
2166 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
2167 #endif
2168 buffer[lenof(buffer)-1] = '\0';
2169 sfree(i->sval);
2170 i->sval = dupstr(buffer);
2171 } else if (i->type == C_BOOLEAN &&
2172 (HIWORD(wParam) == BN_CLICKED ||
2173 HIWORD(wParam) == BN_DBLCLK)) {
2174 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
2175 } else if (i->type == C_CHOICES &&
2176 HIWORD(wParam) == CBN_SELCHANGE) {
2177 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
2178 CB_GETCURSEL, 0, 0);
2181 return 0;
2183 case WM_CLOSE:
2184 fe->dlg_done = 1;
2185 return 0;
2188 return 0;
2191 #ifndef _WIN32_WCE
2192 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2193 char *wclass, int wstyle,
2194 int exstyle, const char *wtext, int wid)
2196 HWND ret;
2197 ret = CreateWindowEx(exstyle, wclass, wtext,
2198 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
2199 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2200 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
2201 return ret;
2203 #endif
2205 static void about(frontend *fe)
2207 #ifdef _WIN32_WCE
2208 DialogBox(fe->inst, MAKEINTRESOURCE(IDD_ABOUT), fe->hwnd, AboutDlgProc);
2209 #else
2210 int i;
2211 WNDCLASS wc;
2212 MSG msg;
2213 TEXTMETRIC tm;
2214 HDC hdc;
2215 HFONT oldfont;
2216 SIZE size;
2217 int gm, id;
2218 int winwidth, winheight, y;
2219 int height, width, maxwid;
2220 const char *strings[16];
2221 int lengths[16];
2222 int nstrings = 0;
2223 char titlebuf[512];
2225 sprintf(titlebuf, "About %.250s", fe->game->name);
2227 strings[nstrings++] = fe->game->name;
2228 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
2229 strings[nstrings++] = ver;
2231 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2232 wc.lpfnWndProc = DefDlgProc;
2233 wc.cbClsExtra = 0;
2234 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2235 wc.hInstance = fe->inst;
2236 wc.hIcon = NULL;
2237 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2238 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2239 wc.lpszMenuName = NULL;
2240 wc.lpszClassName = "GameAboutBox";
2241 RegisterClass(&wc);
2243 hdc = GetDC(fe->hwnd);
2244 SetMapMode(hdc, MM_TEXT);
2246 fe->dlg_done = FALSE;
2248 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2249 0, 0, 0, 0,
2250 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2251 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2252 DEFAULT_QUALITY,
2253 FF_SWISS,
2254 "MS Shell Dlg");
2256 oldfont = SelectObject(hdc, fe->cfgfont);
2257 if (GetTextMetrics(hdc, &tm)) {
2258 height = tm.tmAscent + tm.tmDescent;
2259 width = tm.tmAveCharWidth;
2260 } else {
2261 height = width = 30;
2265 * Figure out the layout of the About box by measuring the
2266 * length of each piece of text.
2268 maxwid = 0;
2269 winheight = height/2;
2271 for (i = 0; i < nstrings; i++) {
2272 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
2273 lengths[i] = size.cx;
2274 else
2275 lengths[i] = 0; /* *shrug* */
2276 if (maxwid < lengths[i])
2277 maxwid = lengths[i];
2278 winheight += height * 3 / 2 + (height / 2);
2281 winheight += height + height * 7 / 4; /* OK button */
2282 winwidth = maxwid + 4*width;
2284 SelectObject(hdc, oldfont);
2285 ReleaseDC(fe->hwnd, hdc);
2288 * Create the dialog, now that we know its size.
2291 RECT r, r2;
2293 r.left = r.top = 0;
2294 r.right = winwidth;
2295 r.bottom = winheight;
2297 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2298 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2299 WS_CAPTION | WS_SYSMENU*/) &~
2300 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2301 FALSE, 0);
2304 * Centre the dialog on its parent window.
2306 r.right -= r.left;
2307 r.bottom -= r.top;
2308 GetWindowRect(fe->hwnd, &r2);
2309 r.left = (r2.left + r2.right - r.right) / 2;
2310 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2311 r.right += r.left;
2312 r.bottom += r.top;
2314 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
2315 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2316 WS_CAPTION | WS_SYSMENU,
2317 r.left, r.top,
2318 r.right-r.left, r.bottom-r.top,
2319 fe->hwnd, NULL, fe->inst, NULL);
2322 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2324 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2325 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
2327 id = 1000;
2328 y = height/2;
2329 for (i = 0; i < nstrings; i++) {
2330 int border = width*2 + (maxwid - lengths[i]) / 2;
2331 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
2332 "Static", 0, 0, strings[i], id++);
2333 y += height*3/2;
2335 assert(y < winheight);
2336 y += height/2;
2339 y += height/2; /* extra space before OK */
2340 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
2341 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2342 "OK", IDOK);
2344 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2346 EnableWindow(fe->hwnd, FALSE);
2347 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2348 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2349 if (!IsDialogMessage(fe->cfgbox, &msg))
2350 DispatchMessage(&msg);
2351 if (fe->dlg_done)
2352 break;
2354 EnableWindow(fe->hwnd, TRUE);
2355 SetForegroundWindow(fe->hwnd);
2356 DestroyWindow(fe->cfgbox);
2357 DeleteObject(fe->cfgfont);
2358 #endif
2361 static int get_config(frontend *fe, int which)
2363 #ifdef _WIN32_WCE
2364 fe->cfg_which = which;
2366 return DialogBoxParam(fe->inst,
2367 MAKEINTRESOURCE(IDD_CONFIG),
2368 fe->hwnd, ConfigDlgProc,
2369 (LPARAM) fe) == 2;
2370 #else
2371 config_item *i;
2372 struct cfg_aux *j;
2373 char *title;
2374 WNDCLASS wc;
2375 MSG msg;
2376 TEXTMETRIC tm;
2377 HDC hdc;
2378 HFONT oldfont;
2379 SIZE size;
2380 HWND ctl;
2381 int gm, id, nctrls;
2382 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
2383 int height, width, maxlabel, maxcheckbox;
2385 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2386 wc.lpfnWndProc = DefDlgProc;
2387 wc.cbClsExtra = 0;
2388 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2389 wc.hInstance = fe->inst;
2390 wc.hIcon = NULL;
2391 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2392 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2393 wc.lpszMenuName = NULL;
2394 wc.lpszClassName = "GameConfigBox";
2395 RegisterClass(&wc);
2397 hdc = GetDC(fe->hwnd);
2398 SetMapMode(hdc, MM_TEXT);
2400 fe->dlg_done = FALSE;
2402 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2403 0, 0, 0, 0,
2404 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2405 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2406 DEFAULT_QUALITY,
2407 FF_SWISS,
2408 "MS Shell Dlg");
2410 oldfont = SelectObject(hdc, fe->cfgfont);
2411 if (GetTextMetrics(hdc, &tm)) {
2412 height = tm.tmAscent + tm.tmDescent;
2413 width = tm.tmAveCharWidth;
2414 } else {
2415 height = width = 30;
2418 fe->cfg = frontend_get_config(fe, which, &title);
2419 fe->cfg_which = which;
2422 * Figure out the layout of the config box by measuring the
2423 * length of each piece of text.
2425 maxlabel = maxcheckbox = 0;
2426 winheight = height/2;
2428 for (i = fe->cfg; i->type != C_END; i++) {
2429 switch (i->type) {
2430 case C_STRING:
2431 case C_CHOICES:
2433 * Both these control types have a label filling only
2434 * the left-hand column of the box.
2436 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2437 maxlabel < size.cx)
2438 maxlabel = size.cx;
2439 winheight += height * 3 / 2 + (height / 2);
2440 break;
2442 case C_BOOLEAN:
2444 * Checkboxes take up the whole of the box width.
2446 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2447 maxcheckbox < size.cx)
2448 maxcheckbox = size.cx;
2449 winheight += height + (height / 2);
2450 break;
2454 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
2456 col1l = 2*width;
2457 col1r = col1l + maxlabel;
2458 col2l = col1r + 2*width;
2459 col2r = col2l + 30*width;
2460 if (col2r < col1l+2*height+maxcheckbox)
2461 col2r = col1l+2*height+maxcheckbox;
2462 winwidth = col2r + 2*width;
2464 SelectObject(hdc, oldfont);
2465 ReleaseDC(fe->hwnd, hdc);
2468 * Create the dialog, now that we know its size.
2471 RECT r, r2;
2473 r.left = r.top = 0;
2474 r.right = winwidth;
2475 r.bottom = winheight;
2477 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2478 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2479 WS_CAPTION | WS_SYSMENU*/) &~
2480 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2481 FALSE, 0);
2484 * Centre the dialog on its parent window.
2486 r.right -= r.left;
2487 r.bottom -= r.top;
2488 GetWindowRect(fe->hwnd, &r2);
2489 r.left = (r2.left + r2.right - r.right) / 2;
2490 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2491 r.right += r.left;
2492 r.bottom += r.top;
2494 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
2495 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2496 WS_CAPTION | WS_SYSMENU,
2497 r.left, r.top,
2498 r.right-r.left, r.bottom-r.top,
2499 fe->hwnd, NULL, fe->inst, NULL);
2500 sfree(title);
2503 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2505 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2506 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
2509 * Count the controls so we can allocate cfgaux.
2511 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2512 nctrls++;
2513 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2515 id = 1000;
2516 y = height/2;
2517 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2518 switch (i->type) {
2519 case C_STRING:
2521 * Edit box with a label beside it.
2523 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2524 "Static", 0, 0, i->name, id++);
2525 ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
2526 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
2527 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2528 SetWindowText(ctl, i->sval);
2529 y += height*3/2;
2530 break;
2532 case C_BOOLEAN:
2534 * Simple checkbox.
2536 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
2537 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2538 0, i->name, (j->ctlid = id++));
2539 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2540 y += height;
2541 break;
2543 case C_CHOICES:
2545 * Drop-down list with a label beside it.
2547 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2548 "STATIC", 0, 0, i->name, id++);
2549 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
2550 "COMBOBOX", WS_TABSTOP |
2551 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2552 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2554 char c, *p, *q, *str;
2556 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
2557 p = i->sval;
2558 c = *p++;
2559 while (*p) {
2560 q = p;
2561 while (*q && *q != c) q++;
2562 str = snewn(q-p+1, char);
2563 strncpy(str, p, q-p);
2564 str[q-p] = '\0';
2565 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
2566 sfree(str);
2567 if (*q) q++;
2568 p = q;
2572 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2574 y += height*3/2;
2575 break;
2578 assert(y < winheight);
2579 y += height/2;
2582 y += height/2; /* extra space before OK and Cancel */
2583 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
2584 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2585 "OK", IDOK);
2586 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
2587 BS_PUSHBUTTON | WS_TABSTOP, 0, "Cancel", IDCANCEL);
2589 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2591 EnableWindow(fe->hwnd, FALSE);
2592 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2593 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2594 if (!IsDialogMessage(fe->cfgbox, &msg))
2595 DispatchMessage(&msg);
2596 if (fe->dlg_done)
2597 break;
2599 EnableWindow(fe->hwnd, TRUE);
2600 SetForegroundWindow(fe->hwnd);
2601 DestroyWindow(fe->cfgbox);
2602 DeleteObject(fe->cfgfont);
2604 free_cfg(fe->cfg);
2605 sfree(fe->cfgaux);
2607 return (fe->dlg_done == 2);
2608 #endif
2611 #ifdef _WIN32_WCE
2612 static void calculate_bitmap_position(frontend *fe, int x, int y)
2614 /* Pocket PC - center the game in the full screen window */
2615 int yMargin;
2616 RECT rcClient;
2618 GetClientRect(fe->hwnd, &rcClient);
2619 fe->bitmapPosition.left = (rcClient.right - x) / 2;
2620 yMargin = rcClient.bottom - y;
2622 if (fe->numpad != NULL) {
2623 RECT rcPad;
2624 GetWindowRect(fe->numpad, &rcPad);
2625 yMargin -= rcPad.bottom - rcPad.top;
2628 if (fe->statusbar != NULL) {
2629 RECT rcStatus;
2630 GetWindowRect(fe->statusbar, &rcStatus);
2631 yMargin -= rcStatus.bottom - rcStatus.top;
2634 fe->bitmapPosition.top = yMargin / 2;
2636 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2637 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2639 #else
2640 static void calculate_bitmap_position(frontend *fe, int x, int y)
2642 /* Plain Windows - position the game in the upper-left corner */
2643 fe->bitmapPosition.left = 0;
2644 fe->bitmapPosition.top = 0;
2645 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2646 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2648 #endif
2650 static void new_bitmap(frontend *fe, int x, int y)
2652 HDC hdc;
2654 if (fe->bitmap) DeleteObject(fe->bitmap);
2656 hdc = GetDC(fe->hwnd);
2657 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2658 calculate_bitmap_position(fe, x, y);
2659 ReleaseDC(fe->hwnd, hdc);
2662 static void new_game_size(frontend *fe, float scale)
2664 RECT r, sr;
2665 int x, y;
2667 get_max_puzzle_size(fe, &x, &y);
2668 midend_size(fe->me, &x, &y, FALSE);
2670 if (scale != 1.0) {
2671 x = (int)((float)x * fe->puzz_scale);
2672 y = (int)((float)y * fe->puzz_scale);
2673 midend_size(fe->me, &x, &y, TRUE);
2675 fe->ymin = (fe->xmin * y) / x;
2677 r.left = r.top = 0;
2678 r.right = x;
2679 r.bottom = y;
2680 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2682 if (fe->statusbar != NULL) {
2683 GetWindowRect(fe->statusbar, &sr);
2684 } else {
2685 sr.left = sr.right = sr.top = sr.bottom = 0;
2687 #ifndef _WIN32_WCE
2688 SetWindowPos(fe->hwnd, NULL, 0, 0,
2689 r.right - r.left,
2690 r.bottom - r.top + sr.bottom - sr.top,
2691 SWP_NOMOVE | SWP_NOZORDER);
2692 #endif
2694 check_window_size(fe, &x, &y);
2696 #ifndef _WIN32_WCE
2697 if (fe->statusbar != NULL)
2698 SetWindowPos(fe->statusbar, NULL, 0, y, x,
2699 sr.bottom - sr.top, SWP_NOZORDER);
2700 #endif
2702 new_bitmap(fe, x, y);
2704 #ifdef _WIN32_WCE
2705 InvalidateRect(fe->hwnd, NULL, TRUE);
2706 #endif
2707 midend_redraw(fe->me);
2711 * Given a proposed new window rect, work out the resulting
2712 * difference in client size (from current), and use to try
2713 * and resize the puzzle, returning (wx,wy) as the actual
2714 * new window size.
2717 static void adjust_game_size(frontend *fe, RECT *proposed, int isedge,
2718 int *wx_r, int *wy_r)
2720 RECT cr, wr;
2721 int nx, ny, xdiff, ydiff, wx, wy;
2723 /* Work out the current window sizing, and thus the
2724 * difference in size we're asking for. */
2725 GetClientRect(fe->hwnd, &cr);
2726 wr = cr;
2727 AdjustWindowRectEx(&wr, WINFLAGS, TRUE, 0);
2729 xdiff = (proposed->right - proposed->left) - (wr.right - wr.left);
2730 ydiff = (proposed->bottom - proposed->top) - (wr.bottom - wr.top);
2732 if (isedge) {
2733 /* These next four lines work around the fact that midend_size
2734 * is happy to shrink _but not grow_ if you change one dimension
2735 * but not the other. */
2736 if (xdiff > 0 && ydiff == 0)
2737 ydiff = (xdiff * (wr.right - wr.left)) / (wr.bottom - wr.top);
2738 if (xdiff == 0 && ydiff > 0)
2739 xdiff = (ydiff * (wr.bottom - wr.top)) / (wr.right - wr.left);
2742 if (check_window_resize(fe,
2743 (cr.right - cr.left) + xdiff,
2744 (cr.bottom - cr.top) + ydiff,
2745 &nx, &ny, &wx, &wy)) {
2746 new_bitmap(fe, nx, ny);
2747 midend_force_redraw(fe->me);
2748 } else {
2749 /* reset size to current window size */
2750 wx = wr.right - wr.left;
2751 wy = wr.bottom - wr.top;
2753 /* Re-fetch rectangle; size limits mean we might not have
2754 * taken it quite to the mouse drag positions. */
2755 GetClientRect(fe->hwnd, &cr);
2756 adjust_statusbar(fe, &cr);
2758 *wx_r = wx; *wy_r = wy;
2761 static void update_type_menu_tick(frontend *fe)
2763 int total, n, i;
2765 if (fe->typemenu == INVALID_HANDLE_VALUE)
2766 return;
2768 total = GetMenuItemCount(fe->typemenu);
2769 n = midend_which_preset(fe->me);
2770 if (n < 0)
2771 n = total - 1; /* "Custom" item */
2773 for (i = 0; i < total; i++) {
2774 int flag = (i == n ? MF_CHECKED : MF_UNCHECKED);
2775 CheckMenuItem(fe->typemenu, i, MF_BYPOSITION | flag);
2778 DrawMenuBar(fe->hwnd);
2781 static void update_copy_menu_greying(frontend *fe)
2783 UINT enable = (midend_can_format_as_text_now(fe->me) ?
2784 MF_ENABLED : MF_GRAYED);
2785 EnableMenuItem(fe->gamemenu, IDM_COPY, MF_BYCOMMAND | enable);
2788 static void new_game_type(frontend *fe)
2790 midend_new_game(fe->me);
2791 new_game_size(fe, 1.0);
2792 update_type_menu_tick(fe);
2793 update_copy_menu_greying(fe);
2796 static int is_alt_pressed(void)
2798 BYTE keystate[256];
2799 int r = GetKeyboardState(keystate);
2800 if (!r)
2801 return FALSE;
2802 if (keystate[VK_MENU] & 0x80)
2803 return TRUE;
2804 if (keystate[VK_RMENU] & 0x80)
2805 return TRUE;
2806 return FALSE;
2809 static void savefile_write(void *wctx, void *buf, int len)
2811 FILE *fp = (FILE *)wctx;
2812 fwrite(buf, 1, len, fp);
2815 static int savefile_read(void *wctx, void *buf, int len)
2817 FILE *fp = (FILE *)wctx;
2818 int ret;
2820 ret = fread(buf, 1, len, fp);
2821 return (ret == len);
2824 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2825 WPARAM wParam, LPARAM lParam)
2827 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2828 int cmd;
2830 switch (message) {
2831 case WM_CLOSE:
2832 DestroyWindow(hwnd);
2833 return 0;
2834 case WM_COMMAND:
2835 #ifdef _WIN32_WCE
2836 /* Numeric pad sends WM_COMMAND messages */
2837 if ((wParam >= IDM_KEYEMUL) && (wParam < IDM_KEYEMUL + 256))
2839 midend_process_key(fe->me, 0, 0, wParam - IDM_KEYEMUL);
2841 #endif
2842 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
2843 switch (cmd) {
2844 case IDM_NEW:
2845 if (!midend_process_key(fe->me, 0, 0, 'n'))
2846 PostQuitMessage(0);
2847 break;
2848 case IDM_RESTART:
2849 midend_restart_game(fe->me);
2850 break;
2851 case IDM_UNDO:
2852 if (!midend_process_key(fe->me, 0, 0, 'u'))
2853 PostQuitMessage(0);
2854 break;
2855 case IDM_REDO:
2856 if (!midend_process_key(fe->me, 0, 0, '\x12'))
2857 PostQuitMessage(0);
2858 break;
2859 case IDM_COPY:
2861 char *text = midend_text_format(fe->me);
2862 if (text)
2863 write_clip(hwnd, text);
2864 else
2865 MessageBeep(MB_ICONWARNING);
2866 sfree(text);
2868 break;
2869 case IDM_SOLVE:
2871 char *msg = midend_solve(fe->me);
2872 if (msg)
2873 MessageBox(hwnd, msg, "Unable to solve",
2874 MB_ICONERROR | MB_OK);
2876 break;
2877 case IDM_QUIT:
2878 if (!midend_process_key(fe->me, 0, 0, 'q'))
2879 PostQuitMessage(0);
2880 break;
2881 case IDM_CONFIG:
2882 if (get_config(fe, CFG_SETTINGS))
2883 new_game_type(fe);
2884 break;
2885 case IDM_SEED:
2886 if (get_config(fe, CFG_SEED))
2887 new_game_type(fe);
2888 break;
2889 case IDM_DESC:
2890 if (get_config(fe, CFG_DESC))
2891 new_game_type(fe);
2892 break;
2893 case IDM_PRINT:
2894 if (get_config(fe, CFG_PRINT))
2895 print(fe);
2896 break;
2897 case IDM_ABOUT:
2898 about(fe);
2899 break;
2900 case IDM_LOAD:
2901 case IDM_SAVE:
2903 OPENFILENAME of;
2904 char filename[FILENAME_MAX];
2905 int ret;
2907 memset(&of, 0, sizeof(of));
2908 of.hwndOwner = hwnd;
2909 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
2910 of.lpstrCustomFilter = NULL;
2911 of.nFilterIndex = 1;
2912 of.lpstrFile = filename;
2913 filename[0] = '\0';
2914 of.nMaxFile = lenof(filename);
2915 of.lpstrFileTitle = NULL;
2916 of.lpstrTitle = (cmd == IDM_SAVE ?
2917 "Enter name of game file to save" :
2918 "Enter name of saved game file to load");
2919 of.Flags = 0;
2920 #ifdef OPENFILENAME_SIZE_VERSION_400
2921 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2922 #else
2923 of.lStructSize = sizeof(of);
2924 #endif
2925 of.lpstrInitialDir = NULL;
2927 if (cmd == IDM_SAVE)
2928 ret = GetSaveFileName(&of);
2929 else
2930 ret = GetOpenFileName(&of);
2932 if (ret) {
2933 if (cmd == IDM_SAVE) {
2934 FILE *fp;
2936 if ((fp = fopen(filename, "r")) != NULL) {
2937 char buf[256 + FILENAME_MAX];
2938 fclose(fp);
2939 /* file exists */
2941 sprintf(buf, "Are you sure you want to overwrite"
2942 " the file \"%.*s\"?",
2943 FILENAME_MAX, filename);
2944 if (MessageBox(hwnd, buf, "Question",
2945 MB_YESNO | MB_ICONQUESTION)
2946 != IDYES)
2947 break;
2950 fp = fopen(filename, "w");
2952 if (!fp) {
2953 MessageBox(hwnd, "Unable to open save file",
2954 "Error", MB_ICONERROR | MB_OK);
2955 break;
2958 midend_serialise(fe->me, savefile_write, fp);
2960 fclose(fp);
2961 } else {
2962 FILE *fp = fopen(filename, "r");
2963 char *err;
2965 if (!fp) {
2966 MessageBox(hwnd, "Unable to open saved game file",
2967 "Error", MB_ICONERROR | MB_OK);
2968 break;
2971 err = midend_deserialise(fe->me, savefile_read, fp);
2973 fclose(fp);
2975 if (err) {
2976 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
2977 break;
2980 new_game_size(fe, 1.0);
2985 break;
2986 #ifndef _WIN32_WCE
2987 case IDM_HELPC:
2988 start_help(fe, NULL);
2989 break;
2990 case IDM_GAMEHELP:
2991 assert(help_type != NONE);
2992 start_help(fe, help_type == CHM ?
2993 fe->game->htmlhelp_topic : fe->game->winhelp_topic);
2994 break;
2995 #endif
2996 default:
2997 #ifdef COMBINED
2998 if (wParam >= IDM_GAMES && wParam < (IDM_GAMES + (WPARAM)gamecount)) {
2999 int p = wParam - IDM_GAMES;
3000 char *error;
3002 new_game(fe, gamelist[p], NULL, &error);
3003 } else
3004 #endif
3006 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
3008 if (p >= 0 && p < fe->npresets) {
3009 midend_set_params(fe->me, fe->presets[p]);
3010 new_game_type(fe);
3013 break;
3015 break;
3016 case WM_DESTROY:
3017 #ifndef _WIN32_WCE
3018 stop_help(fe);
3019 #endif
3020 frontend_free(fe);
3021 PostQuitMessage(0);
3022 return 0;
3023 case WM_PAINT:
3025 PAINTSTRUCT p;
3026 HDC hdc, hdc2;
3027 HBITMAP prevbm;
3028 RECT rcDest;
3030 hdc = BeginPaint(hwnd, &p);
3031 hdc2 = CreateCompatibleDC(hdc);
3032 prevbm = SelectObject(hdc2, fe->bitmap);
3033 #ifdef _WIN32_WCE
3034 FillRect(hdc, &(p.rcPaint), (HBRUSH) GetStockObject(WHITE_BRUSH));
3035 #endif
3036 IntersectRect(&rcDest, &(fe->bitmapPosition), &(p.rcPaint));
3037 BitBlt(hdc,
3038 rcDest.left, rcDest.top,
3039 rcDest.right - rcDest.left,
3040 rcDest.bottom - rcDest.top,
3041 hdc2,
3042 rcDest.left - fe->bitmapPosition.left,
3043 rcDest.top - fe->bitmapPosition.top,
3044 SRCCOPY);
3045 SelectObject(hdc2, prevbm);
3046 DeleteDC(hdc2);
3047 EndPaint(hwnd, &p);
3049 return 0;
3050 case WM_KEYDOWN:
3052 int key = -1;
3053 BYTE keystate[256];
3054 int r = GetKeyboardState(keystate);
3055 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
3056 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
3058 switch (wParam) {
3059 case VK_LEFT:
3060 if (!(lParam & 0x01000000))
3061 key = MOD_NUM_KEYPAD | '4';
3062 else
3063 key = shift | ctrl | CURSOR_LEFT;
3064 break;
3065 case VK_RIGHT:
3066 if (!(lParam & 0x01000000))
3067 key = MOD_NUM_KEYPAD | '6';
3068 else
3069 key = shift | ctrl | CURSOR_RIGHT;
3070 break;
3071 case VK_UP:
3072 if (!(lParam & 0x01000000))
3073 key = MOD_NUM_KEYPAD | '8';
3074 else
3075 key = shift | ctrl | CURSOR_UP;
3076 break;
3077 case VK_DOWN:
3078 if (!(lParam & 0x01000000))
3079 key = MOD_NUM_KEYPAD | '2';
3080 else
3081 key = shift | ctrl | CURSOR_DOWN;
3082 break;
3084 * Diagonal keys on the numeric keypad.
3086 case VK_PRIOR:
3087 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
3088 break;
3089 case VK_NEXT:
3090 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
3091 break;
3092 case VK_HOME:
3093 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
3094 break;
3095 case VK_END:
3096 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
3097 break;
3098 case VK_INSERT:
3099 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
3100 break;
3101 case VK_CLEAR:
3102 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
3103 break;
3105 * Numeric keypad keys with Num Lock on.
3107 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
3108 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
3109 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
3110 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
3111 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
3112 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
3113 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
3114 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
3115 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
3116 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
3119 if (key != -1) {
3120 if (!midend_process_key(fe->me, 0, 0, key))
3121 PostQuitMessage(0);
3122 } else {
3123 MSG m;
3124 m.hwnd = hwnd;
3125 m.message = WM_KEYDOWN;
3126 m.wParam = wParam;
3127 m.lParam = lParam & 0xdfff;
3128 TranslateMessage(&m);
3131 break;
3132 case WM_LBUTTONDOWN:
3133 case WM_RBUTTONDOWN:
3134 case WM_MBUTTONDOWN:
3136 int button;
3139 * Shift-clicks count as middle-clicks, since otherwise
3140 * two-button Windows users won't have any kind of
3141 * middle click to use.
3143 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
3144 button = MIDDLE_BUTTON;
3145 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
3146 button = RIGHT_BUTTON;
3147 else
3148 #ifndef _WIN32_WCE
3149 button = LEFT_BUTTON;
3150 #else
3151 if ((fe->game->flags & REQUIRE_RBUTTON) == 0)
3152 button = LEFT_BUTTON;
3153 else
3155 SHRGINFO shrgi;
3157 shrgi.cbSize = sizeof(SHRGINFO);
3158 shrgi.hwndClient = hwnd;
3159 shrgi.ptDown.x = (signed short)LOWORD(lParam);
3160 shrgi.ptDown.y = (signed short)HIWORD(lParam);
3161 shrgi.dwFlags = SHRG_RETURNCMD;
3163 if (GN_CONTEXTMENU == SHRecognizeGesture(&shrgi))
3164 button = RIGHT_BUTTON;
3165 else
3166 button = LEFT_BUTTON;
3168 #endif
3170 if (!midend_process_key(fe->me,
3171 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3172 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3173 button))
3174 PostQuitMessage(0);
3176 SetCapture(hwnd);
3178 break;
3179 case WM_LBUTTONUP:
3180 case WM_RBUTTONUP:
3181 case WM_MBUTTONUP:
3183 int button;
3186 * Shift-clicks count as middle-clicks, since otherwise
3187 * two-button Windows users won't have any kind of
3188 * middle click to use.
3190 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
3191 button = MIDDLE_RELEASE;
3192 else if (message == WM_RBUTTONUP || is_alt_pressed())
3193 button = RIGHT_RELEASE;
3194 else
3195 button = LEFT_RELEASE;
3197 if (!midend_process_key(fe->me,
3198 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3199 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3200 button))
3201 PostQuitMessage(0);
3203 ReleaseCapture();
3205 break;
3206 case WM_MOUSEMOVE:
3208 int button;
3210 if (wParam & (MK_MBUTTON | MK_SHIFT))
3211 button = MIDDLE_DRAG;
3212 else if (wParam & MK_RBUTTON || is_alt_pressed())
3213 button = RIGHT_DRAG;
3214 else
3215 button = LEFT_DRAG;
3217 if (!midend_process_key(fe->me,
3218 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3219 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3220 button))
3221 PostQuitMessage(0);
3223 break;
3224 case WM_CHAR:
3225 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
3226 PostQuitMessage(0);
3227 return 0;
3228 case WM_TIMER:
3229 if (fe->timer) {
3230 DWORD now = GetTickCount();
3231 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
3232 midend_timer(fe->me, elapsed);
3233 fe->timer_last_tickcount = now;
3235 return 0;
3236 #ifndef _WIN32_WCE
3237 case WM_SIZING:
3239 RECT *sr = (RECT *)lParam;
3240 int wx, wy, isedge = 0;
3242 if (wParam == WMSZ_TOP ||
3243 wParam == WMSZ_RIGHT ||
3244 wParam == WMSZ_BOTTOM ||
3245 wParam == WMSZ_LEFT) isedge = 1;
3246 adjust_game_size(fe, sr, isedge, &wx, &wy);
3248 /* Given the window size the puzzles constrain
3249 * us to, work out which edge we should be moving. */
3250 if (wParam == WMSZ_TOP ||
3251 wParam == WMSZ_TOPLEFT ||
3252 wParam == WMSZ_TOPRIGHT) {
3253 sr->top = sr->bottom - wy;
3254 } else {
3255 sr->bottom = sr->top + wy;
3257 if (wParam == WMSZ_LEFT ||
3258 wParam == WMSZ_TOPLEFT ||
3259 wParam == WMSZ_BOTTOMLEFT) {
3260 sr->left = sr->right - wx;
3261 } else {
3262 sr->right = sr->left + wx;
3264 return TRUE;
3266 break;
3267 #endif
3270 return DefWindowProc(hwnd, message, wParam, lParam);
3273 #ifdef _WIN32_WCE
3274 static int FindPreviousInstance()
3276 /* Check if application is running. If it's running then focus on the window */
3277 HWND hOtherWnd = NULL;
3279 hOtherWnd = FindWindow (wGameName, wGameName);
3280 if (hOtherWnd)
3282 SetForegroundWindow (hOtherWnd);
3283 return TRUE;
3286 return FALSE;
3288 #endif
3290 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
3292 MSG msg;
3293 char *error;
3294 const game *gg;
3295 frontend *fe;
3297 #ifdef _WIN32_WCE
3298 MultiByteToWideChar (CP_ACP, 0, CLASSNAME, -1, wClassName, 256);
3299 if (FindPreviousInstance ())
3300 return 0;
3301 #endif
3303 InitCommonControls();
3305 if (!prev) {
3306 WNDCLASS wndclass;
3308 wndclass.style = 0;
3309 wndclass.lpfnWndProc = WndProc;
3310 wndclass.cbClsExtra = 0;
3311 wndclass.cbWndExtra = 0;
3312 wndclass.hInstance = inst;
3313 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
3314 #ifndef _WIN32_WCE
3315 if (!wndclass.hIcon) /* in case resource file is absent */
3316 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
3317 #endif
3318 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
3319 wndclass.hbrBackground = NULL;
3320 wndclass.lpszMenuName = NULL;
3321 #ifdef _WIN32_WCE
3322 wndclass.lpszClassName = wClassName;
3323 #else
3324 wndclass.lpszClassName = CLASSNAME;
3325 #endif
3327 RegisterClass(&wndclass);
3330 while (*cmdline && isspace((unsigned char)*cmdline))
3331 cmdline++;
3333 init_help();
3335 #ifdef COMBINED
3336 gg = gamelist[0];
3338 int i;
3339 for (i = 0; i < gamecount; i++) {
3340 const char *p = gamelist[i]->name;
3341 char *q = cmdline;
3342 while (*q && isspace((unsigned char)*q))
3343 q++;
3344 while (*p && *q) {
3345 if (isspace((unsigned char)*p)) {
3346 while (*q && isspace((unsigned char)*q))
3347 q++;
3348 } else {
3349 if (tolower((unsigned char)*p) !=
3350 tolower((unsigned char)*q))
3351 break;
3352 q++;
3354 p++;
3356 if (!*p) {
3357 gg = gamelist[i];
3358 cmdline = q;
3359 if (*cmdline) {
3360 while (*cmdline && isspace((unsigned char)*cmdline))
3361 cmdline++;
3366 #else
3367 gg = &thegame;
3368 #endif
3370 fe = frontend_new(inst);
3371 if (new_game(fe, gg, *cmdline ? cmdline : NULL, &error)) {
3372 char buf[128];
3373 sprintf(buf, "%.100s Error", gg->name);
3374 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
3375 return 1;
3377 show_window(fe);
3379 while (GetMessage(&msg, NULL, 0, 0)) {
3380 DispatchMessage(&msg);
3383 cleanup_help();
3385 return msg.wParam;
3387 /* vim: set shiftwidth=4 tabstop=8: */