Fix bug in --save caused by failure to initialise ctx.error to zero
[sgt-puzzles/ydirson.git] / windows.c
blob7bdb5e2bdcef279fbaf2b190402ab28506172434
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;
157 static int debugging = -1;
159 if (debugging == -1)
160 debugging = getenv("DEBUG_PUZZLES") ? 1 : 0;
162 if (debugging) {
163 va_start(ap, fmt);
164 _vsnprintf(buf, 4095, fmt, ap);
165 dputs(buf);
166 va_end(ap);
169 #endif
171 #ifndef _WIN32_WCE
172 #define WINFLAGS (WS_OVERLAPPEDWINDOW &~ \
173 (WS_MAXIMIZEBOX | WS_OVERLAPPED))
174 #else
175 #define WINFLAGS (WS_CAPTION | WS_SYSMENU)
176 #endif
178 static void new_game_size(frontend *fe, float scale);
180 struct font {
181 HFONT font;
182 int type;
183 int size;
186 struct cfg_aux {
187 int ctlid;
190 struct blitter {
191 HBITMAP bitmap;
192 frontend *fe;
193 int x, y, w, h;
196 enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
198 struct frontend {
199 const game *game;
200 midend *me;
201 HWND hwnd, statusbar, cfgbox;
202 #ifdef _WIN32_WCE
203 HWND numpad; /* window handle for the numeric pad */
204 #endif
205 HINSTANCE inst;
206 HBITMAP bitmap, prevbm;
207 RECT bitmapPosition; /* game bitmap position within game window */
208 HDC hdc;
209 COLORREF *colours;
210 HBRUSH *brushes;
211 HPEN *pens;
212 HRGN clip;
213 HMENU gamemenu, typemenu;
214 UINT timer;
215 DWORD timer_last_tickcount;
216 int npresets;
217 game_params **presets;
218 struct font *fonts;
219 int nfonts, fontsize;
220 config_item *cfg;
221 struct cfg_aux *cfgaux;
222 int cfg_which, dlg_done;
223 HFONT cfgfont;
224 HBRUSH oldbr;
225 HPEN oldpen;
226 int help_running;
227 enum { DRAWING, PRINTING, NOTHING } drawstatus;
228 DOCINFO di;
229 int printcount, printw, printh, printsolns, printcurr, printcolour;
230 float printscale;
231 int printoffsetx, printoffsety;
232 float printpixelscale;
233 int fontstart;
234 int linewidth, linedotted;
235 drawing *dr;
236 int xmin, ymin;
237 float puzz_scale;
240 void frontend_free(frontend *fe)
242 midend_free(fe->me);
244 sfree(fe->colours);
245 sfree(fe->brushes);
246 sfree(fe->pens);
247 sfree(fe->presets);
248 sfree(fe->fonts);
250 sfree(fe);
253 static void update_type_menu_tick(frontend *fe);
254 static void update_copy_menu_greying(frontend *fe);
256 void fatal(char *fmt, ...)
258 char buf[2048];
259 va_list ap;
261 va_start(ap, fmt);
262 vsprintf(buf, fmt, ap);
263 va_end(ap);
265 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
267 exit(1);
270 char *geterrstr(void)
272 LPVOID lpMsgBuf;
273 DWORD dw = GetLastError();
274 char *ret;
276 FormatMessage(
277 FORMAT_MESSAGE_ALLOCATE_BUFFER |
278 FORMAT_MESSAGE_FROM_SYSTEM,
279 NULL,
281 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
282 (LPTSTR) &lpMsgBuf,
283 0, NULL );
285 ret = dupstr(lpMsgBuf);
287 LocalFree(lpMsgBuf);
289 return ret;
292 void get_random_seed(void **randseed, int *randseedsize)
294 SYSTEMTIME *st = snew(SYSTEMTIME);
296 GetLocalTime(st);
298 *randseed = (void *)st;
299 *randseedsize = sizeof(SYSTEMTIME);
302 static void win_status_bar(void *handle, char *text)
304 #ifdef _WIN32_WCE
305 TCHAR wText[255];
306 #endif
307 frontend *fe = (frontend *)handle;
309 #ifdef _WIN32_WCE
310 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 255);
311 SendMessage(fe->statusbar, SB_SETTEXT,
312 (WPARAM) 255 | SBT_NOBORDERS,
313 (LPARAM) wText);
314 #else
315 SetWindowText(fe->statusbar, text);
316 #endif
319 static blitter *win_blitter_new(void *handle, int w, int h)
321 blitter *bl = snew(blitter);
323 memset(bl, 0, sizeof(blitter));
324 bl->w = w;
325 bl->h = h;
326 bl->bitmap = 0;
328 return bl;
331 static void win_blitter_free(void *handle, blitter *bl)
333 if (bl->bitmap) DeleteObject(bl->bitmap);
334 sfree(bl);
337 static void blitter_mkbitmap(frontend *fe, blitter *bl)
339 HDC hdc = GetDC(fe->hwnd);
340 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
341 ReleaseDC(fe->hwnd, hdc);
344 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
346 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
348 frontend *fe = (frontend *)handle;
349 HDC hdc_win, hdc_blit;
350 HBITMAP prev_blit;
352 assert(fe->drawstatus == DRAWING);
354 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
356 bl->x = x; bl->y = y;
358 hdc_win = GetDC(fe->hwnd);
359 hdc_blit = CreateCompatibleDC(hdc_win);
360 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
362 prev_blit = SelectObject(hdc_blit, bl->bitmap);
363 if (prev_blit == NULL || prev_blit == HGDI_ERROR)
364 fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
366 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
367 fe->hdc, x, y, SRCCOPY))
368 fatal("BitBlt failed: 0x%x", GetLastError());
370 SelectObject(hdc_blit, prev_blit);
371 DeleteDC(hdc_blit);
372 ReleaseDC(fe->hwnd, hdc_win);
375 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
377 frontend *fe = (frontend *)handle;
378 HDC hdc_win, hdc_blit;
379 HBITMAP prev_blit;
381 assert(fe->drawstatus == DRAWING);
383 assert(bl->bitmap); /* we should always have saved before loading */
385 if (x == BLITTER_FROMSAVED) x = bl->x;
386 if (y == BLITTER_FROMSAVED) y = bl->y;
388 hdc_win = GetDC(fe->hwnd);
389 hdc_blit = CreateCompatibleDC(hdc_win);
391 prev_blit = SelectObject(hdc_blit, bl->bitmap);
393 BitBlt(fe->hdc, x, y, bl->w, bl->h,
394 hdc_blit, 0, 0, SRCCOPY);
396 SelectObject(hdc_blit, prev_blit);
397 DeleteDC(hdc_blit);
398 ReleaseDC(fe->hwnd, hdc_win);
401 void frontend_default_colour(frontend *fe, float *output)
403 DWORD c = GetSysColor(COLOR_MENU); /* ick */
405 output[0] = (float)(GetRValue(c) / 255.0);
406 output[1] = (float)(GetGValue(c) / 255.0);
407 output[2] = (float)(GetBValue(c) / 255.0);
410 static POINT win_transform_point(frontend *fe, int x, int y)
412 POINT ret;
414 assert(fe->drawstatus != NOTHING);
416 if (fe->drawstatus == PRINTING) {
417 ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
418 ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
419 } else {
420 ret.x = x;
421 ret.y = y;
424 return ret;
427 static void win_text_colour(frontend *fe, int colour)
429 assert(fe->drawstatus != NOTHING);
431 if (fe->drawstatus == PRINTING) {
432 int hatch;
433 float r, g, b;
434 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
437 * Displaying text in hatched colours is not permitted.
439 assert(hatch < 0);
441 SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
442 } else {
443 SetTextColor(fe->hdc, fe->colours[colour]);
447 static void win_set_brush(frontend *fe, int colour)
449 HBRUSH br;
450 assert(fe->drawstatus != NOTHING);
452 if (fe->drawstatus == PRINTING) {
453 int hatch;
454 float r, g, b;
455 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
457 if (hatch < 0) {
458 br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
459 } else {
460 #ifdef _WIN32_WCE
462 * This is only ever required during printing, and the
463 * PocketPC port doesn't support printing.
465 fatal("CreateHatchBrush not supported");
466 #else
467 br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
468 hatch == HATCH_SLASH ? HS_BDIAGONAL :
469 hatch == HATCH_HORIZ ? HS_HORIZONTAL :
470 hatch == HATCH_VERT ? HS_VERTICAL :
471 hatch == HATCH_PLUS ? HS_CROSS :
472 /* hatch == HATCH_X ? */ HS_DIAGCROSS,
473 RGB(0,0,0));
474 #endif
476 } else {
477 br = fe->brushes[colour];
479 fe->oldbr = SelectObject(fe->hdc, br);
482 static void win_reset_brush(frontend *fe)
484 HBRUSH br;
486 assert(fe->drawstatus != NOTHING);
488 br = SelectObject(fe->hdc, fe->oldbr);
489 if (fe->drawstatus == PRINTING)
490 DeleteObject(br);
493 static void win_set_pen(frontend *fe, int colour, int thin)
495 HPEN pen;
496 assert(fe->drawstatus != NOTHING);
498 if (fe->drawstatus == PRINTING) {
499 int hatch;
500 float r, g, b;
501 int width = thin ? 0 : fe->linewidth;
503 if (fe->linedotted)
504 width = 0;
506 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
508 * Stroking in hatched colours is not permitted.
510 assert(hatch < 0);
511 pen = CreatePen(fe->linedotted ? PS_DOT : PS_SOLID,
512 width, RGB(r * 255, g * 255, b * 255));
513 } else {
514 pen = fe->pens[colour];
516 fe->oldpen = SelectObject(fe->hdc, pen);
519 static void win_reset_pen(frontend *fe)
521 HPEN pen;
523 assert(fe->drawstatus != NOTHING);
525 pen = SelectObject(fe->hdc, fe->oldpen);
526 if (fe->drawstatus == PRINTING)
527 DeleteObject(pen);
530 static void win_clip(void *handle, int x, int y, int w, int h)
532 frontend *fe = (frontend *)handle;
533 POINT p, q;
535 if (fe->drawstatus == NOTHING)
536 return;
538 p = win_transform_point(fe, x, y);
539 q = win_transform_point(fe, x+w, y+h);
540 IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
543 static void win_unclip(void *handle)
545 frontend *fe = (frontend *)handle;
547 if (fe->drawstatus == NOTHING)
548 return;
550 SelectClipRgn(fe->hdc, NULL);
553 static void win_draw_text(void *handle, int x, int y, int fonttype,
554 int fontsize, int align, int colour, char *text)
556 frontend *fe = (frontend *)handle;
557 POINT xy;
558 int i;
559 LOGFONT lf;
561 if (fe->drawstatus == NOTHING)
562 return;
564 if (fe->drawstatus == PRINTING)
565 fontsize = (int)(fontsize * fe->printpixelscale);
567 xy = win_transform_point(fe, x, y);
570 * Find or create the font.
572 for (i = fe->fontstart; i < fe->nfonts; i++)
573 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
574 break;
576 if (i == fe->nfonts) {
577 if (fe->fontsize <= fe->nfonts) {
578 fe->fontsize = fe->nfonts + 10;
579 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
582 fe->nfonts++;
584 fe->fonts[i].type = fonttype;
585 fe->fonts[i].size = fontsize;
587 memset (&lf, 0, sizeof(LOGFONT));
588 lf.lfHeight = -fontsize;
589 lf.lfWeight = (fe->drawstatus == PRINTING ? 0 : FW_BOLD);
590 lf.lfCharSet = DEFAULT_CHARSET;
591 lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
592 lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
593 lf.lfQuality = DEFAULT_QUALITY;
594 lf.lfPitchAndFamily = (fonttype == FONT_FIXED ?
595 FIXED_PITCH | FF_DONTCARE :
596 VARIABLE_PITCH | FF_SWISS);
597 #ifdef _WIN32_WCE
598 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
599 #endif
601 fe->fonts[i].font = CreateFontIndirect(&lf);
605 * Position and draw the text.
608 HFONT oldfont;
609 TEXTMETRIC tm;
610 SIZE size;
611 TCHAR wText[256];
612 MultiByteToWideChar (CP_UTF8, 0, text, -1, wText, 256);
614 oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
615 if (GetTextMetrics(fe->hdc, &tm)) {
616 if (align & ALIGN_VCENTRE)
617 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
618 else
619 xy.y -= tm.tmAscent;
621 if (GetTextExtentPoint32W(fe->hdc, wText, wcslen(wText), &size))
623 if (align & ALIGN_HCENTRE)
624 xy.x -= size.cx / 2;
625 else if (align & ALIGN_HRIGHT)
626 xy.x -= size.cx;
628 SetBkMode(fe->hdc, TRANSPARENT);
629 win_text_colour(fe, colour);
630 ExtTextOutW(fe->hdc, xy.x, xy.y, 0, NULL, wText, wcslen(wText), NULL);
631 SelectObject(fe->hdc, oldfont);
635 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
637 frontend *fe = (frontend *)handle;
638 POINT p, q;
640 if (fe->drawstatus == NOTHING)
641 return;
643 if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
645 * Rectangle() appears to get uppity if asked to draw a 1x1
646 * rectangle, presumably on the grounds that that's beneath
647 * its dignity and you ought to be using SetPixel instead.
648 * So I will.
650 SetPixel(fe->hdc, x, y, fe->colours[colour]);
651 } else {
652 win_set_brush(fe, colour);
653 win_set_pen(fe, colour, TRUE);
654 p = win_transform_point(fe, x, y);
655 q = win_transform_point(fe, x+w, y+h);
656 Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
657 win_reset_brush(fe);
658 win_reset_pen(fe);
662 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
664 frontend *fe = (frontend *)handle;
665 POINT pp[2];
667 if (fe->drawstatus == NOTHING)
668 return;
670 win_set_pen(fe, colour, FALSE);
671 pp[0] = win_transform_point(fe, x1, y1);
672 pp[1] = win_transform_point(fe, x2, y2);
673 Polyline(fe->hdc, pp, 2);
674 if (fe->drawstatus == DRAWING)
675 SetPixel(fe->hdc, pp[1].x, pp[1].y, fe->colours[colour]);
676 win_reset_pen(fe);
679 static void win_draw_circle(void *handle, int cx, int cy, int radius,
680 int fillcolour, int outlinecolour)
682 frontend *fe = (frontend *)handle;
683 POINT p, q;
685 assert(outlinecolour >= 0);
687 if (fe->drawstatus == NOTHING)
688 return;
690 if (fillcolour >= 0)
691 win_set_brush(fe, fillcolour);
692 else
693 fe->oldbr = SelectObject(fe->hdc, GetStockObject(NULL_BRUSH));
695 win_set_pen(fe, outlinecolour, FALSE);
696 p = win_transform_point(fe, cx - radius, cy - radius);
697 q = win_transform_point(fe, cx + radius, cy + radius);
698 Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
699 win_reset_brush(fe);
700 win_reset_pen(fe);
703 static void win_draw_polygon(void *handle, int *coords, int npoints,
704 int fillcolour, int outlinecolour)
706 frontend *fe = (frontend *)handle;
707 POINT *pts;
708 int i;
710 if (fe->drawstatus == NOTHING)
711 return;
713 pts = snewn(npoints+1, POINT);
715 for (i = 0; i <= npoints; i++) {
716 int j = (i < npoints ? i : 0);
717 pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
720 assert(outlinecolour >= 0);
722 if (fillcolour >= 0) {
723 win_set_brush(fe, fillcolour);
724 win_set_pen(fe, outlinecolour, FALSE);
725 Polygon(fe->hdc, pts, npoints);
726 win_reset_brush(fe);
727 win_reset_pen(fe);
728 } else {
729 win_set_pen(fe, outlinecolour, FALSE);
730 Polyline(fe->hdc, pts, npoints+1);
731 win_reset_pen(fe);
734 sfree(pts);
737 static void win_start_draw(void *handle)
739 frontend *fe = (frontend *)handle;
740 HDC hdc_win;
742 assert(fe->drawstatus == NOTHING);
744 hdc_win = GetDC(fe->hwnd);
745 fe->hdc = CreateCompatibleDC(hdc_win);
746 fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
747 ReleaseDC(fe->hwnd, hdc_win);
748 fe->clip = NULL;
749 #ifndef _WIN32_WCE
750 SetMapMode(fe->hdc, MM_TEXT);
751 #endif
752 fe->drawstatus = DRAWING;
755 static void win_draw_update(void *handle, int x, int y, int w, int h)
757 frontend *fe = (frontend *)handle;
758 RECT r;
760 if (fe->drawstatus != DRAWING)
761 return;
763 r.left = x;
764 r.top = y;
765 r.right = x + w;
766 r.bottom = y + h;
768 OffsetRect(&r, fe->bitmapPosition.left, fe->bitmapPosition.top);
769 InvalidateRect(fe->hwnd, &r, FALSE);
772 static void win_end_draw(void *handle)
774 frontend *fe = (frontend *)handle;
775 assert(fe->drawstatus == DRAWING);
776 SelectObject(fe->hdc, fe->prevbm);
777 DeleteDC(fe->hdc);
778 if (fe->clip) {
779 DeleteObject(fe->clip);
780 fe->clip = NULL;
782 fe->drawstatus = NOTHING;
785 static void win_line_width(void *handle, float width)
787 frontend *fe = (frontend *)handle;
789 assert(fe->drawstatus != DRAWING);
790 if (fe->drawstatus == NOTHING)
791 return;
793 fe->linewidth = (int)(width * fe->printpixelscale);
796 static void win_line_dotted(void *handle, int dotted)
798 frontend *fe = (frontend *)handle;
800 assert(fe->drawstatus != DRAWING);
801 if (fe->drawstatus == NOTHING)
802 return;
804 fe->linedotted = dotted;
807 static void win_begin_doc(void *handle, int pages)
809 frontend *fe = (frontend *)handle;
811 assert(fe->drawstatus != DRAWING);
812 if (fe->drawstatus == NOTHING)
813 return;
815 if (StartDoc(fe->hdc, &fe->di) <= 0) {
816 char *e = geterrstr();
817 MessageBox(fe->hwnd, e, "Error starting to print",
818 MB_ICONERROR | MB_OK);
819 sfree(e);
820 fe->drawstatus = NOTHING;
824 * Push a marker on the font stack so that we won't use the
825 * same fonts for printing and drawing. (This is because
826 * drawing seems to look generally better in bold, but printing
827 * is better not in bold.)
829 fe->fontstart = fe->nfonts;
832 static void win_begin_page(void *handle, int number)
834 frontend *fe = (frontend *)handle;
836 assert(fe->drawstatus != DRAWING);
837 if (fe->drawstatus == NOTHING)
838 return;
840 if (StartPage(fe->hdc) <= 0) {
841 char *e = geterrstr();
842 MessageBox(fe->hwnd, e, "Error starting a page",
843 MB_ICONERROR | MB_OK);
844 sfree(e);
845 fe->drawstatus = NOTHING;
849 static void win_begin_puzzle(void *handle, float xm, float xc,
850 float ym, float yc, int pw, int ph, float wmm)
852 frontend *fe = (frontend *)handle;
853 int ppw, pph, pox, poy;
854 float mmpw, mmph, mmox, mmoy;
855 float scale;
857 assert(fe->drawstatus != DRAWING);
858 if (fe->drawstatus == NOTHING)
859 return;
861 ppw = GetDeviceCaps(fe->hdc, HORZRES);
862 pph = GetDeviceCaps(fe->hdc, VERTRES);
863 mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
864 mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
867 * Compute the puzzle's position on the logical page.
869 mmox = xm * mmpw + xc;
870 mmoy = ym * mmph + yc;
873 * Work out what that comes to in pixels.
875 pox = (int)(mmox * (float)ppw / mmpw);
876 poy = (int)(mmoy * (float)pph / mmph);
879 * And determine the scale.
881 * I need a scale such that the maximum puzzle-coordinate
882 * extent of the rectangle (pw * scale) is equal to the pixel
883 * equivalent of the puzzle's millimetre width (wmm * ppw /
884 * mmpw).
886 scale = (wmm * ppw) / (mmpw * pw);
889 * Now store pox, poy and scale for use in the main drawing
890 * functions.
892 fe->printoffsetx = pox;
893 fe->printoffsety = poy;
894 fe->printpixelscale = scale;
896 fe->linewidth = 1;
897 fe->linedotted = FALSE;
900 static void win_end_puzzle(void *handle)
902 /* Nothing needs to be done here. */
905 static void win_end_page(void *handle, int number)
907 frontend *fe = (frontend *)handle;
909 assert(fe->drawstatus != DRAWING);
911 if (fe->drawstatus == NOTHING)
912 return;
914 if (EndPage(fe->hdc) <= 0) {
915 char *e = geterrstr();
916 MessageBox(fe->hwnd, e, "Error finishing a page",
917 MB_ICONERROR | MB_OK);
918 sfree(e);
919 fe->drawstatus = NOTHING;
923 static void win_end_doc(void *handle)
925 frontend *fe = (frontend *)handle;
927 assert(fe->drawstatus != DRAWING);
930 * Free all the fonts created since we began printing.
932 while (fe->nfonts > fe->fontstart) {
933 fe->nfonts--;
934 DeleteObject(fe->fonts[fe->nfonts].font);
936 fe->fontstart = 0;
939 * The MSDN web site sample code doesn't bother to call EndDoc
940 * if an error occurs half way through printing. I expect doing
941 * so would cause the erroneous document to actually be
942 * printed, or something equally undesirable.
944 if (fe->drawstatus == NOTHING)
945 return;
947 if (EndDoc(fe->hdc) <= 0) {
948 char *e = geterrstr();
949 MessageBox(fe->hwnd, e, "Error finishing printing",
950 MB_ICONERROR | MB_OK);
951 sfree(e);
952 fe->drawstatus = NOTHING;
956 char *win_text_fallback(void *handle, const char *const *strings, int nstrings)
959 * We assume Windows can cope with any UTF-8 likely to be
960 * emitted by a puzzle.
962 return dupstr(strings[0]);
965 const struct drawing_api win_drawing = {
966 win_draw_text,
967 win_draw_rect,
968 win_draw_line,
969 win_draw_polygon,
970 win_draw_circle,
971 win_draw_update,
972 win_clip,
973 win_unclip,
974 win_start_draw,
975 win_end_draw,
976 win_status_bar,
977 win_blitter_new,
978 win_blitter_free,
979 win_blitter_save,
980 win_blitter_load,
981 win_begin_doc,
982 win_begin_page,
983 win_begin_puzzle,
984 win_end_puzzle,
985 win_end_page,
986 win_end_doc,
987 win_line_width,
988 win_line_dotted,
989 win_text_fallback,
992 void print(frontend *fe)
994 #ifndef _WIN32_WCE
995 PRINTDLG pd;
996 char doctitle[256];
997 document *doc;
998 midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
999 int i;
1000 char *err = NULL;
1003 * Create our document structure and fill it up with puzzles.
1005 doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
1006 for (i = 0; i < fe->printcount; i++) {
1007 if (i == 0 && fe->printcurr) {
1008 err = midend_print_puzzle(fe->me, doc, fe->printsolns);
1009 } else {
1010 if (!nme) {
1011 game_params *params;
1013 nme = midend_new(NULL, fe->game, NULL, NULL);
1016 * Set the non-interactive mid-end to have the same
1017 * parameters as the standard one.
1019 params = midend_get_params(fe->me);
1020 midend_set_params(nme, params);
1021 fe->game->free_params(params);
1024 midend_new_game(nme);
1025 err = midend_print_puzzle(nme, doc, fe->printsolns);
1027 if (err)
1028 break;
1030 if (nme)
1031 midend_free(nme);
1033 if (err) {
1034 MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
1035 MB_ICONERROR | MB_OK);
1036 document_free(doc);
1037 return;
1040 memset(&pd, 0, sizeof(pd));
1041 pd.lStructSize = sizeof(pd);
1042 pd.hwndOwner = fe->hwnd;
1043 pd.hDevMode = NULL;
1044 pd.hDevNames = NULL;
1045 pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
1046 PD_NOPAGENUMS | PD_NOSELECTION;
1047 pd.nCopies = 1;
1048 pd.nFromPage = pd.nToPage = 0xFFFF;
1049 pd.nMinPage = pd.nMaxPage = 1;
1051 if (!PrintDlg(&pd)) {
1052 document_free(doc);
1053 return;
1057 * Now pd.hDC is a device context for the printer.
1061 * FIXME: IWBNI we put up an Abort box here.
1064 memset(&fe->di, 0, sizeof(fe->di));
1065 fe->di.cbSize = sizeof(fe->di);
1066 sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
1067 " Portable Puzzle Collection)", fe->game->name);
1068 fe->di.lpszDocName = doctitle;
1069 fe->di.lpszOutput = NULL;
1070 fe->di.lpszDatatype = NULL;
1071 fe->di.fwType = 0;
1073 fe->drawstatus = PRINTING;
1074 fe->hdc = pd.hDC;
1076 fe->dr = drawing_new(&win_drawing, NULL, fe);
1077 document_print(doc, fe->dr);
1078 drawing_free(fe->dr);
1079 fe->dr = NULL;
1081 fe->drawstatus = NOTHING;
1083 DeleteDC(pd.hDC);
1084 document_free(doc);
1085 #endif
1088 void deactivate_timer(frontend *fe)
1090 if (!fe)
1091 return; /* for non-interactive midend */
1092 if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
1093 fe->timer = 0;
1096 void activate_timer(frontend *fe)
1098 if (!fe)
1099 return; /* for non-interactive midend */
1100 if (!fe->timer) {
1101 fe->timer = SetTimer(fe->hwnd, 1, 20, NULL);
1102 fe->timer_last_tickcount = GetTickCount();
1106 void write_clip(HWND hwnd, char *data)
1108 HGLOBAL clipdata;
1109 int len, i, j;
1110 char *data2;
1111 void *lock;
1114 * Windows expects CRLF in the clipboard, so we must convert
1115 * any \n that has come out of the puzzle backend.
1117 len = 0;
1118 for (i = 0; data[i]; i++) {
1119 if (data[i] == '\n')
1120 len++;
1121 len++;
1123 data2 = snewn(len+1, char);
1124 j = 0;
1125 for (i = 0; data[i]; i++) {
1126 if (data[i] == '\n')
1127 data2[j++] = '\r';
1128 data2[j++] = data[i];
1130 assert(j == len);
1131 data2[j] = '\0';
1133 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
1134 if (!clipdata) {
1135 sfree(data2);
1136 return;
1138 lock = GlobalLock(clipdata);
1139 if (!lock) {
1140 GlobalFree(clipdata);
1141 sfree(data2);
1142 return;
1144 memcpy(lock, data2, len);
1145 ((unsigned char *) lock)[len] = 0;
1146 GlobalUnlock(clipdata);
1148 if (OpenClipboard(hwnd)) {
1149 EmptyClipboard();
1150 SetClipboardData(CF_TEXT, clipdata);
1151 CloseClipboard();
1152 } else
1153 GlobalFree(clipdata);
1155 sfree(data2);
1159 * Set up Help and see if we can find a help file.
1161 static void init_help(void)
1163 #ifndef _WIN32_WCE
1164 char b[2048], *p, *q, *r;
1165 FILE *fp;
1168 * Find the executable file path, so we can look alongside
1169 * it for help files. Trim the filename off the end.
1171 GetModuleFileName(NULL, b, sizeof(b) - 1);
1172 r = b;
1173 p = strrchr(b, '\\');
1174 if (p && p >= r) r = p+1;
1175 q = strrchr(b, ':');
1176 if (q && q >= r) r = q+1;
1178 #ifndef NO_HTMLHELP
1180 * Try HTML Help first.
1182 strcpy(r, CHM_FILE_NAME);
1183 if ( (fp = fopen(b, "r")) != NULL) {
1184 fclose(fp);
1187 * We have a .CHM. See if we can use it.
1189 hh_dll = LoadLibrary("hhctrl.ocx");
1190 if (hh_dll) {
1191 htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
1192 if (!htmlhelp)
1193 FreeLibrary(hh_dll);
1195 if (htmlhelp) {
1196 help_path = dupstr(b);
1197 help_type = CHM;
1198 return;
1201 #endif /* NO_HTMLHELP */
1204 * Now try old-style .HLP.
1206 strcpy(r, HELP_FILE_NAME);
1207 if ( (fp = fopen(b, "r")) != NULL) {
1208 fclose(fp);
1210 help_path = dupstr(b);
1211 help_type = HLP;
1214 * See if there's a .CNT file alongside it.
1216 strcpy(r, HELP_CNT_NAME);
1217 if ( (fp = fopen(b, "r")) != NULL) {
1218 fclose(fp);
1219 help_has_contents = TRUE;
1220 } else
1221 help_has_contents = FALSE;
1223 return;
1226 help_type = NONE; /* didn't find any */
1227 #endif
1230 #ifndef _WIN32_WCE
1233 * Start Help.
1235 static void start_help(frontend *fe, const char *topic)
1237 char *str = NULL;
1238 int cmd;
1240 switch (help_type) {
1241 case HLP:
1242 assert(help_path);
1243 if (topic) {
1244 str = snewn(10+strlen(topic), char);
1245 sprintf(str, "JI(`',`%s')", topic);
1246 cmd = HELP_COMMAND;
1247 } else if (help_has_contents) {
1248 cmd = HELP_FINDER;
1249 } else {
1250 cmd = HELP_CONTENTS;
1252 WinHelp(fe->hwnd, help_path, cmd, (DWORD)str);
1253 fe->help_running = TRUE;
1254 break;
1255 case CHM:
1256 #ifndef NO_HTMLHELP
1257 assert(help_path);
1258 assert(htmlhelp);
1259 if (topic) {
1260 str = snewn(20 + strlen(topic) + strlen(help_path), char);
1261 sprintf(str, "%s::/%s.html>main", help_path, topic);
1262 } else {
1263 str = dupstr(help_path);
1265 htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
1266 fe->help_running = TRUE;
1267 break;
1268 #endif /* NO_HTMLHELP */
1269 case NONE:
1270 assert(!"This shouldn't happen");
1271 break;
1274 sfree(str);
1278 * Stop Help on window cleanup.
1280 static void stop_help(frontend *fe)
1282 if (fe->help_running) {
1283 switch (help_type) {
1284 case HLP:
1285 WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
1286 break;
1287 case CHM:
1288 #ifndef NO_HTMLHELP
1289 assert(htmlhelp);
1290 htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
1291 break;
1292 #endif /* NO_HTMLHELP */
1293 case NONE:
1294 assert(!"This shouldn't happen");
1295 break;
1297 fe->help_running = FALSE;
1301 #endif
1304 * Terminate Help on process exit.
1306 static void cleanup_help(void)
1308 /* Nothing to do currently.
1309 * (If we were running HTML Help single-threaded, this is where we'd
1310 * call HH_UNINITIALIZE.) */
1313 static int get_statusbar_height(frontend *fe)
1315 int sy;
1316 if (fe->statusbar) {
1317 RECT sr;
1318 GetWindowRect(fe->statusbar, &sr);
1319 sy = sr.bottom - sr.top;
1320 } else {
1321 sy = 0;
1323 return sy;
1326 static void adjust_statusbar(frontend *fe, RECT *r)
1328 int sy;
1330 if (!fe->statusbar) return;
1332 sy = get_statusbar_height(fe);
1333 #ifndef _WIN32_WCE
1334 SetWindowPos(fe->statusbar, NULL, 0, r->bottom-r->top-sy, r->right-r->left,
1335 sy, SWP_NOZORDER);
1336 #endif
1339 static void get_menu_size(HWND wh, RECT *r)
1341 HMENU bar = GetMenu(wh);
1342 RECT rect;
1343 int i;
1345 SetRect(r, 0, 0, 0, 0);
1346 for (i = 0; i < GetMenuItemCount(bar); i++) {
1347 GetMenuItemRect(wh, bar, i, &rect);
1348 UnionRect(r, r, &rect);
1353 * Given a proposed new puzzle size (cx,cy), work out the actual
1354 * puzzle size that would be (px,py) and the window size including
1355 * furniture (wx,wy).
1358 static int check_window_resize(frontend *fe, int cx, int cy,
1359 int *px, int *py,
1360 int *wx, int *wy)
1362 RECT r;
1363 int x, y, sy = get_statusbar_height(fe), changed = 0;
1365 /* disallow making window thinner than menu bar */
1366 x = max(cx, fe->xmin);
1367 y = max(cy - sy, fe->ymin);
1370 * See if we actually got the window size we wanted, and adjust
1371 * the puzzle size if not.
1373 midend_size(fe->me, &x, &y, TRUE);
1374 if (x != cx || y != cy) {
1376 * Resize the window, now we know what size we _really_
1377 * want it to be.
1379 r.left = r.top = 0;
1380 r.right = x;
1381 r.bottom = y + sy;
1382 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1383 *wx = r.right - r.left;
1384 *wy = r.bottom - r.top;
1385 changed = 1;
1388 *px = x;
1389 *py = y;
1391 fe->puzz_scale =
1392 (float)midend_tilesize(fe->me) / (float)fe->game->preferred_tilesize;
1394 return changed;
1398 * Given the current window size, make sure it's sane for the
1399 * current puzzle and resize if necessary.
1402 static void check_window_size(frontend *fe, int *px, int *py)
1404 RECT r;
1405 int wx, wy, cx, cy;
1407 GetClientRect(fe->hwnd, &r);
1408 cx = r.right - r.left;
1409 cy = r.bottom - r.top;
1411 if (check_window_resize(fe, cx, cy, px, py, &wx, &wy)) {
1412 #ifdef _WIN32_WCE
1413 SetWindowPos(fe->hwnd, NULL, 0, 0, wx, wy,
1414 SWP_NOMOVE | SWP_NOZORDER);
1415 #endif
1419 GetClientRect(fe->hwnd, &r);
1420 adjust_statusbar(fe, &r);
1423 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1425 RECT r, sr;
1427 if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1428 *x = sr.right - sr.left;
1429 *y = sr.bottom - sr.top;
1430 r.left = 100;
1431 r.right = 200;
1432 r.top = 100;
1433 r.bottom = 200;
1434 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1435 *x -= r.right - r.left - 100;
1436 *y -= r.bottom - r.top - 100;
1437 } else {
1438 *x = *y = INT_MAX;
1441 if (fe->statusbar != NULL) {
1442 GetWindowRect(fe->statusbar, &sr);
1443 *y -= sr.bottom - sr.top;
1447 #ifdef _WIN32_WCE
1448 /* Toolbar buttons on the numeric pad */
1449 static TBBUTTON tbNumpadButtons[] =
1451 {0, IDM_KEYEMUL + '1', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1452 {1, IDM_KEYEMUL + '2', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1453 {2, IDM_KEYEMUL + '3', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1454 {3, IDM_KEYEMUL + '4', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1455 {4, IDM_KEYEMUL + '5', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1456 {5, IDM_KEYEMUL + '6', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1457 {6, IDM_KEYEMUL + '7', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1458 {7, IDM_KEYEMUL + '8', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1459 {8, IDM_KEYEMUL + '9', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1460 {9, IDM_KEYEMUL + ' ', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1}
1462 #endif
1465 * Allocate a new frontend structure and create its main window.
1467 static frontend *frontend_new(HINSTANCE inst)
1469 frontend *fe;
1470 const char *nogame = "Puzzles (no game selected)";
1472 fe = snew(frontend);
1474 fe->inst = inst;
1476 fe->game = NULL;
1477 fe->me = NULL;
1479 fe->timer = 0;
1480 fe->hwnd = NULL;
1482 fe->help_running = FALSE;
1484 fe->drawstatus = NOTHING;
1485 fe->dr = NULL;
1486 fe->fontstart = 0;
1488 fe->fonts = NULL;
1489 fe->nfonts = fe->fontsize = 0;
1491 fe->colours = NULL;
1492 fe->brushes = NULL;
1493 fe->pens = NULL;
1495 fe->puzz_scale = 1.0;
1497 #ifdef _WIN32_WCE
1498 MultiByteToWideChar (CP_ACP, 0, nogame, -1, wGameName, 256);
1499 fe->hwnd = CreateWindowEx(0, wClassName, wGameName,
1500 WS_VISIBLE,
1501 CW_USEDEFAULT, CW_USEDEFAULT,
1502 CW_USEDEFAULT, CW_USEDEFAULT,
1503 NULL, NULL, inst, NULL);
1506 SHMENUBARINFO mbi;
1507 RECT rc, rcBar, rcTB, rcClient;
1509 memset (&mbi, 0, sizeof(SHMENUBARINFO));
1510 mbi.cbSize = sizeof(SHMENUBARINFO);
1511 mbi.hwndParent = fe->hwnd;
1512 mbi.nToolBarId = IDR_MENUBAR1;
1513 mbi.hInstRes = inst;
1515 SHCreateMenuBar(&mbi);
1517 GetWindowRect(fe->hwnd, &rc);
1518 GetWindowRect(mbi.hwndMB, &rcBar);
1519 rc.bottom -= rcBar.bottom - rcBar.top;
1520 MoveWindow(fe->hwnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, FALSE);
1522 fe->numpad = NULL;
1524 #else
1525 fe->hwnd = CreateWindowEx(0, CLASSNAME, nogame,
1526 WS_OVERLAPPEDWINDOW &~
1527 (WS_MAXIMIZEBOX),
1528 CW_USEDEFAULT, CW_USEDEFAULT,
1529 CW_USEDEFAULT, CW_USEDEFAULT,
1530 NULL, NULL, inst, NULL);
1531 if (!fe->hwnd) {
1532 DWORD lerr = GetLastError();
1533 printf("no window: 0x%x\n", lerr);
1535 #endif
1537 fe->gamemenu = NULL;
1538 fe->presets = NULL;
1540 fe->statusbar = NULL;
1541 fe->bitmap = NULL;
1543 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1545 return fe;
1549 * Populate a frontend structure with a (new) game and midend structure, and
1550 * create any window furniture that it needs.
1552 * Previously-allocated memory and window furniture will be freed by this function.
1554 static int new_game(frontend *fe, const game *game, char *game_id, char **error)
1556 int x, y;
1557 RECT r;
1559 fe->game = game;
1561 if (fe->me) midend_free(fe->me);
1562 fe->me = midend_new(fe, fe->game, &win_drawing, fe);
1564 if (game_id) {
1565 *error = midend_game_id(fe->me, game_id);
1566 if (*error) {
1567 midend_free(fe->me);
1568 sfree(fe);
1569 return -1;
1573 midend_new_game(fe->me);
1576 int i, ncolours;
1577 float *colours;
1579 colours = midend_colours(fe->me, &ncolours);
1581 if (fe->colours) sfree(fe->colours);
1582 if (fe->brushes) sfree(fe->brushes);
1583 if (fe->pens) sfree(fe->pens);
1585 fe->colours = snewn(ncolours, COLORREF);
1586 fe->brushes = snewn(ncolours, HBRUSH);
1587 fe->pens = snewn(ncolours, HPEN);
1589 for (i = 0; i < ncolours; i++) {
1590 fe->colours[i] = RGB(255 * colours[i*3+0],
1591 255 * colours[i*3+1],
1592 255 * colours[i*3+2]);
1593 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1594 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1596 sfree(colours);
1599 if (fe->statusbar)
1600 DestroyWindow(fe->statusbar);
1601 if (midend_wants_statusbar(fe->me)) {
1602 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1603 WS_CHILD | WS_VISIBLE,
1604 0, 0, 0, 0, /* status bar does these */
1605 NULL, NULL, fe->inst, NULL);
1606 } else
1607 fe->statusbar = NULL;
1609 get_max_puzzle_size(fe, &x, &y);
1610 midend_size(fe->me, &x, &y, FALSE);
1612 r.left = r.top = 0;
1613 r.right = x;
1614 r.bottom = y;
1615 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1617 #ifdef _WIN32_WCE
1618 if (fe->numpad)
1619 DestroyWindow(fe->numpad);
1620 if (fe->game->flags & REQUIRE_NUMPAD)
1622 fe->numpad = CreateToolbarEx (fe->hwnd,
1623 WS_VISIBLE | WS_CHILD | CCS_NOPARENTALIGN | TBSTYLE_FLAT,
1624 0, 10, fe->inst, IDR_PADTOOLBAR,
1625 tbNumpadButtons, sizeof (tbNumpadButtons) / sizeof (TBBUTTON),
1626 0, 0, 14, 15, sizeof (TBBUTTON));
1627 GetWindowRect(fe->numpad, &rcTB);
1628 GetClientRect(fe->hwnd, &rcClient);
1629 MoveWindow(fe->numpad,
1631 rcClient.bottom - (rcTB.bottom - rcTB.top) - 1,
1632 rcClient.right,
1633 rcTB.bottom - rcTB.top,
1634 FALSE);
1635 SendMessage(fe->numpad, TB_SETINDENT, (rcClient.right - (10 * 21)) / 2, 0);
1637 else {
1638 fe->numpad = NULL;
1640 MultiByteToWideChar (CP_ACP, 0, fe->game->name, -1, wGameName, 256);
1641 SetWindowText(fe->hwnd, wGameName);
1642 #else
1643 SetWindowText(fe->hwnd, fe->game->name);
1644 #endif
1646 if (fe->statusbar)
1647 DestroyWindow(fe->statusbar);
1648 if (midend_wants_statusbar(fe->me)) {
1649 RECT sr;
1650 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1651 WS_CHILD | WS_VISIBLE,
1652 0, 0, 0, 0, /* status bar does these */
1653 fe->hwnd, NULL, fe->inst, NULL);
1654 #ifdef _WIN32_WCE
1655 /* Flat status bar looks better on the Pocket PC */
1656 SendMessage(fe->statusbar, SB_SIMPLE, (WPARAM) TRUE, 0);
1657 SendMessage(fe->statusbar, SB_SETTEXT,
1658 (WPARAM) 255 | SBT_NOBORDERS,
1659 (LPARAM) L"");
1660 #endif
1663 * Now resize the window to take account of the status bar.
1665 GetWindowRect(fe->statusbar, &sr);
1666 GetWindowRect(fe->hwnd, &r);
1667 #ifndef _WIN32_WCE
1668 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1669 r.bottom - r.top + sr.bottom - sr.top,
1670 SWP_NOMOVE | SWP_NOZORDER);
1671 #endif
1672 } else {
1673 fe->statusbar = NULL;
1677 HMENU oldmenu = GetMenu(fe->hwnd);
1679 #ifndef _WIN32_WCE
1680 HMENU bar = CreateMenu();
1681 HMENU menu = CreateMenu();
1682 RECT menusize;
1684 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "&Game");
1685 #else
1686 HMENU menu = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_GAME);
1687 DeleteMenu(menu, 0, MF_BYPOSITION);
1688 #endif
1689 fe->gamemenu = menu;
1690 AppendMenu(menu, MF_ENABLED, IDM_NEW, TEXT("&New"));
1691 AppendMenu(menu, MF_ENABLED, IDM_RESTART, TEXT("&Restart"));
1692 #ifndef _WIN32_WCE
1693 /* ...here I run out of sensible accelerator characters. */
1694 AppendMenu(menu, MF_ENABLED, IDM_DESC, TEXT("Speci&fic..."));
1695 AppendMenu(menu, MF_ENABLED, IDM_SEED, TEXT("Rando&m Seed..."));
1696 #endif
1698 if (fe->presets)
1699 sfree(fe->presets);
1700 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1701 fe->game->can_configure) {
1702 int i;
1703 #ifndef _WIN32_WCE
1704 HMENU sub = CreateMenu();
1706 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "&Type");
1707 #else
1708 HMENU sub = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_TYPE);
1709 DeleteMenu(sub, 0, MF_BYPOSITION);
1710 #endif
1711 fe->presets = snewn(fe->npresets, game_params *);
1713 for (i = 0; i < fe->npresets; i++) {
1714 char *name;
1715 #ifdef _WIN32_WCE
1716 TCHAR wName[255];
1717 #endif
1719 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1722 * FIXME: we ought to go through and do something
1723 * with ampersands here.
1726 #ifndef _WIN32_WCE
1727 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1728 #else
1729 MultiByteToWideChar (CP_ACP, 0, name, -1, wName, 255);
1730 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, wName);
1731 #endif
1733 if (fe->game->can_configure) {
1734 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, TEXT("&Custom..."));
1737 fe->typemenu = sub;
1738 } else {
1739 fe->typemenu = INVALID_HANDLE_VALUE;
1740 fe->presets = NULL;
1743 #ifdef COMBINED
1744 #ifdef _WIN32_WCE
1745 #error Windows CE does not support COMBINED build.
1746 #endif
1748 HMENU games = CreateMenu();
1749 int i;
1751 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1752 AppendMenu(menu, MF_ENABLED|MF_POPUP, (UINT)games, "&Other");
1753 for (i = 0; i < gamecount; i++) {
1754 if (strcmp(gamelist[i]->name, fe->game->name) != 0) {
1755 /* only include those games that aren't the same as the
1756 * game we're currently playing. */
1757 AppendMenu(games, MF_ENABLED, IDM_GAMES + i, gamelist[i]->name);
1761 #endif
1763 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1764 #ifndef _WIN32_WCE
1765 AppendMenu(menu, MF_ENABLED, IDM_LOAD, TEXT("&Load..."));
1766 AppendMenu(menu, MF_ENABLED, IDM_SAVE, TEXT("&Save..."));
1767 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1768 if (fe->game->can_print) {
1769 AppendMenu(menu, MF_ENABLED, IDM_PRINT, TEXT("&Print..."));
1770 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1772 #endif
1773 AppendMenu(menu, MF_ENABLED, IDM_UNDO, TEXT("Undo"));
1774 AppendMenu(menu, MF_ENABLED, IDM_REDO, TEXT("Redo"));
1775 #ifndef _WIN32_WCE
1776 if (fe->game->can_format_as_text_ever) {
1777 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1778 AppendMenu(menu, MF_ENABLED, IDM_COPY, TEXT("&Copy"));
1780 #endif
1781 if (fe->game->can_solve) {
1782 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1783 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, TEXT("Sol&ve"));
1785 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1786 #ifndef _WIN32_WCE
1787 AppendMenu(menu, MF_ENABLED, IDM_QUIT, TEXT("E&xit"));
1788 menu = CreateMenu();
1789 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, TEXT("&Help"));
1790 #endif
1791 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, TEXT("&About"));
1792 #ifndef _WIN32_WCE
1793 if (help_type != NONE) {
1794 char *item;
1795 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1796 AppendMenu(menu, MF_ENABLED, IDM_HELPC, TEXT("&Contents"));
1797 assert(fe->game->name);
1798 item = snewn(10+strlen(fe->game->name), char); /*ick*/
1799 sprintf(item, "&Help on %s", fe->game->name);
1800 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1801 sfree(item);
1803 DestroyMenu(oldmenu);
1804 SetMenu(fe->hwnd, bar);
1805 get_menu_size(fe->hwnd, &menusize);
1806 fe->xmin = (menusize.right - menusize.left) + 25;
1807 #endif
1810 if (fe->bitmap) DeleteObject(fe->bitmap);
1811 fe->bitmap = NULL;
1812 new_game_size(fe, fe->puzz_scale); /* initialises fe->bitmap */
1814 return 0;
1817 static void show_window(frontend *fe)
1819 ShowWindow(fe->hwnd, SW_SHOWNORMAL);
1820 SetForegroundWindow(fe->hwnd);
1822 update_type_menu_tick(fe);
1823 update_copy_menu_greying(fe);
1825 midend_redraw(fe->me);
1828 #ifdef _WIN32_WCE
1829 static HFONT dialog_title_font()
1831 static HFONT hf = NULL;
1832 LOGFONT lf;
1834 if (hf)
1835 return hf;
1837 memset (&lf, 0, sizeof(LOGFONT));
1838 lf.lfHeight = -11; /* - ((8 * GetDeviceCaps(hdc, LOGPIXELSY)) / 72) */
1839 lf.lfWeight = FW_BOLD;
1840 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
1842 return hf = CreateFontIndirect(&lf);
1845 static void make_dialog_full_screen(HWND hwnd)
1847 SHINITDLGINFO shidi;
1849 /* Make dialog full screen */
1850 shidi.dwMask = SHIDIM_FLAGS;
1851 shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIZEDLGFULLSCREEN |
1852 SHIDIF_EMPTYMENU;
1853 shidi.hDlg = hwnd;
1854 SHInitDialog(&shidi);
1856 #endif
1858 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1859 WPARAM wParam, LPARAM lParam)
1861 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1863 switch (msg) {
1864 case WM_INITDIALOG:
1865 #ifdef _WIN32_WCE
1867 char title[256];
1869 make_dialog_full_screen(hwnd);
1871 sprintf(title, "About %.250s", fe->game->name);
1872 SetDlgItemTextA(hwnd, IDC_ABOUT_CAPTION, title);
1874 SendDlgItemMessage(hwnd, IDC_ABOUT_CAPTION, WM_SETFONT,
1875 (WPARAM) dialog_title_font(), 0);
1877 SetDlgItemTextA(hwnd, IDC_ABOUT_GAME, fe->game->name);
1878 SetDlgItemTextA(hwnd, IDC_ABOUT_VERSION, ver);
1880 #endif
1881 return TRUE;
1883 case WM_COMMAND:
1884 if (LOWORD(wParam) == IDOK)
1885 #ifdef _WIN32_WCE
1886 EndDialog(hwnd, 1);
1887 #else
1888 fe->dlg_done = 1;
1889 #endif
1890 return 0;
1892 case WM_CLOSE:
1893 #ifdef _WIN32_WCE
1894 EndDialog(hwnd, 1);
1895 #else
1896 fe->dlg_done = 1;
1897 #endif
1898 return 0;
1901 return 0;
1905 * Wrappers on midend_{get,set}_config, which extend the CFG_*
1906 * enumeration to add CFG_PRINT.
1908 static config_item *frontend_get_config(frontend *fe, int which,
1909 char **wintitle)
1911 if (which < CFG_FRONTEND_SPECIFIC) {
1912 return midend_get_config(fe->me, which, wintitle);
1913 } else if (which == CFG_PRINT) {
1914 config_item *ret;
1915 int i;
1917 *wintitle = snewn(40 + strlen(fe->game->name), char);
1918 sprintf(*wintitle, "%s print setup", fe->game->name);
1920 ret = snewn(8, config_item);
1922 i = 0;
1924 ret[i].name = "Number of puzzles to print";
1925 ret[i].type = C_STRING;
1926 ret[i].sval = dupstr("1");
1927 ret[i].ival = 0;
1928 i++;
1930 ret[i].name = "Number of puzzles across the page";
1931 ret[i].type = C_STRING;
1932 ret[i].sval = dupstr("1");
1933 ret[i].ival = 0;
1934 i++;
1936 ret[i].name = "Number of puzzles down the page";
1937 ret[i].type = C_STRING;
1938 ret[i].sval = dupstr("1");
1939 ret[i].ival = 0;
1940 i++;
1942 ret[i].name = "Percentage of standard size";
1943 ret[i].type = C_STRING;
1944 ret[i].sval = dupstr("100.0");
1945 ret[i].ival = 0;
1946 i++;
1948 ret[i].name = "Include currently shown puzzle";
1949 ret[i].type = C_BOOLEAN;
1950 ret[i].sval = NULL;
1951 ret[i].ival = TRUE;
1952 i++;
1954 ret[i].name = "Print solutions";
1955 ret[i].type = C_BOOLEAN;
1956 ret[i].sval = NULL;
1957 ret[i].ival = FALSE;
1958 i++;
1960 if (fe->game->can_print_in_colour) {
1961 ret[i].name = "Print in colour";
1962 ret[i].type = C_BOOLEAN;
1963 ret[i].sval = NULL;
1964 ret[i].ival = FALSE;
1965 i++;
1968 ret[i].name = NULL;
1969 ret[i].type = C_END;
1970 ret[i].sval = NULL;
1971 ret[i].ival = 0;
1972 i++;
1974 return ret;
1975 } else {
1976 assert(!"We should never get here");
1977 return NULL;
1981 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
1983 if (which < CFG_FRONTEND_SPECIFIC) {
1984 return midend_set_config(fe->me, which, cfg);
1985 } else if (which == CFG_PRINT) {
1986 if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
1987 return "Number of puzzles to print should be at least one";
1988 if ((fe->printw = atoi(cfg[1].sval)) <= 0)
1989 return "Number of puzzles across the page should be at least one";
1990 if ((fe->printh = atoi(cfg[2].sval)) <= 0)
1991 return "Number of puzzles down the page should be at least one";
1992 if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
1993 return "Print size should be positive";
1994 fe->printcurr = cfg[4].ival;
1995 fe->printsolns = cfg[5].ival;
1996 fe->printcolour = fe->game->can_print_in_colour && cfg[6].ival;
1997 return NULL;
1998 } else {
1999 assert(!"We should never get here");
2000 return "Internal error";
2004 #ifdef _WIN32_WCE
2005 /* Separate version of mkctrl function for the Pocket PC. */
2006 /* Control coordinates should be specified in dialog units. */
2007 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2008 LPCTSTR wclass, int wstyle,
2009 int exstyle, const char *wtext, int wid)
2011 RECT rc;
2012 TCHAR wwtext[256];
2014 /* Convert dialog units into pixels */
2015 rc.left = x1; rc.right = x2;
2016 rc.top = y1; rc.bottom = y2;
2017 MapDialogRect(fe->cfgbox, &rc);
2019 MultiByteToWideChar (CP_ACP, 0, wtext, -1, wwtext, 256);
2021 return CreateWindowEx(exstyle, wclass, wwtext,
2022 wstyle | WS_CHILD | WS_VISIBLE,
2023 rc.left, rc.top,
2024 rc.right - rc.left, rc.bottom - rc.top,
2025 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2028 static void create_config_controls(frontend * fe)
2030 int id, nctrls;
2031 int col1l, col1r, col2l, col2r, y;
2032 config_item *i;
2033 struct cfg_aux *j;
2034 HWND ctl;
2036 /* Control placement done in dialog units */
2037 col1l = 4; col1r = 96; /* Label column */
2038 col2l = 100; col2r = 154; /* Input column (edit boxes and combo boxes) */
2041 * Count the controls so we can allocate cfgaux.
2043 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2044 nctrls++;
2045 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2047 id = 1000;
2048 y = 22; /* Leave some room for the dialog title */
2049 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2050 switch (i->type) {
2051 case C_STRING:
2053 * Edit box with a label beside it.
2055 mkctrl(fe, col1l, col1r, y + 1, y + 11,
2056 TEXT("Static"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
2057 mkctrl(fe, col2l, col2r, y, y + 12,
2058 TEXT("EDIT"), WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
2059 0, "", (j->ctlid = id++));
2060 SetDlgItemTextA(fe->cfgbox, j->ctlid, i->sval);
2061 break;
2063 case C_BOOLEAN:
2065 * Simple checkbox.
2067 mkctrl(fe, col1l, col2r, y + 1, y + 11, TEXT("BUTTON"),
2068 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2069 0, i->name, (j->ctlid = id++));
2070 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2071 break;
2073 case C_CHOICES:
2075 * Drop-down list with a label beside it.
2077 mkctrl(fe, col1l, col1r, y + 1, y + 11,
2078 TEXT("STATIC"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
2079 ctl = mkctrl(fe, col2l, col2r, y, y + 48,
2080 TEXT("COMBOBOX"), WS_BORDER | WS_TABSTOP |
2081 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2082 0, "", (j->ctlid = id++));
2084 char c, *p, *q, *str;
2086 p = i->sval;
2087 c = *p++;
2088 while (*p) {
2089 q = p;
2090 while (*q && *q != c) q++;
2091 str = snewn(q-p+1, char);
2092 strncpy(str, p, q-p);
2093 str[q-p] = '\0';
2095 TCHAR ws[50];
2096 MultiByteToWideChar (CP_ACP, 0, str, -1, ws, 50);
2097 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)ws);
2100 sfree(str);
2101 if (*q) q++;
2102 p = q;
2105 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2106 break;
2109 y += 15;
2113 #endif
2115 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
2116 WPARAM wParam, LPARAM lParam)
2118 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2119 config_item *i;
2120 struct cfg_aux *j;
2122 switch (msg) {
2123 case WM_INITDIALOG:
2124 #ifdef _WIN32_WCE
2126 char *title;
2128 fe = (frontend *) lParam;
2129 SetWindowLong(hwnd, GWL_USERDATA, lParam);
2130 fe->cfgbox = hwnd;
2132 fe->cfg = frontend_get_config(fe, fe->cfg_which, &title);
2134 make_dialog_full_screen(hwnd);
2136 SetDlgItemTextA(hwnd, IDC_CONFIG_CAPTION, title);
2137 SendDlgItemMessage(hwnd, IDC_CONFIG_CAPTION, WM_SETFONT,
2138 (WPARAM) dialog_title_font(), 0);
2140 create_config_controls(fe);
2142 #endif
2143 return TRUE;
2145 case WM_COMMAND:
2147 * OK and Cancel are special cases.
2149 if ((LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
2150 if (LOWORD(wParam) == IDOK) {
2151 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
2153 if (err) {
2154 MessageBox(hwnd, err, "Validation error",
2155 MB_ICONERROR | MB_OK);
2156 } else {
2157 #ifdef _WIN32_WCE
2158 EndDialog(hwnd, 2);
2159 #else
2160 fe->dlg_done = 2;
2161 #endif
2163 } else {
2164 #ifdef _WIN32_WCE
2165 EndDialog(hwnd, 1);
2166 #else
2167 fe->dlg_done = 1;
2168 #endif
2170 return 0;
2174 * First find the control whose id this is.
2176 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2177 if (j->ctlid == LOWORD(wParam))
2178 break;
2180 if (i->type == C_END)
2181 return 0; /* not our problem */
2183 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
2184 char buffer[4096];
2185 #ifdef _WIN32_WCE
2186 TCHAR wBuffer[4096];
2187 GetDlgItemText(fe->cfgbox, j->ctlid, wBuffer, 4096);
2188 WideCharToMultiByte(CP_ACP, 0, wBuffer, -1, buffer, 4096, NULL, NULL);
2189 #else
2190 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
2191 #endif
2192 buffer[lenof(buffer)-1] = '\0';
2193 sfree(i->sval);
2194 i->sval = dupstr(buffer);
2195 } else if (i->type == C_BOOLEAN &&
2196 (HIWORD(wParam) == BN_CLICKED ||
2197 HIWORD(wParam) == BN_DBLCLK)) {
2198 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
2199 } else if (i->type == C_CHOICES &&
2200 HIWORD(wParam) == CBN_SELCHANGE) {
2201 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
2202 CB_GETCURSEL, 0, 0);
2205 return 0;
2207 case WM_CLOSE:
2208 fe->dlg_done = 1;
2209 return 0;
2212 return 0;
2215 #ifndef _WIN32_WCE
2216 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2217 char *wclass, int wstyle,
2218 int exstyle, const char *wtext, int wid)
2220 HWND ret;
2221 ret = CreateWindowEx(exstyle, wclass, wtext,
2222 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
2223 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2224 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
2225 return ret;
2227 #endif
2229 static void about(frontend *fe)
2231 #ifdef _WIN32_WCE
2232 DialogBox(fe->inst, MAKEINTRESOURCE(IDD_ABOUT), fe->hwnd, AboutDlgProc);
2233 #else
2234 int i;
2235 WNDCLASS wc;
2236 MSG msg;
2237 TEXTMETRIC tm;
2238 HDC hdc;
2239 HFONT oldfont;
2240 SIZE size;
2241 int gm, id;
2242 int winwidth, winheight, y;
2243 int height, width, maxwid;
2244 const char *strings[16];
2245 int lengths[16];
2246 int nstrings = 0;
2247 char titlebuf[512];
2249 sprintf(titlebuf, "About %.250s", fe->game->name);
2251 strings[nstrings++] = fe->game->name;
2252 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
2253 strings[nstrings++] = ver;
2255 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2256 wc.lpfnWndProc = DefDlgProc;
2257 wc.cbClsExtra = 0;
2258 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2259 wc.hInstance = fe->inst;
2260 wc.hIcon = NULL;
2261 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2262 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2263 wc.lpszMenuName = NULL;
2264 wc.lpszClassName = "GameAboutBox";
2265 RegisterClass(&wc);
2267 hdc = GetDC(fe->hwnd);
2268 SetMapMode(hdc, MM_TEXT);
2270 fe->dlg_done = FALSE;
2272 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2273 0, 0, 0, 0,
2274 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2275 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2276 DEFAULT_QUALITY,
2277 FF_SWISS,
2278 "MS Shell Dlg");
2280 oldfont = SelectObject(hdc, fe->cfgfont);
2281 if (GetTextMetrics(hdc, &tm)) {
2282 height = tm.tmAscent + tm.tmDescent;
2283 width = tm.tmAveCharWidth;
2284 } else {
2285 height = width = 30;
2289 * Figure out the layout of the About box by measuring the
2290 * length of each piece of text.
2292 maxwid = 0;
2293 winheight = height/2;
2295 for (i = 0; i < nstrings; i++) {
2296 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
2297 lengths[i] = size.cx;
2298 else
2299 lengths[i] = 0; /* *shrug* */
2300 if (maxwid < lengths[i])
2301 maxwid = lengths[i];
2302 winheight += height * 3 / 2 + (height / 2);
2305 winheight += height + height * 7 / 4; /* OK button */
2306 winwidth = maxwid + 4*width;
2308 SelectObject(hdc, oldfont);
2309 ReleaseDC(fe->hwnd, hdc);
2312 * Create the dialog, now that we know its size.
2315 RECT r, r2;
2317 r.left = r.top = 0;
2318 r.right = winwidth;
2319 r.bottom = winheight;
2321 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2322 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2323 WS_CAPTION | WS_SYSMENU*/) &~
2324 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2325 FALSE, 0);
2328 * Centre the dialog on its parent window.
2330 r.right -= r.left;
2331 r.bottom -= r.top;
2332 GetWindowRect(fe->hwnd, &r2);
2333 r.left = (r2.left + r2.right - r.right) / 2;
2334 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2335 r.right += r.left;
2336 r.bottom += r.top;
2338 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
2339 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2340 WS_CAPTION | WS_SYSMENU,
2341 r.left, r.top,
2342 r.right-r.left, r.bottom-r.top,
2343 fe->hwnd, NULL, fe->inst, NULL);
2346 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2348 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2349 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
2351 id = 1000;
2352 y = height/2;
2353 for (i = 0; i < nstrings; i++) {
2354 int border = width*2 + (maxwid - lengths[i]) / 2;
2355 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
2356 "Static", 0, 0, strings[i], id++);
2357 y += height*3/2;
2359 assert(y < winheight);
2360 y += height/2;
2363 y += height/2; /* extra space before OK */
2364 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
2365 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2366 "OK", IDOK);
2368 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2370 EnableWindow(fe->hwnd, FALSE);
2371 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2372 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2373 if (!IsDialogMessage(fe->cfgbox, &msg))
2374 DispatchMessage(&msg);
2375 if (fe->dlg_done)
2376 break;
2378 EnableWindow(fe->hwnd, TRUE);
2379 SetForegroundWindow(fe->hwnd);
2380 DestroyWindow(fe->cfgbox);
2381 DeleteObject(fe->cfgfont);
2382 #endif
2385 static int get_config(frontend *fe, int which)
2387 #ifdef _WIN32_WCE
2388 fe->cfg_which = which;
2390 return DialogBoxParam(fe->inst,
2391 MAKEINTRESOURCE(IDD_CONFIG),
2392 fe->hwnd, ConfigDlgProc,
2393 (LPARAM) fe) == 2;
2394 #else
2395 config_item *i;
2396 struct cfg_aux *j;
2397 char *title;
2398 WNDCLASS wc;
2399 MSG msg;
2400 TEXTMETRIC tm;
2401 HDC hdc;
2402 HFONT oldfont;
2403 SIZE size;
2404 HWND ctl;
2405 int gm, id, nctrls;
2406 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
2407 int height, width, maxlabel, maxcheckbox;
2409 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2410 wc.lpfnWndProc = DefDlgProc;
2411 wc.cbClsExtra = 0;
2412 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2413 wc.hInstance = fe->inst;
2414 wc.hIcon = NULL;
2415 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2416 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2417 wc.lpszMenuName = NULL;
2418 wc.lpszClassName = "GameConfigBox";
2419 RegisterClass(&wc);
2421 hdc = GetDC(fe->hwnd);
2422 SetMapMode(hdc, MM_TEXT);
2424 fe->dlg_done = FALSE;
2426 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2427 0, 0, 0, 0,
2428 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2429 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2430 DEFAULT_QUALITY,
2431 FF_SWISS,
2432 "MS Shell Dlg");
2434 oldfont = SelectObject(hdc, fe->cfgfont);
2435 if (GetTextMetrics(hdc, &tm)) {
2436 height = tm.tmAscent + tm.tmDescent;
2437 width = tm.tmAveCharWidth;
2438 } else {
2439 height = width = 30;
2442 fe->cfg = frontend_get_config(fe, which, &title);
2443 fe->cfg_which = which;
2446 * Figure out the layout of the config box by measuring the
2447 * length of each piece of text.
2449 maxlabel = maxcheckbox = 0;
2450 winheight = height/2;
2452 for (i = fe->cfg; i->type != C_END; i++) {
2453 switch (i->type) {
2454 case C_STRING:
2455 case C_CHOICES:
2457 * Both these control types have a label filling only
2458 * the left-hand column of the box.
2460 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2461 maxlabel < size.cx)
2462 maxlabel = size.cx;
2463 winheight += height * 3 / 2 + (height / 2);
2464 break;
2466 case C_BOOLEAN:
2468 * Checkboxes take up the whole of the box width.
2470 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2471 maxcheckbox < size.cx)
2472 maxcheckbox = size.cx;
2473 winheight += height + (height / 2);
2474 break;
2478 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
2480 col1l = 2*width;
2481 col1r = col1l + maxlabel;
2482 col2l = col1r + 2*width;
2483 col2r = col2l + 30*width;
2484 if (col2r < col1l+2*height+maxcheckbox)
2485 col2r = col1l+2*height+maxcheckbox;
2486 winwidth = col2r + 2*width;
2488 SelectObject(hdc, oldfont);
2489 ReleaseDC(fe->hwnd, hdc);
2492 * Create the dialog, now that we know its size.
2495 RECT r, r2;
2497 r.left = r.top = 0;
2498 r.right = winwidth;
2499 r.bottom = winheight;
2501 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2502 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2503 WS_CAPTION | WS_SYSMENU*/) &~
2504 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2505 FALSE, 0);
2508 * Centre the dialog on its parent window.
2510 r.right -= r.left;
2511 r.bottom -= r.top;
2512 GetWindowRect(fe->hwnd, &r2);
2513 r.left = (r2.left + r2.right - r.right) / 2;
2514 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2515 r.right += r.left;
2516 r.bottom += r.top;
2518 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
2519 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2520 WS_CAPTION | WS_SYSMENU,
2521 r.left, r.top,
2522 r.right-r.left, r.bottom-r.top,
2523 fe->hwnd, NULL, fe->inst, NULL);
2524 sfree(title);
2527 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2529 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2530 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
2533 * Count the controls so we can allocate cfgaux.
2535 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2536 nctrls++;
2537 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2539 id = 1000;
2540 y = height/2;
2541 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2542 switch (i->type) {
2543 case C_STRING:
2545 * Edit box 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*3/2,
2550 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
2551 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2552 SetWindowText(ctl, i->sval);
2553 y += height*3/2;
2554 break;
2556 case C_BOOLEAN:
2558 * Simple checkbox.
2560 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
2561 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2562 0, i->name, (j->ctlid = id++));
2563 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2564 y += height;
2565 break;
2567 case C_CHOICES:
2569 * Drop-down list with a label beside it.
2571 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2572 "STATIC", 0, 0, i->name, id++);
2573 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
2574 "COMBOBOX", WS_TABSTOP |
2575 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2576 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2578 char c, *p, *q, *str;
2580 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
2581 p = i->sval;
2582 c = *p++;
2583 while (*p) {
2584 q = p;
2585 while (*q && *q != c) q++;
2586 str = snewn(q-p+1, char);
2587 strncpy(str, p, q-p);
2588 str[q-p] = '\0';
2589 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
2590 sfree(str);
2591 if (*q) q++;
2592 p = q;
2596 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2598 y += height*3/2;
2599 break;
2602 assert(y < winheight);
2603 y += height/2;
2606 y += height/2; /* extra space before OK and Cancel */
2607 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
2608 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2609 "OK", IDOK);
2610 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
2611 BS_PUSHBUTTON | WS_TABSTOP, 0, "Cancel", IDCANCEL);
2613 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2615 EnableWindow(fe->hwnd, FALSE);
2616 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2617 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2618 if (!IsDialogMessage(fe->cfgbox, &msg))
2619 DispatchMessage(&msg);
2620 if (fe->dlg_done)
2621 break;
2623 EnableWindow(fe->hwnd, TRUE);
2624 SetForegroundWindow(fe->hwnd);
2625 DestroyWindow(fe->cfgbox);
2626 DeleteObject(fe->cfgfont);
2628 free_cfg(fe->cfg);
2629 sfree(fe->cfgaux);
2631 return (fe->dlg_done == 2);
2632 #endif
2635 #ifdef _WIN32_WCE
2636 static void calculate_bitmap_position(frontend *fe, int x, int y)
2638 /* Pocket PC - center the game in the full screen window */
2639 int yMargin;
2640 RECT rcClient;
2642 GetClientRect(fe->hwnd, &rcClient);
2643 fe->bitmapPosition.left = (rcClient.right - x) / 2;
2644 yMargin = rcClient.bottom - y;
2646 if (fe->numpad != NULL) {
2647 RECT rcPad;
2648 GetWindowRect(fe->numpad, &rcPad);
2649 yMargin -= rcPad.bottom - rcPad.top;
2652 if (fe->statusbar != NULL) {
2653 RECT rcStatus;
2654 GetWindowRect(fe->statusbar, &rcStatus);
2655 yMargin -= rcStatus.bottom - rcStatus.top;
2658 fe->bitmapPosition.top = yMargin / 2;
2660 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2661 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2663 #else
2664 static void calculate_bitmap_position(frontend *fe, int x, int y)
2666 /* Plain Windows - position the game in the upper-left corner */
2667 fe->bitmapPosition.left = 0;
2668 fe->bitmapPosition.top = 0;
2669 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2670 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2672 #endif
2674 static void new_bitmap(frontend *fe, int x, int y)
2676 HDC hdc;
2678 if (fe->bitmap) DeleteObject(fe->bitmap);
2680 hdc = GetDC(fe->hwnd);
2681 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2682 calculate_bitmap_position(fe, x, y);
2683 ReleaseDC(fe->hwnd, hdc);
2686 static void new_game_size(frontend *fe, float scale)
2688 RECT r, sr;
2689 int x, y;
2691 get_max_puzzle_size(fe, &x, &y);
2692 midend_size(fe->me, &x, &y, FALSE);
2694 if (scale != 1.0) {
2695 x = (int)((float)x * fe->puzz_scale);
2696 y = (int)((float)y * fe->puzz_scale);
2697 midend_size(fe->me, &x, &y, TRUE);
2699 fe->ymin = (fe->xmin * y) / x;
2701 r.left = r.top = 0;
2702 r.right = x;
2703 r.bottom = y;
2704 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2706 if (fe->statusbar != NULL) {
2707 GetWindowRect(fe->statusbar, &sr);
2708 } else {
2709 sr.left = sr.right = sr.top = sr.bottom = 0;
2711 #ifndef _WIN32_WCE
2712 SetWindowPos(fe->hwnd, NULL, 0, 0,
2713 r.right - r.left,
2714 r.bottom - r.top + sr.bottom - sr.top,
2715 SWP_NOMOVE | SWP_NOZORDER);
2716 #endif
2718 check_window_size(fe, &x, &y);
2720 #ifndef _WIN32_WCE
2721 if (fe->statusbar != NULL)
2722 SetWindowPos(fe->statusbar, NULL, 0, y, x,
2723 sr.bottom - sr.top, SWP_NOZORDER);
2724 #endif
2726 new_bitmap(fe, x, y);
2728 #ifdef _WIN32_WCE
2729 InvalidateRect(fe->hwnd, NULL, TRUE);
2730 #endif
2731 midend_redraw(fe->me);
2735 * Given a proposed new window rect, work out the resulting
2736 * difference in client size (from current), and use to try
2737 * and resize the puzzle, returning (wx,wy) as the actual
2738 * new window size.
2741 static void adjust_game_size(frontend *fe, RECT *proposed, int isedge,
2742 int *wx_r, int *wy_r)
2744 RECT cr, wr;
2745 int nx, ny, xdiff, ydiff, wx, wy;
2747 /* Work out the current window sizing, and thus the
2748 * difference in size we're asking for. */
2749 GetClientRect(fe->hwnd, &cr);
2750 wr = cr;
2751 AdjustWindowRectEx(&wr, WINFLAGS, TRUE, 0);
2753 xdiff = (proposed->right - proposed->left) - (wr.right - wr.left);
2754 ydiff = (proposed->bottom - proposed->top) - (wr.bottom - wr.top);
2756 if (isedge) {
2757 /* These next four lines work around the fact that midend_size
2758 * is happy to shrink _but not grow_ if you change one dimension
2759 * but not the other. */
2760 if (xdiff > 0 && ydiff == 0)
2761 ydiff = (xdiff * (wr.right - wr.left)) / (wr.bottom - wr.top);
2762 if (xdiff == 0 && ydiff > 0)
2763 xdiff = (ydiff * (wr.bottom - wr.top)) / (wr.right - wr.left);
2766 if (check_window_resize(fe,
2767 (cr.right - cr.left) + xdiff,
2768 (cr.bottom - cr.top) + ydiff,
2769 &nx, &ny, &wx, &wy)) {
2770 new_bitmap(fe, nx, ny);
2771 midend_force_redraw(fe->me);
2772 } else {
2773 /* reset size to current window size */
2774 wx = wr.right - wr.left;
2775 wy = wr.bottom - wr.top;
2777 /* Re-fetch rectangle; size limits mean we might not have
2778 * taken it quite to the mouse drag positions. */
2779 GetClientRect(fe->hwnd, &cr);
2780 adjust_statusbar(fe, &cr);
2782 *wx_r = wx; *wy_r = wy;
2785 static void update_type_menu_tick(frontend *fe)
2787 int total, n, i;
2789 if (fe->typemenu == INVALID_HANDLE_VALUE)
2790 return;
2792 total = GetMenuItemCount(fe->typemenu);
2793 n = midend_which_preset(fe->me);
2794 if (n < 0)
2795 n = total - 1; /* "Custom" item */
2797 for (i = 0; i < total; i++) {
2798 int flag = (i == n ? MF_CHECKED : MF_UNCHECKED);
2799 CheckMenuItem(fe->typemenu, i, MF_BYPOSITION | flag);
2802 DrawMenuBar(fe->hwnd);
2805 static void update_copy_menu_greying(frontend *fe)
2807 UINT enable = (midend_can_format_as_text_now(fe->me) ?
2808 MF_ENABLED : MF_GRAYED);
2809 EnableMenuItem(fe->gamemenu, IDM_COPY, MF_BYCOMMAND | enable);
2812 static void new_game_type(frontend *fe)
2814 midend_new_game(fe->me);
2815 new_game_size(fe, 1.0);
2816 update_type_menu_tick(fe);
2817 update_copy_menu_greying(fe);
2820 static int is_alt_pressed(void)
2822 BYTE keystate[256];
2823 int r = GetKeyboardState(keystate);
2824 if (!r)
2825 return FALSE;
2826 if (keystate[VK_MENU] & 0x80)
2827 return TRUE;
2828 if (keystate[VK_RMENU] & 0x80)
2829 return TRUE;
2830 return FALSE;
2833 static void savefile_write(void *wctx, void *buf, int len)
2835 FILE *fp = (FILE *)wctx;
2836 fwrite(buf, 1, len, fp);
2839 static int savefile_read(void *wctx, void *buf, int len)
2841 FILE *fp = (FILE *)wctx;
2842 int ret;
2844 ret = fread(buf, 1, len, fp);
2845 return (ret == len);
2848 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2849 WPARAM wParam, LPARAM lParam)
2851 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2852 int cmd;
2854 switch (message) {
2855 case WM_CLOSE:
2856 DestroyWindow(hwnd);
2857 return 0;
2858 case WM_COMMAND:
2859 #ifdef _WIN32_WCE
2860 /* Numeric pad sends WM_COMMAND messages */
2861 if ((wParam >= IDM_KEYEMUL) && (wParam < IDM_KEYEMUL + 256))
2863 midend_process_key(fe->me, 0, 0, wParam - IDM_KEYEMUL);
2865 #endif
2866 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
2867 switch (cmd) {
2868 case IDM_NEW:
2869 if (!midend_process_key(fe->me, 0, 0, 'n'))
2870 PostQuitMessage(0);
2871 break;
2872 case IDM_RESTART:
2873 midend_restart_game(fe->me);
2874 break;
2875 case IDM_UNDO:
2876 if (!midend_process_key(fe->me, 0, 0, 'u'))
2877 PostQuitMessage(0);
2878 break;
2879 case IDM_REDO:
2880 if (!midend_process_key(fe->me, 0, 0, '\x12'))
2881 PostQuitMessage(0);
2882 break;
2883 case IDM_COPY:
2885 char *text = midend_text_format(fe->me);
2886 if (text)
2887 write_clip(hwnd, text);
2888 else
2889 MessageBeep(MB_ICONWARNING);
2890 sfree(text);
2892 break;
2893 case IDM_SOLVE:
2895 char *msg = midend_solve(fe->me);
2896 if (msg)
2897 MessageBox(hwnd, msg, "Unable to solve",
2898 MB_ICONERROR | MB_OK);
2900 break;
2901 case IDM_QUIT:
2902 if (!midend_process_key(fe->me, 0, 0, 'q'))
2903 PostQuitMessage(0);
2904 break;
2905 case IDM_CONFIG:
2906 if (get_config(fe, CFG_SETTINGS))
2907 new_game_type(fe);
2908 break;
2909 case IDM_SEED:
2910 if (get_config(fe, CFG_SEED))
2911 new_game_type(fe);
2912 break;
2913 case IDM_DESC:
2914 if (get_config(fe, CFG_DESC))
2915 new_game_type(fe);
2916 break;
2917 case IDM_PRINT:
2918 if (get_config(fe, CFG_PRINT))
2919 print(fe);
2920 break;
2921 case IDM_ABOUT:
2922 about(fe);
2923 break;
2924 case IDM_LOAD:
2925 case IDM_SAVE:
2927 OPENFILENAME of;
2928 char filename[FILENAME_MAX];
2929 int ret;
2931 memset(&of, 0, sizeof(of));
2932 of.hwndOwner = hwnd;
2933 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
2934 of.lpstrCustomFilter = NULL;
2935 of.nFilterIndex = 1;
2936 of.lpstrFile = filename;
2937 filename[0] = '\0';
2938 of.nMaxFile = lenof(filename);
2939 of.lpstrFileTitle = NULL;
2940 of.lpstrTitle = (cmd == IDM_SAVE ?
2941 "Enter name of game file to save" :
2942 "Enter name of saved game file to load");
2943 of.Flags = 0;
2944 #ifdef OPENFILENAME_SIZE_VERSION_400
2945 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2946 #else
2947 of.lStructSize = sizeof(of);
2948 #endif
2949 of.lpstrInitialDir = NULL;
2951 if (cmd == IDM_SAVE)
2952 ret = GetSaveFileName(&of);
2953 else
2954 ret = GetOpenFileName(&of);
2956 if (ret) {
2957 if (cmd == IDM_SAVE) {
2958 FILE *fp;
2960 if ((fp = fopen(filename, "r")) != NULL) {
2961 char buf[256 + FILENAME_MAX];
2962 fclose(fp);
2963 /* file exists */
2965 sprintf(buf, "Are you sure you want to overwrite"
2966 " the file \"%.*s\"?",
2967 FILENAME_MAX, filename);
2968 if (MessageBox(hwnd, buf, "Question",
2969 MB_YESNO | MB_ICONQUESTION)
2970 != IDYES)
2971 break;
2974 fp = fopen(filename, "w");
2976 if (!fp) {
2977 MessageBox(hwnd, "Unable to open save file",
2978 "Error", MB_ICONERROR | MB_OK);
2979 break;
2982 midend_serialise(fe->me, savefile_write, fp);
2984 fclose(fp);
2985 } else {
2986 FILE *fp = fopen(filename, "r");
2987 char *err;
2989 if (!fp) {
2990 MessageBox(hwnd, "Unable to open saved game file",
2991 "Error", MB_ICONERROR | MB_OK);
2992 break;
2995 err = midend_deserialise(fe->me, savefile_read, fp);
2997 fclose(fp);
2999 if (err) {
3000 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
3001 break;
3004 new_game_size(fe, 1.0);
3009 break;
3010 #ifndef _WIN32_WCE
3011 case IDM_HELPC:
3012 start_help(fe, NULL);
3013 break;
3014 case IDM_GAMEHELP:
3015 assert(help_type != NONE);
3016 start_help(fe, help_type == CHM ?
3017 fe->game->htmlhelp_topic : fe->game->winhelp_topic);
3018 break;
3019 #endif
3020 default:
3021 #ifdef COMBINED
3022 if (wParam >= IDM_GAMES && wParam < (IDM_GAMES + (WPARAM)gamecount)) {
3023 int p = wParam - IDM_GAMES;
3024 char *error;
3026 new_game(fe, gamelist[p], NULL, &error);
3027 } else
3028 #endif
3030 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
3032 if (p >= 0 && p < fe->npresets) {
3033 midend_set_params(fe->me, fe->presets[p]);
3034 new_game_type(fe);
3037 break;
3039 break;
3040 case WM_DESTROY:
3041 #ifndef _WIN32_WCE
3042 stop_help(fe);
3043 #endif
3044 frontend_free(fe);
3045 PostQuitMessage(0);
3046 return 0;
3047 case WM_PAINT:
3049 PAINTSTRUCT p;
3050 HDC hdc, hdc2;
3051 HBITMAP prevbm;
3052 RECT rcDest;
3054 hdc = BeginPaint(hwnd, &p);
3055 hdc2 = CreateCompatibleDC(hdc);
3056 prevbm = SelectObject(hdc2, fe->bitmap);
3057 #ifdef _WIN32_WCE
3058 FillRect(hdc, &(p.rcPaint), (HBRUSH) GetStockObject(WHITE_BRUSH));
3059 #endif
3060 IntersectRect(&rcDest, &(fe->bitmapPosition), &(p.rcPaint));
3061 BitBlt(hdc,
3062 rcDest.left, rcDest.top,
3063 rcDest.right - rcDest.left,
3064 rcDest.bottom - rcDest.top,
3065 hdc2,
3066 rcDest.left - fe->bitmapPosition.left,
3067 rcDest.top - fe->bitmapPosition.top,
3068 SRCCOPY);
3069 SelectObject(hdc2, prevbm);
3070 DeleteDC(hdc2);
3071 EndPaint(hwnd, &p);
3073 return 0;
3074 case WM_KEYDOWN:
3076 int key = -1;
3077 BYTE keystate[256];
3078 int r = GetKeyboardState(keystate);
3079 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
3080 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
3082 switch (wParam) {
3083 case VK_LEFT:
3084 if (!(lParam & 0x01000000))
3085 key = MOD_NUM_KEYPAD | '4';
3086 else
3087 key = shift | ctrl | CURSOR_LEFT;
3088 break;
3089 case VK_RIGHT:
3090 if (!(lParam & 0x01000000))
3091 key = MOD_NUM_KEYPAD | '6';
3092 else
3093 key = shift | ctrl | CURSOR_RIGHT;
3094 break;
3095 case VK_UP:
3096 if (!(lParam & 0x01000000))
3097 key = MOD_NUM_KEYPAD | '8';
3098 else
3099 key = shift | ctrl | CURSOR_UP;
3100 break;
3101 case VK_DOWN:
3102 if (!(lParam & 0x01000000))
3103 key = MOD_NUM_KEYPAD | '2';
3104 else
3105 key = shift | ctrl | CURSOR_DOWN;
3106 break;
3108 * Diagonal keys on the numeric keypad.
3110 case VK_PRIOR:
3111 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
3112 break;
3113 case VK_NEXT:
3114 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
3115 break;
3116 case VK_HOME:
3117 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
3118 break;
3119 case VK_END:
3120 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
3121 break;
3122 case VK_INSERT:
3123 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
3124 break;
3125 case VK_CLEAR:
3126 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
3127 break;
3129 * Numeric keypad keys with Num Lock on.
3131 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
3132 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
3133 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
3134 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
3135 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
3136 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
3137 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
3138 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
3139 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
3140 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
3143 if (key != -1) {
3144 if (!midend_process_key(fe->me, 0, 0, key))
3145 PostQuitMessage(0);
3146 } else {
3147 MSG m;
3148 m.hwnd = hwnd;
3149 m.message = WM_KEYDOWN;
3150 m.wParam = wParam;
3151 m.lParam = lParam & 0xdfff;
3152 TranslateMessage(&m);
3155 break;
3156 case WM_LBUTTONDOWN:
3157 case WM_RBUTTONDOWN:
3158 case WM_MBUTTONDOWN:
3160 int button;
3163 * Shift-clicks count as middle-clicks, since otherwise
3164 * two-button Windows users won't have any kind of
3165 * middle click to use.
3167 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
3168 button = MIDDLE_BUTTON;
3169 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
3170 button = RIGHT_BUTTON;
3171 else
3172 #ifndef _WIN32_WCE
3173 button = LEFT_BUTTON;
3174 #else
3175 if ((fe->game->flags & REQUIRE_RBUTTON) == 0)
3176 button = LEFT_BUTTON;
3177 else
3179 SHRGINFO shrgi;
3181 shrgi.cbSize = sizeof(SHRGINFO);
3182 shrgi.hwndClient = hwnd;
3183 shrgi.ptDown.x = (signed short)LOWORD(lParam);
3184 shrgi.ptDown.y = (signed short)HIWORD(lParam);
3185 shrgi.dwFlags = SHRG_RETURNCMD;
3187 if (GN_CONTEXTMENU == SHRecognizeGesture(&shrgi))
3188 button = RIGHT_BUTTON;
3189 else
3190 button = LEFT_BUTTON;
3192 #endif
3194 if (!midend_process_key(fe->me,
3195 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3196 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3197 button))
3198 PostQuitMessage(0);
3200 SetCapture(hwnd);
3202 break;
3203 case WM_LBUTTONUP:
3204 case WM_RBUTTONUP:
3205 case WM_MBUTTONUP:
3207 int button;
3210 * Shift-clicks count as middle-clicks, since otherwise
3211 * two-button Windows users won't have any kind of
3212 * middle click to use.
3214 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
3215 button = MIDDLE_RELEASE;
3216 else if (message == WM_RBUTTONUP || is_alt_pressed())
3217 button = RIGHT_RELEASE;
3218 else
3219 button = LEFT_RELEASE;
3221 if (!midend_process_key(fe->me,
3222 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3223 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3224 button))
3225 PostQuitMessage(0);
3227 ReleaseCapture();
3229 break;
3230 case WM_MOUSEMOVE:
3232 int button;
3234 if (wParam & (MK_MBUTTON | MK_SHIFT))
3235 button = MIDDLE_DRAG;
3236 else if (wParam & MK_RBUTTON || is_alt_pressed())
3237 button = RIGHT_DRAG;
3238 else
3239 button = LEFT_DRAG;
3241 if (!midend_process_key(fe->me,
3242 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3243 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3244 button))
3245 PostQuitMessage(0);
3247 break;
3248 case WM_CHAR:
3249 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
3250 PostQuitMessage(0);
3251 return 0;
3252 case WM_TIMER:
3253 if (fe->timer) {
3254 DWORD now = GetTickCount();
3255 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
3256 midend_timer(fe->me, elapsed);
3257 fe->timer_last_tickcount = now;
3259 return 0;
3260 #ifndef _WIN32_WCE
3261 case WM_SIZING:
3263 RECT *sr = (RECT *)lParam;
3264 int wx, wy, isedge = 0;
3266 if (wParam == WMSZ_TOP ||
3267 wParam == WMSZ_RIGHT ||
3268 wParam == WMSZ_BOTTOM ||
3269 wParam == WMSZ_LEFT) isedge = 1;
3270 adjust_game_size(fe, sr, isedge, &wx, &wy);
3272 /* Given the window size the puzzles constrain
3273 * us to, work out which edge we should be moving. */
3274 if (wParam == WMSZ_TOP ||
3275 wParam == WMSZ_TOPLEFT ||
3276 wParam == WMSZ_TOPRIGHT) {
3277 sr->top = sr->bottom - wy;
3278 } else {
3279 sr->bottom = sr->top + wy;
3281 if (wParam == WMSZ_LEFT ||
3282 wParam == WMSZ_TOPLEFT ||
3283 wParam == WMSZ_BOTTOMLEFT) {
3284 sr->left = sr->right - wx;
3285 } else {
3286 sr->right = sr->left + wx;
3288 return TRUE;
3290 break;
3291 #endif
3294 return DefWindowProc(hwnd, message, wParam, lParam);
3297 #ifdef _WIN32_WCE
3298 static int FindPreviousInstance()
3300 /* Check if application is running. If it's running then focus on the window */
3301 HWND hOtherWnd = NULL;
3303 hOtherWnd = FindWindow (wGameName, wGameName);
3304 if (hOtherWnd)
3306 SetForegroundWindow (hOtherWnd);
3307 return TRUE;
3310 return FALSE;
3312 #endif
3314 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
3316 MSG msg;
3317 char *error;
3318 const game *gg;
3319 frontend *fe;
3321 #ifdef _WIN32_WCE
3322 MultiByteToWideChar (CP_ACP, 0, CLASSNAME, -1, wClassName, 256);
3323 if (FindPreviousInstance ())
3324 return 0;
3325 #endif
3327 InitCommonControls();
3329 if (!prev) {
3330 WNDCLASS wndclass;
3332 wndclass.style = 0;
3333 wndclass.lpfnWndProc = WndProc;
3334 wndclass.cbClsExtra = 0;
3335 wndclass.cbWndExtra = 0;
3336 wndclass.hInstance = inst;
3337 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
3338 #ifndef _WIN32_WCE
3339 if (!wndclass.hIcon) /* in case resource file is absent */
3340 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
3341 #endif
3342 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
3343 wndclass.hbrBackground = NULL;
3344 wndclass.lpszMenuName = NULL;
3345 #ifdef _WIN32_WCE
3346 wndclass.lpszClassName = wClassName;
3347 #else
3348 wndclass.lpszClassName = CLASSNAME;
3349 #endif
3351 RegisterClass(&wndclass);
3354 while (*cmdline && isspace((unsigned char)*cmdline))
3355 cmdline++;
3357 init_help();
3359 #ifdef COMBINED
3360 gg = gamelist[0];
3362 int i;
3363 for (i = 0; i < gamecount; i++) {
3364 const char *p = gamelist[i]->name;
3365 char *q = cmdline;
3366 while (*q && isspace((unsigned char)*q))
3367 q++;
3368 while (*p && *q) {
3369 if (isspace((unsigned char)*p)) {
3370 while (*q && isspace((unsigned char)*q))
3371 q++;
3372 } else {
3373 if (tolower((unsigned char)*p) !=
3374 tolower((unsigned char)*q))
3375 break;
3376 q++;
3378 p++;
3380 if (!*p) {
3381 gg = gamelist[i];
3382 cmdline = q;
3383 if (*cmdline) {
3384 while (*cmdline && isspace((unsigned char)*cmdline))
3385 cmdline++;
3390 #else
3391 gg = &thegame;
3392 #endif
3394 fe = frontend_new(inst);
3395 if (new_game(fe, gg, *cmdline ? cmdline : NULL, &error)) {
3396 char buf[128];
3397 sprintf(buf, "%.100s Error", gg->name);
3398 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
3399 return 1;
3401 show_window(fe);
3403 while (GetMessage(&msg, NULL, 0, 0)) {
3404 DispatchMessage(&msg);
3407 DestroyWindow(fe->hwnd);
3408 cleanup_help();
3410 return msg.wParam;
3412 /* vim: set shiftwidth=4 tabstop=8: */