Implement tick marks in the Type menu on Windows. Now all my front
[sgt/puzzles] / windows.c
1 /*
2 * windows.c: Windows front end for my puzzle collection.
3 */
4
5 #include <windows.h>
6 #include <commctrl.h>
7 #ifndef NO_HTMLHELP
8 #include <htmlhelp.h>
9 #endif /* NO_HTMLHELP */
10
11 #ifdef _WIN32_WCE
12 #include <commdlg.h>
13 #include <aygshell.h>
14 #endif
15
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>
23
24 #include "puzzles.h"
25
26 #ifdef _WIN32_WCE
27 #include "resource.h"
28 #endif
29
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
48 #define IDM_KEYEMUL 0x0400
49
50 #define HELP_FILE_NAME "puzzles.hlp"
51 #define HELP_CNT_NAME "puzzles.cnt"
52 #ifndef NO_HTMLHELP
53 #define CHM_FILE_NAME "puzzles.chm"
54 #endif /* NO_HTMLHELP */
55
56 #ifndef NO_HTMLHELP
57 typedef HWND (CALLBACK *htmlhelp_t)(HWND, LPCSTR, UINT, DWORD);
58 static htmlhelp_t htmlhelp;
59 static HINSTANCE hh_dll;
60 #endif /* NO_HTMLHELP */
61 enum { NONE, HLP, CHM } help_type;
62 char *help_path;
63 const char *help_topic;
64 int help_has_contents;
65
66 #ifndef FILENAME_MAX
67 #define FILENAME_MAX (260)
68 #endif
69
70 #ifndef HGDI_ERROR
71 #define HGDI_ERROR ((HANDLE)GDI_ERROR)
72 #endif
73
74 #ifdef _WIN32_WCE
75
76 /*
77 * Wrapper implementations of functions not supplied by the
78 * PocketPC API.
79 */
80
81 #define SHGetSubMenu(hWndMB,ID_MENU) (HMENU)SendMessage((hWndMB), SHCMBM_GETSUBMENU, (WPARAM)0, (LPARAM)ID_MENU)
82
83 #undef MessageBox
84
85 int MessageBox(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType)
86 {
87 TCHAR wText[2048];
88 TCHAR wCaption[2048];
89
90 MultiByteToWideChar (CP_ACP, 0, lpText, -1, wText, 2048);
91 MultiByteToWideChar (CP_ACP, 0, lpCaption, -1, wCaption, 2048);
92
93 return MessageBoxW (hWnd, wText, wCaption, uType);
94 }
95
96 BOOL SetDlgItemTextA(HWND hDlg, int nIDDlgItem, LPCSTR lpString)
97 {
98 TCHAR wText[256];
99
100 MultiByteToWideChar (CP_ACP, 0, lpString, -1, wText, 256);
101 return SetDlgItemTextW(hDlg, nIDDlgItem, wText);
102 }
103
104 LPCSTR getenv(LPCSTR buf)
105 {
106 return NULL;
107 }
108
109 BOOL GetKeyboardState(PBYTE pb)
110 {
111 return FALSE;
112 }
113
114 static TCHAR wGameName[256];
115
116 #endif
117
118 #ifdef DEBUGGING
119 static FILE *debug_fp = NULL;
120 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
121 static int debug_got_console = 0;
122
123 void dputs(char *buf)
124 {
125 DWORD dw;
126
127 if (!debug_got_console) {
128 if (AllocConsole()) {
129 debug_got_console = 1;
130 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
131 }
132 }
133 if (!debug_fp) {
134 debug_fp = fopen("debug.log", "w");
135 }
136
137 if (debug_hdl != INVALID_HANDLE_VALUE) {
138 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
139 }
140 fputs(buf, debug_fp);
141 fflush(debug_fp);
142 OutputDebugString(buf);
143 }
144
145 void debug_printf(char *fmt, ...)
146 {
147 char buf[4096];
148 va_list ap;
149
150 va_start(ap, fmt);
151 _vsnprintf(buf, 4095, fmt, ap);
152 dputs(buf);
153 va_end(ap);
154 }
155 #endif
156
157 #ifndef _WIN32_WCE
158 #define WINFLAGS (WS_OVERLAPPEDWINDOW &~ \
159 (WS_MAXIMIZEBOX | WS_OVERLAPPED))
160 #else
161 #define WINFLAGS (WS_CAPTION | WS_SYSMENU)
162 #endif
163
164 static void new_game_size(frontend *fe);
165
166 struct font {
167 HFONT font;
168 int type;
169 int size;
170 };
171
172 struct cfg_aux {
173 int ctlid;
174 };
175
176 struct blitter {
177 HBITMAP bitmap;
178 frontend *fe;
179 int x, y, w, h;
180 };
181
182 enum { CFG_PRINT = CFG_FRONTEND_SPECIFIC };
183
184 struct frontend {
185 midend *me;
186 HWND hwnd, statusbar, cfgbox;
187 #ifdef _WIN32_WCE
188 HWND numpad; /* window handle for the numeric pad */
189 #endif
190 HINSTANCE inst;
191 HBITMAP bitmap, prevbm;
192 RECT bitmapPosition; /* game bitmap position within game window */
193 HDC hdc;
194 COLORREF *colours;
195 HBRUSH *brushes;
196 HPEN *pens;
197 HRGN clip;
198 HMENU typemenu;
199 UINT timer;
200 DWORD timer_last_tickcount;
201 int npresets;
202 game_params **presets;
203 struct font *fonts;
204 int nfonts, fontsize;
205 config_item *cfg;
206 struct cfg_aux *cfgaux;
207 int cfg_which, dlg_done;
208 HFONT cfgfont;
209 HBRUSH oldbr;
210 HPEN oldpen;
211 int help_running;
212 enum { DRAWING, PRINTING, NOTHING } drawstatus;
213 DOCINFO di;
214 int printcount, printw, printh, printsolns, printcurr, printcolour;
215 float printscale;
216 int printoffsetx, printoffsety;
217 float printpixelscale;
218 int fontstart;
219 int linewidth;
220 drawing *dr;
221 int xmin, ymin;
222 };
223
224 static void update_type_menu_tick(frontend *fe);
225
226 void fatal(char *fmt, ...)
227 {
228 char buf[2048];
229 va_list ap;
230
231 va_start(ap, fmt);
232 vsprintf(buf, fmt, ap);
233 va_end(ap);
234
235 MessageBox(NULL, buf, "Fatal error", MB_ICONEXCLAMATION | MB_OK);
236
237 exit(1);
238 }
239
240 char *geterrstr(void)
241 {
242 LPVOID lpMsgBuf;
243 DWORD dw = GetLastError();
244 char *ret;
245
246 FormatMessage(
247 FORMAT_MESSAGE_ALLOCATE_BUFFER |
248 FORMAT_MESSAGE_FROM_SYSTEM,
249 NULL,
250 dw,
251 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
252 (LPTSTR) &lpMsgBuf,
253 0, NULL );
254
255 ret = dupstr(lpMsgBuf);
256
257 LocalFree(lpMsgBuf);
258
259 return ret;
260 }
261
262 void get_random_seed(void **randseed, int *randseedsize)
263 {
264 SYSTEMTIME *st = snew(SYSTEMTIME);
265
266 GetLocalTime(st);
267
268 *randseed = (void *)st;
269 *randseedsize = sizeof(SYSTEMTIME);
270 }
271
272 static void win_status_bar(void *handle, char *text)
273 {
274 #ifdef _WIN32_WCE
275 TCHAR wText[255];
276 #endif
277 frontend *fe = (frontend *)handle;
278
279 #ifdef _WIN32_WCE
280 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 255);
281 SendMessage(fe->statusbar, SB_SETTEXT,
282 (WPARAM) 255 | SBT_NOBORDERS,
283 (LPARAM) wText);
284 #else
285 SetWindowText(fe->statusbar, text);
286 #endif
287 }
288
289 static blitter *win_blitter_new(void *handle, int w, int h)
290 {
291 blitter *bl = snew(blitter);
292
293 memset(bl, 0, sizeof(blitter));
294 bl->w = w;
295 bl->h = h;
296 bl->bitmap = 0;
297
298 return bl;
299 }
300
301 static void win_blitter_free(void *handle, blitter *bl)
302 {
303 if (bl->bitmap) DeleteObject(bl->bitmap);
304 sfree(bl);
305 }
306
307 static void blitter_mkbitmap(frontend *fe, blitter *bl)
308 {
309 HDC hdc = GetDC(fe->hwnd);
310 bl->bitmap = CreateCompatibleBitmap(hdc, bl->w, bl->h);
311 ReleaseDC(fe->hwnd, hdc);
312 }
313
314 /* BitBlt(dstDC, dstX, dstY, dstW, dstH, srcDC, srcX, srcY, dType) */
315
316 static void win_blitter_save(void *handle, blitter *bl, int x, int y)
317 {
318 frontend *fe = (frontend *)handle;
319 HDC hdc_win, hdc_blit;
320 HBITMAP prev_blit;
321
322 assert(fe->drawstatus == DRAWING);
323
324 if (!bl->bitmap) blitter_mkbitmap(fe, bl);
325
326 bl->x = x; bl->y = y;
327
328 hdc_win = GetDC(fe->hwnd);
329 hdc_blit = CreateCompatibleDC(hdc_win);
330 if (!hdc_blit) fatal("hdc_blit failed: 0x%x", GetLastError());
331
332 prev_blit = SelectObject(hdc_blit, bl->bitmap);
333 if (prev_blit == NULL || prev_blit == HGDI_ERROR)
334 fatal("SelectObject for hdc_main failed: 0x%x", GetLastError());
335
336 if (!BitBlt(hdc_blit, 0, 0, bl->w, bl->h,
337 fe->hdc, x, y, SRCCOPY))
338 fatal("BitBlt failed: 0x%x", GetLastError());
339
340 SelectObject(hdc_blit, prev_blit);
341 DeleteDC(hdc_blit);
342 ReleaseDC(fe->hwnd, hdc_win);
343 }
344
345 static void win_blitter_load(void *handle, blitter *bl, int x, int y)
346 {
347 frontend *fe = (frontend *)handle;
348 HDC hdc_win, hdc_blit;
349 HBITMAP prev_blit;
350
351 assert(fe->drawstatus == DRAWING);
352
353 assert(bl->bitmap); /* we should always have saved before loading */
354
355 if (x == BLITTER_FROMSAVED) x = bl->x;
356 if (y == BLITTER_FROMSAVED) y = bl->y;
357
358 hdc_win = GetDC(fe->hwnd);
359 hdc_blit = CreateCompatibleDC(hdc_win);
360
361 prev_blit = SelectObject(hdc_blit, bl->bitmap);
362
363 BitBlt(fe->hdc, x, y, bl->w, bl->h,
364 hdc_blit, 0, 0, SRCCOPY);
365
366 SelectObject(hdc_blit, prev_blit);
367 DeleteDC(hdc_blit);
368 ReleaseDC(fe->hwnd, hdc_win);
369 }
370
371 void frontend_default_colour(frontend *fe, float *output)
372 {
373 DWORD c = GetSysColor(COLOR_MENU); /* ick */
374
375 output[0] = (float)(GetRValue(c) / 255.0);
376 output[1] = (float)(GetGValue(c) / 255.0);
377 output[2] = (float)(GetBValue(c) / 255.0);
378 }
379
380 static POINT win_transform_point(frontend *fe, int x, int y)
381 {
382 POINT ret;
383
384 assert(fe->drawstatus != NOTHING);
385
386 if (fe->drawstatus == PRINTING) {
387 ret.x = (int)(fe->printoffsetx + fe->printpixelscale * x);
388 ret.y = (int)(fe->printoffsety + fe->printpixelscale * y);
389 } else {
390 ret.x = x;
391 ret.y = y;
392 }
393
394 return ret;
395 }
396
397 static void win_text_colour(frontend *fe, int colour)
398 {
399 assert(fe->drawstatus != NOTHING);
400
401 if (fe->drawstatus == PRINTING) {
402 int hatch;
403 float r, g, b;
404 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
405
406 /*
407 * Displaying text in hatched colours is not permitted.
408 */
409 assert(hatch < 0);
410
411 SetTextColor(fe->hdc, RGB(r * 255, g * 255, b * 255));
412 } else {
413 SetTextColor(fe->hdc, fe->colours[colour]);
414 }
415 }
416
417 static void win_set_brush(frontend *fe, int colour)
418 {
419 HBRUSH br;
420 assert(fe->drawstatus != NOTHING);
421
422 if (fe->drawstatus == PRINTING) {
423 int hatch;
424 float r, g, b;
425 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
426
427 if (hatch < 0) {
428 br = CreateSolidBrush(RGB(r * 255, g * 255, b * 255));
429 } else {
430 #ifdef _WIN32_WCE
431 /*
432 * This is only ever required during printing, and the
433 * PocketPC port doesn't support printing.
434 */
435 fatal("CreateHatchBrush not supported");
436 #else
437 br = CreateHatchBrush(hatch == HATCH_BACKSLASH ? HS_FDIAGONAL :
438 hatch == HATCH_SLASH ? HS_BDIAGONAL :
439 hatch == HATCH_HORIZ ? HS_HORIZONTAL :
440 hatch == HATCH_VERT ? HS_VERTICAL :
441 hatch == HATCH_PLUS ? HS_CROSS :
442 /* hatch == HATCH_X ? */ HS_DIAGCROSS,
443 RGB(0,0,0));
444 #endif
445 }
446 } else {
447 br = fe->brushes[colour];
448 }
449 fe->oldbr = SelectObject(fe->hdc, br);
450 }
451
452 static void win_reset_brush(frontend *fe)
453 {
454 HBRUSH br;
455
456 assert(fe->drawstatus != NOTHING);
457
458 br = SelectObject(fe->hdc, fe->oldbr);
459 if (fe->drawstatus == PRINTING)
460 DeleteObject(br);
461 }
462
463 static void win_set_pen(frontend *fe, int colour, int thin)
464 {
465 HPEN pen;
466 assert(fe->drawstatus != NOTHING);
467
468 if (fe->drawstatus == PRINTING) {
469 int hatch;
470 float r, g, b;
471 int width = thin ? 0 : fe->linewidth;
472
473 print_get_colour(fe->dr, colour, fe->printcolour, &hatch, &r, &g, &b);
474 /*
475 * Stroking in hatched colours is not permitted.
476 */
477 assert(hatch < 0);
478 pen = CreatePen(PS_SOLID, width, RGB(r * 255, g * 255, b * 255));
479 } else {
480 pen = fe->pens[colour];
481 }
482 fe->oldpen = SelectObject(fe->hdc, pen);
483 }
484
485 static void win_reset_pen(frontend *fe)
486 {
487 HPEN pen;
488
489 assert(fe->drawstatus != NOTHING);
490
491 pen = SelectObject(fe->hdc, fe->oldpen);
492 if (fe->drawstatus == PRINTING)
493 DeleteObject(pen);
494 }
495
496 static void win_clip(void *handle, int x, int y, int w, int h)
497 {
498 frontend *fe = (frontend *)handle;
499 POINT p, q;
500
501 if (fe->drawstatus == NOTHING)
502 return;
503
504 p = win_transform_point(fe, x, y);
505 q = win_transform_point(fe, x+w, y+h);
506 IntersectClipRect(fe->hdc, p.x, p.y, q.x, q.y);
507 }
508
509 static void win_unclip(void *handle)
510 {
511 frontend *fe = (frontend *)handle;
512
513 if (fe->drawstatus == NOTHING)
514 return;
515
516 SelectClipRgn(fe->hdc, NULL);
517 }
518
519 static void win_draw_text(void *handle, int x, int y, int fonttype,
520 int fontsize, int align, int colour, char *text)
521 {
522 frontend *fe = (frontend *)handle;
523 POINT xy;
524 int i;
525 LOGFONT lf;
526
527 if (fe->drawstatus == NOTHING)
528 return;
529
530 if (fe->drawstatus == PRINTING)
531 fontsize = (int)(fontsize * fe->printpixelscale);
532
533 xy = win_transform_point(fe, x, y);
534
535 /*
536 * Find or create the font.
537 */
538 for (i = fe->fontstart; i < fe->nfonts; i++)
539 if (fe->fonts[i].type == fonttype && fe->fonts[i].size == fontsize)
540 break;
541
542 if (i == fe->nfonts) {
543 if (fe->fontsize <= fe->nfonts) {
544 fe->fontsize = fe->nfonts + 10;
545 fe->fonts = sresize(fe->fonts, fe->fontsize, struct font);
546 }
547
548 fe->nfonts++;
549
550 fe->fonts[i].type = fonttype;
551 fe->fonts[i].size = fontsize;
552
553 memset (&lf, 0, sizeof(LOGFONT));
554 lf.lfHeight = -fontsize;
555 lf.lfWeight = (fe->drawstatus == PRINTING ? 0 : FW_BOLD);
556 lf.lfCharSet = DEFAULT_CHARSET;
557 lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
558 lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
559 lf.lfQuality = DEFAULT_QUALITY;
560 lf.lfPitchAndFamily = (fonttype == FONT_FIXED ?
561 FIXED_PITCH | FF_DONTCARE :
562 VARIABLE_PITCH | FF_SWISS);
563 #ifdef _WIN32_WCE
564 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
565 #endif
566
567 fe->fonts[i].font = CreateFontIndirect(&lf);
568 }
569
570 /*
571 * Position and draw the text.
572 */
573 {
574 HFONT oldfont;
575 TEXTMETRIC tm;
576 SIZE size;
577 #ifdef _WIN32_WCE
578 TCHAR wText[256];
579 MultiByteToWideChar (CP_ACP, 0, text, -1, wText, 256);
580 #endif
581
582 oldfont = SelectObject(fe->hdc, fe->fonts[i].font);
583 if (GetTextMetrics(fe->hdc, &tm)) {
584 if (align & ALIGN_VCENTRE)
585 xy.y -= (tm.tmAscent+tm.tmDescent)/2;
586 else
587 xy.y -= tm.tmAscent;
588 }
589 #ifndef _WIN32_WCE
590 if (GetTextExtentPoint32(fe->hdc, text, strlen(text), &size))
591 #else
592 if (GetTextExtentPoint32(fe->hdc, wText, wcslen(wText), &size))
593 #endif
594 {
595 if (align & ALIGN_HCENTRE)
596 xy.x -= size.cx / 2;
597 else if (align & ALIGN_HRIGHT)
598 xy.x -= size.cx;
599 }
600 SetBkMode(fe->hdc, TRANSPARENT);
601 win_text_colour(fe, colour);
602 #ifndef _WIN32_WCE
603 TextOut(fe->hdc, xy.x, xy.y, text, strlen(text));
604 #else
605 ExtTextOut(fe->hdc, xy.x, xy.y, 0, NULL, wText, wcslen(wText), NULL);
606 #endif
607 SelectObject(fe->hdc, oldfont);
608 }
609 }
610
611 static void win_draw_rect(void *handle, int x, int y, int w, int h, int colour)
612 {
613 frontend *fe = (frontend *)handle;
614 POINT p, q;
615
616 if (fe->drawstatus == NOTHING)
617 return;
618
619 if (fe->drawstatus == DRAWING && w == 1 && h == 1) {
620 /*
621 * Rectangle() appears to get uppity if asked to draw a 1x1
622 * rectangle, presumably on the grounds that that's beneath
623 * its dignity and you ought to be using SetPixel instead.
624 * So I will.
625 */
626 SetPixel(fe->hdc, x, y, fe->colours[colour]);
627 } else {
628 win_set_brush(fe, colour);
629 win_set_pen(fe, colour, TRUE);
630 p = win_transform_point(fe, x, y);
631 q = win_transform_point(fe, x+w, y+h);
632 Rectangle(fe->hdc, p.x, p.y, q.x, q.y);
633 win_reset_brush(fe);
634 win_reset_pen(fe);
635 }
636 }
637
638 static void win_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
639 {
640 frontend *fe = (frontend *)handle;
641 POINT pp[2];
642
643 if (fe->drawstatus == NOTHING)
644 return;
645
646 win_set_pen(fe, colour, FALSE);
647 pp[0] = win_transform_point(fe, x1, y1);
648 pp[1] = win_transform_point(fe, x2, y2);
649 Polyline(fe->hdc, pp, 2);
650 if (fe->drawstatus == DRAWING)
651 SetPixel(fe->hdc, pp[1].x, pp[1].y, fe->colours[colour]);
652 win_reset_pen(fe);
653 }
654
655 static void win_draw_circle(void *handle, int cx, int cy, int radius,
656 int fillcolour, int outlinecolour)
657 {
658 frontend *fe = (frontend *)handle;
659 POINT p, q;
660
661 assert(outlinecolour >= 0);
662
663 if (fe->drawstatus == NOTHING)
664 return;
665
666 if (fillcolour >= 0)
667 win_set_brush(fe, fillcolour);
668 else
669 fe->oldbr = SelectObject(fe->hdc, GetStockObject(NULL_BRUSH));
670
671 win_set_pen(fe, outlinecolour, FALSE);
672 p = win_transform_point(fe, cx - radius, cy - radius);
673 q = win_transform_point(fe, cx + radius, cy + radius);
674 Ellipse(fe->hdc, p.x, p.y, q.x+1, q.y+1);
675 win_reset_brush(fe);
676 win_reset_pen(fe);
677 }
678
679 static void win_draw_polygon(void *handle, int *coords, int npoints,
680 int fillcolour, int outlinecolour)
681 {
682 frontend *fe = (frontend *)handle;
683 POINT *pts;
684 int i;
685
686 if (fe->drawstatus == NOTHING)
687 return;
688
689 pts = snewn(npoints+1, POINT);
690
691 for (i = 0; i <= npoints; i++) {
692 int j = (i < npoints ? i : 0);
693 pts[i] = win_transform_point(fe, coords[j*2], coords[j*2+1]);
694 }
695
696 assert(outlinecolour >= 0);
697
698 if (fillcolour >= 0) {
699 win_set_brush(fe, fillcolour);
700 win_set_pen(fe, outlinecolour, FALSE);
701 Polygon(fe->hdc, pts, npoints);
702 win_reset_brush(fe);
703 win_reset_pen(fe);
704 } else {
705 win_set_pen(fe, outlinecolour, FALSE);
706 Polyline(fe->hdc, pts, npoints+1);
707 win_reset_pen(fe);
708 }
709
710 sfree(pts);
711 }
712
713 static void win_start_draw(void *handle)
714 {
715 frontend *fe = (frontend *)handle;
716 HDC hdc_win;
717
718 assert(fe->drawstatus == NOTHING);
719
720 hdc_win = GetDC(fe->hwnd);
721 fe->hdc = CreateCompatibleDC(hdc_win);
722 fe->prevbm = SelectObject(fe->hdc, fe->bitmap);
723 ReleaseDC(fe->hwnd, hdc_win);
724 fe->clip = NULL;
725 #ifndef _WIN32_WCE
726 SetMapMode(fe->hdc, MM_TEXT);
727 #endif
728 fe->drawstatus = DRAWING;
729 }
730
731 static void win_draw_update(void *handle, int x, int y, int w, int h)
732 {
733 frontend *fe = (frontend *)handle;
734 RECT r;
735
736 if (fe->drawstatus != DRAWING)
737 return;
738
739 r.left = x;
740 r.top = y;
741 r.right = x + w;
742 r.bottom = y + h;
743
744 OffsetRect(&r, fe->bitmapPosition.left, fe->bitmapPosition.top);
745 InvalidateRect(fe->hwnd, &r, FALSE);
746 }
747
748 static void win_end_draw(void *handle)
749 {
750 frontend *fe = (frontend *)handle;
751 assert(fe->drawstatus == DRAWING);
752 SelectObject(fe->hdc, fe->prevbm);
753 DeleteDC(fe->hdc);
754 if (fe->clip) {
755 DeleteObject(fe->clip);
756 fe->clip = NULL;
757 }
758 fe->drawstatus = NOTHING;
759 }
760
761 static void win_line_width(void *handle, float width)
762 {
763 frontend *fe = (frontend *)handle;
764
765 assert(fe->drawstatus != DRAWING);
766 if (fe->drawstatus == NOTHING)
767 return;
768
769 fe->linewidth = (int)(width * fe->printpixelscale);
770 }
771
772 static void win_begin_doc(void *handle, int pages)
773 {
774 frontend *fe = (frontend *)handle;
775
776 assert(fe->drawstatus != DRAWING);
777 if (fe->drawstatus == NOTHING)
778 return;
779
780 if (StartDoc(fe->hdc, &fe->di) <= 0) {
781 char *e = geterrstr();
782 MessageBox(fe->hwnd, e, "Error starting to print",
783 MB_ICONERROR | MB_OK);
784 sfree(e);
785 fe->drawstatus = NOTHING;
786 }
787
788 /*
789 * Push a marker on the font stack so that we won't use the
790 * same fonts for printing and drawing. (This is because
791 * drawing seems to look generally better in bold, but printing
792 * is better not in bold.)
793 */
794 fe->fontstart = fe->nfonts;
795 }
796
797 static void win_begin_page(void *handle, int number)
798 {
799 frontend *fe = (frontend *)handle;
800
801 assert(fe->drawstatus != DRAWING);
802 if (fe->drawstatus == NOTHING)
803 return;
804
805 if (StartPage(fe->hdc) <= 0) {
806 char *e = geterrstr();
807 MessageBox(fe->hwnd, e, "Error starting a page",
808 MB_ICONERROR | MB_OK);
809 sfree(e);
810 fe->drawstatus = NOTHING;
811 }
812 }
813
814 static void win_begin_puzzle(void *handle, float xm, float xc,
815 float ym, float yc, int pw, int ph, float wmm)
816 {
817 frontend *fe = (frontend *)handle;
818 int ppw, pph, pox, poy;
819 float mmpw, mmph, mmox, mmoy;
820 float scale;
821
822 assert(fe->drawstatus != DRAWING);
823 if (fe->drawstatus == NOTHING)
824 return;
825
826 ppw = GetDeviceCaps(fe->hdc, HORZRES);
827 pph = GetDeviceCaps(fe->hdc, VERTRES);
828 mmpw = (float)GetDeviceCaps(fe->hdc, HORZSIZE);
829 mmph = (float)GetDeviceCaps(fe->hdc, VERTSIZE);
830
831 /*
832 * Compute the puzzle's position on the logical page.
833 */
834 mmox = xm * mmpw + xc;
835 mmoy = ym * mmph + yc;
836
837 /*
838 * Work out what that comes to in pixels.
839 */
840 pox = (int)(mmox * (float)ppw / mmpw);
841 poy = (int)(mmoy * (float)ppw / mmpw);
842
843 /*
844 * And determine the scale.
845 *
846 * I need a scale such that the maximum puzzle-coordinate
847 * extent of the rectangle (pw * scale) is equal to the pixel
848 * equivalent of the puzzle's millimetre width (wmm * ppw /
849 * mmpw).
850 */
851 scale = (wmm * ppw) / (mmpw * pw);
852
853 /*
854 * Now store pox, poy and scale for use in the main drawing
855 * functions.
856 */
857 fe->printoffsetx = pox;
858 fe->printoffsety = poy;
859 fe->printpixelscale = scale;
860
861 fe->linewidth = 1;
862 }
863
864 static void win_end_puzzle(void *handle)
865 {
866 /* Nothing needs to be done here. */
867 }
868
869 static void win_end_page(void *handle, int number)
870 {
871 frontend *fe = (frontend *)handle;
872
873 assert(fe->drawstatus != DRAWING);
874
875 if (fe->drawstatus == NOTHING)
876 return;
877
878 if (EndPage(fe->hdc) <= 0) {
879 char *e = geterrstr();
880 MessageBox(fe->hwnd, e, "Error finishing a page",
881 MB_ICONERROR | MB_OK);
882 sfree(e);
883 fe->drawstatus = NOTHING;
884 }
885 }
886
887 static void win_end_doc(void *handle)
888 {
889 frontend *fe = (frontend *)handle;
890
891 assert(fe->drawstatus != DRAWING);
892
893 /*
894 * Free all the fonts created since we began printing.
895 */
896 while (fe->nfonts > fe->fontstart) {
897 fe->nfonts--;
898 DeleteObject(fe->fonts[fe->nfonts].font);
899 }
900 fe->fontstart = 0;
901
902 /*
903 * The MSDN web site sample code doesn't bother to call EndDoc
904 * if an error occurs half way through printing. I expect doing
905 * so would cause the erroneous document to actually be
906 * printed, or something equally undesirable.
907 */
908 if (fe->drawstatus == NOTHING)
909 return;
910
911 if (EndDoc(fe->hdc) <= 0) {
912 char *e = geterrstr();
913 MessageBox(fe->hwnd, e, "Error finishing printing",
914 MB_ICONERROR | MB_OK);
915 sfree(e);
916 fe->drawstatus = NOTHING;
917 }
918 }
919
920 const struct drawing_api win_drawing = {
921 win_draw_text,
922 win_draw_rect,
923 win_draw_line,
924 win_draw_polygon,
925 win_draw_circle,
926 win_draw_update,
927 win_clip,
928 win_unclip,
929 win_start_draw,
930 win_end_draw,
931 win_status_bar,
932 win_blitter_new,
933 win_blitter_free,
934 win_blitter_save,
935 win_blitter_load,
936 win_begin_doc,
937 win_begin_page,
938 win_begin_puzzle,
939 win_end_puzzle,
940 win_end_page,
941 win_end_doc,
942 win_line_width,
943 };
944
945 void print(frontend *fe)
946 {
947 #ifndef _WIN32_WCE
948 PRINTDLG pd;
949 char doctitle[256];
950 document *doc;
951 midend *nme = NULL; /* non-interactive midend for bulk puzzle generation */
952 int i;
953 char *err = NULL;
954
955 /*
956 * Create our document structure and fill it up with puzzles.
957 */
958 doc = document_new(fe->printw, fe->printh, fe->printscale / 100.0F);
959 for (i = 0; i < fe->printcount; i++) {
960 if (i == 0 && fe->printcurr) {
961 err = midend_print_puzzle(fe->me, doc, fe->printsolns);
962 } else {
963 if (!nme) {
964 game_params *params;
965
966 nme = midend_new(NULL, &thegame, NULL, NULL);
967
968 /*
969 * Set the non-interactive mid-end to have the same
970 * parameters as the standard one.
971 */
972 params = midend_get_params(fe->me);
973 midend_set_params(nme, params);
974 thegame.free_params(params);
975 }
976
977 midend_new_game(nme);
978 err = midend_print_puzzle(nme, doc, fe->printsolns);
979 }
980 if (err)
981 break;
982 }
983 if (nme)
984 midend_free(nme);
985
986 if (err) {
987 MessageBox(fe->hwnd, err, "Error preparing puzzles for printing",
988 MB_ICONERROR | MB_OK);
989 document_free(doc);
990 return;
991 }
992
993 memset(&pd, 0, sizeof(pd));
994 pd.lStructSize = sizeof(pd);
995 pd.hwndOwner = fe->hwnd;
996 pd.hDevMode = NULL;
997 pd.hDevNames = NULL;
998 pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC |
999 PD_NOPAGENUMS | PD_NOSELECTION;
1000 pd.nCopies = 1;
1001 pd.nFromPage = pd.nToPage = 0xFFFF;
1002 pd.nMinPage = pd.nMaxPage = 1;
1003
1004 if (!PrintDlg(&pd)) {
1005 document_free(doc);
1006 return;
1007 }
1008
1009 /*
1010 * Now pd.hDC is a device context for the printer.
1011 */
1012
1013 /*
1014 * FIXME: IWBNI we put up an Abort box here.
1015 */
1016
1017 memset(&fe->di, 0, sizeof(fe->di));
1018 fe->di.cbSize = sizeof(fe->di);
1019 sprintf(doctitle, "Printed puzzles from %s (from Simon Tatham's"
1020 " Portable Puzzle Collection)", thegame.name);
1021 fe->di.lpszDocName = doctitle;
1022 fe->di.lpszOutput = NULL;
1023 fe->di.lpszDatatype = NULL;
1024 fe->di.fwType = 0;
1025
1026 fe->drawstatus = PRINTING;
1027 fe->hdc = pd.hDC;
1028
1029 fe->dr = drawing_new(&win_drawing, NULL, fe);
1030 document_print(doc, fe->dr);
1031 drawing_free(fe->dr);
1032 fe->dr = NULL;
1033
1034 fe->drawstatus = NOTHING;
1035
1036 DeleteDC(pd.hDC);
1037 document_free(doc);
1038 #endif
1039 }
1040
1041 void deactivate_timer(frontend *fe)
1042 {
1043 if (!fe)
1044 return; /* for non-interactive midend */
1045 if (fe->hwnd) KillTimer(fe->hwnd, fe->timer);
1046 fe->timer = 0;
1047 }
1048
1049 void activate_timer(frontend *fe)
1050 {
1051 if (!fe)
1052 return; /* for non-interactive midend */
1053 if (!fe->timer) {
1054 fe->timer = SetTimer(fe->hwnd, 1, 20, NULL);
1055 fe->timer_last_tickcount = GetTickCount();
1056 }
1057 }
1058
1059 void write_clip(HWND hwnd, char *data)
1060 {
1061 HGLOBAL clipdata;
1062 int len, i, j;
1063 char *data2;
1064 void *lock;
1065
1066 /*
1067 * Windows expects CRLF in the clipboard, so we must convert
1068 * any \n that has come out of the puzzle backend.
1069 */
1070 len = 0;
1071 for (i = 0; data[i]; i++) {
1072 if (data[i] == '\n')
1073 len++;
1074 len++;
1075 }
1076 data2 = snewn(len+1, char);
1077 j = 0;
1078 for (i = 0; data[i]; i++) {
1079 if (data[i] == '\n')
1080 data2[j++] = '\r';
1081 data2[j++] = data[i];
1082 }
1083 assert(j == len);
1084 data2[j] = '\0';
1085
1086 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
1087 if (!clipdata)
1088 return;
1089 lock = GlobalLock(clipdata);
1090 if (!lock)
1091 return;
1092 memcpy(lock, data2, len);
1093 ((unsigned char *) lock)[len] = 0;
1094 GlobalUnlock(clipdata);
1095
1096 if (OpenClipboard(hwnd)) {
1097 EmptyClipboard();
1098 SetClipboardData(CF_TEXT, clipdata);
1099 CloseClipboard();
1100 } else
1101 GlobalFree(clipdata);
1102
1103 sfree(data2);
1104 }
1105
1106 /*
1107 * Set up Help and see if we can find a help file.
1108 */
1109 static void init_help(void)
1110 {
1111 #ifndef _WIN32_WCE
1112 char b[2048], *p, *q, *r;
1113 FILE *fp;
1114
1115 /*
1116 * Find the executable file path, so we can look alongside
1117 * it for help files. Trim the filename off the end.
1118 */
1119 GetModuleFileName(NULL, b, sizeof(b) - 1);
1120 r = b;
1121 p = strrchr(b, '\\');
1122 if (p && p >= r) r = p+1;
1123 q = strrchr(b, ':');
1124 if (q && q >= r) r = q+1;
1125
1126 #ifndef NO_HTMLHELP
1127 /*
1128 * Try HTML Help first.
1129 */
1130 strcpy(r, CHM_FILE_NAME);
1131 if ( (fp = fopen(b, "r")) != NULL) {
1132 fclose(fp);
1133
1134 /*
1135 * We have a .CHM. See if we can use it.
1136 */
1137 hh_dll = LoadLibrary("hhctrl.ocx");
1138 if (hh_dll) {
1139 htmlhelp = (htmlhelp_t)GetProcAddress(hh_dll, "HtmlHelpA");
1140 if (!htmlhelp)
1141 FreeLibrary(hh_dll);
1142 }
1143 if (htmlhelp) {
1144 help_path = dupstr(b);
1145 help_type = CHM;
1146 help_topic = thegame.htmlhelp_topic;
1147 return;
1148 }
1149 }
1150 #endif /* NO_HTMLHELP */
1151
1152 /*
1153 * Now try old-style .HLP.
1154 */
1155 strcpy(r, HELP_FILE_NAME);
1156 if ( (fp = fopen(b, "r")) != NULL) {
1157 fclose(fp);
1158
1159 help_path = dupstr(b);
1160 help_type = HLP;
1161
1162 help_topic = thegame.winhelp_topic;
1163
1164 /*
1165 * See if there's a .CNT file alongside it.
1166 */
1167 strcpy(r, HELP_CNT_NAME);
1168 if ( (fp = fopen(b, "r")) != NULL) {
1169 fclose(fp);
1170 help_has_contents = TRUE;
1171 } else
1172 help_has_contents = FALSE;
1173
1174 return;
1175 }
1176
1177 help_type = NONE; /* didn't find any */
1178 #endif
1179 }
1180
1181 #ifndef _WIN32_WCE
1182
1183 /*
1184 * Start Help.
1185 */
1186 static void start_help(frontend *fe, const char *topic)
1187 {
1188 char *str = NULL;
1189 int cmd;
1190
1191 switch (help_type) {
1192 case HLP:
1193 assert(help_path);
1194 if (topic) {
1195 str = snewn(10+strlen(topic), char);
1196 sprintf(str, "JI(`',`%s')", topic);
1197 cmd = HELP_COMMAND;
1198 } else if (help_has_contents) {
1199 cmd = HELP_FINDER;
1200 } else {
1201 cmd = HELP_CONTENTS;
1202 }
1203 WinHelp(fe->hwnd, help_path, cmd, (DWORD)str);
1204 fe->help_running = TRUE;
1205 break;
1206 case CHM:
1207 #ifndef NO_HTMLHELP
1208 assert(help_path);
1209 assert(htmlhelp);
1210 if (topic) {
1211 str = snewn(20 + strlen(topic) + strlen(help_path), char);
1212 sprintf(str, "%s::/%s.html>main", help_path, topic);
1213 } else {
1214 str = dupstr(help_path);
1215 }
1216 htmlhelp(fe->hwnd, str, HH_DISPLAY_TOPIC, 0);
1217 fe->help_running = TRUE;
1218 break;
1219 #endif /* NO_HTMLHELP */
1220 case NONE:
1221 assert(!"This shouldn't happen");
1222 break;
1223 }
1224
1225 sfree(str);
1226 }
1227
1228 /*
1229 * Stop Help on window cleanup.
1230 */
1231 static void stop_help(frontend *fe)
1232 {
1233 if (fe->help_running) {
1234 switch (help_type) {
1235 case HLP:
1236 WinHelp(fe->hwnd, help_path, HELP_QUIT, 0);
1237 break;
1238 case CHM:
1239 #ifndef NO_HTMLHELP
1240 assert(htmlhelp);
1241 htmlhelp(NULL, NULL, HH_CLOSE_ALL, 0);
1242 break;
1243 #endif /* NO_HTMLHELP */
1244 case NONE:
1245 assert(!"This shouldn't happen");
1246 break;
1247 }
1248 fe->help_running = FALSE;
1249 }
1250 }
1251
1252 #endif
1253
1254 /*
1255 * Terminate Help on process exit.
1256 */
1257 static void cleanup_help(void)
1258 {
1259 /* Nothing to do currently.
1260 * (If we were running HTML Help single-threaded, this is where we'd
1261 * call HH_UNINITIALIZE.) */
1262 }
1263
1264 static int get_statusbar_height(frontend *fe)
1265 {
1266 int sy;
1267 if (fe->statusbar) {
1268 RECT sr;
1269 GetWindowRect(fe->statusbar, &sr);
1270 sy = sr.bottom - sr.top;
1271 } else {
1272 sy = 0;
1273 }
1274 return sy;
1275 }
1276
1277 static void adjust_statusbar(frontend *fe, RECT *r)
1278 {
1279 int sy;
1280
1281 if (!fe->statusbar) return;
1282
1283 sy = get_statusbar_height(fe);
1284 #ifndef _WIN32_WCE
1285 SetWindowPos(fe->statusbar, NULL, 0, r->bottom-r->top-sy, r->right-r->left,
1286 sy, SWP_NOZORDER);
1287 #endif
1288 }
1289
1290 static void get_menu_size(HWND wh, RECT *r)
1291 {
1292 HMENU bar = GetMenu(wh);
1293 RECT rect;
1294 int i;
1295
1296 SetRect(r, 0, 0, 0, 0);
1297 for (i = 0; i < GetMenuItemCount(bar); i++) {
1298 GetMenuItemRect(wh, bar, i, &rect);
1299 UnionRect(r, r, &rect);
1300 }
1301 }
1302
1303 /*
1304 * Given a proposed new puzzle size (cx,cy), work out the actual
1305 * puzzle size that would be (px,py) and the window size including
1306 * furniture (wx,wy).
1307 */
1308
1309 static int check_window_resize(frontend *fe, int cx, int cy,
1310 int *px, int *py,
1311 int *wx, int *wy, int resize)
1312 {
1313 RECT r;
1314 int x, y, sy = get_statusbar_height(fe), changed = 0;
1315
1316 /* disallow making window thinner than menu bar */
1317 x = max(cx, fe->xmin);
1318 y = max(cy - sy, fe->ymin);
1319
1320 /*
1321 * See if we actually got the window size we wanted, and adjust
1322 * the puzzle size if not.
1323 */
1324 midend_size(fe->me, &x, &y, resize);
1325 if (x != cx || y != cy) {
1326 /*
1327 * Resize the window, now we know what size we _really_
1328 * want it to be.
1329 */
1330 r.left = r.top = 0;
1331 r.right = x;
1332 r.bottom = y + sy;
1333 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1334 *wx = r.right - r.left;
1335 *wy = r.bottom - r.top;
1336 changed = 1;
1337 }
1338
1339 *px = x;
1340 *py = y;
1341
1342 return changed;
1343 }
1344
1345 /*
1346 * Given the current window size, make sure it's sane for the
1347 * current puzzle and resize if necessary.
1348 */
1349
1350 static void check_window_size(frontend *fe, int *px, int *py)
1351 {
1352 RECT r;
1353 int wx, wy, cx, cy;
1354
1355 GetClientRect(fe->hwnd, &r);
1356 cx = r.right - r.left;
1357 cy = r.bottom - r.top;
1358
1359 if (check_window_resize(fe, cx, cy, px, py, &wx, &wy, FALSE)) {
1360 #ifdef _WIN32_WCE
1361 SetWindowPos(fe->hwnd, NULL, 0, 0, wx, wy,
1362 SWP_NOMOVE | SWP_NOZORDER);
1363 #endif
1364 ;
1365 }
1366
1367 GetClientRect(fe->hwnd, &r);
1368 adjust_statusbar(fe, &r);
1369 }
1370
1371 static void get_max_puzzle_size(frontend *fe, int *x, int *y)
1372 {
1373 RECT r, sr;
1374
1375 if (SystemParametersInfo(SPI_GETWORKAREA, 0, &sr, FALSE)) {
1376 *x = sr.right - sr.left;
1377 *y = sr.bottom - sr.top;
1378 r.left = 100;
1379 r.right = 200;
1380 r.top = 100;
1381 r.bottom = 200;
1382 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1383 *x -= r.right - r.left - 100;
1384 *y -= r.bottom - r.top - 100;
1385 } else {
1386 *x = *y = INT_MAX;
1387 }
1388
1389 if (fe->statusbar != NULL) {
1390 GetWindowRect(fe->statusbar, &sr);
1391 *y -= sr.bottom - sr.top;
1392 }
1393 }
1394
1395 #ifdef _WIN32_WCE
1396 /* Toolbar buttons on the numeric pad */
1397 static TBBUTTON tbNumpadButtons[] =
1398 {
1399 {0, IDM_KEYEMUL + '1', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1400 {1, IDM_KEYEMUL + '2', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1401 {2, IDM_KEYEMUL + '3', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1402 {3, IDM_KEYEMUL + '4', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1403 {4, IDM_KEYEMUL + '5', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1404 {5, IDM_KEYEMUL + '6', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1405 {6, IDM_KEYEMUL + '7', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1406 {7, IDM_KEYEMUL + '8', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1407 {8, IDM_KEYEMUL + '9', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1},
1408 {9, IDM_KEYEMUL + ' ', TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, -1}
1409 };
1410 #endif
1411
1412 static frontend *new_window(HINSTANCE inst, char *game_id, char **error)
1413 {
1414 frontend *fe;
1415 int x, y;
1416 RECT r;
1417
1418 fe = snew(frontend);
1419
1420 fe->me = midend_new(fe, &thegame, &win_drawing, fe);
1421
1422 if (game_id) {
1423 *error = midend_game_id(fe->me, game_id);
1424 if (*error) {
1425 midend_free(fe->me);
1426 sfree(fe);
1427 return NULL;
1428 }
1429 }
1430
1431 fe->inst = inst;
1432
1433 fe->timer = 0;
1434 fe->hwnd = NULL;
1435
1436 fe->help_running = FALSE;
1437
1438 fe->drawstatus = NOTHING;
1439 fe->dr = NULL;
1440 fe->fontstart = 0;
1441
1442 midend_new_game(fe->me);
1443
1444 fe->fonts = NULL;
1445 fe->nfonts = fe->fontsize = 0;
1446
1447 {
1448 int i, ncolours;
1449 float *colours;
1450
1451 colours = midend_colours(fe->me, &ncolours);
1452
1453 fe->colours = snewn(ncolours, COLORREF);
1454 fe->brushes = snewn(ncolours, HBRUSH);
1455 fe->pens = snewn(ncolours, HPEN);
1456
1457 for (i = 0; i < ncolours; i++) {
1458 fe->colours[i] = RGB(255 * colours[i*3+0],
1459 255 * colours[i*3+1],
1460 255 * colours[i*3+2]);
1461 fe->brushes[i] = CreateSolidBrush(fe->colours[i]);
1462 fe->pens[i] = CreatePen(PS_SOLID, 1, fe->colours[i]);
1463 }
1464 sfree(colours);
1465 }
1466
1467 if (midend_wants_statusbar(fe->me)) {
1468 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1469 WS_CHILD | WS_VISIBLE,
1470 0, 0, 0, 0, /* status bar does these */
1471 NULL, NULL, inst, NULL);
1472 } else
1473 fe->statusbar = NULL;
1474
1475 get_max_puzzle_size(fe, &x, &y);
1476 midend_size(fe->me, &x, &y, FALSE);
1477
1478 r.left = r.top = 0;
1479 r.right = x;
1480 r.bottom = y;
1481 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
1482
1483 #ifdef _WIN32_WCE
1484 fe->hwnd = CreateWindowEx(0, wGameName, wGameName,
1485 WS_VISIBLE,
1486 CW_USEDEFAULT, CW_USEDEFAULT,
1487 CW_USEDEFAULT, CW_USEDEFAULT,
1488 NULL, NULL, inst, NULL);
1489
1490 {
1491 SHMENUBARINFO mbi;
1492 RECT rc, rcBar, rcTB, rcClient;
1493
1494 memset (&mbi, 0, sizeof(SHMENUBARINFO));
1495 mbi.cbSize = sizeof(SHMENUBARINFO);
1496 mbi.hwndParent = fe->hwnd;
1497 mbi.nToolBarId = IDR_MENUBAR1;
1498 mbi.hInstRes = inst;
1499
1500 SHCreateMenuBar(&mbi);
1501
1502 GetWindowRect(fe->hwnd, &rc);
1503 GetWindowRect(mbi.hwndMB, &rcBar);
1504 rc.bottom -= rcBar.bottom - rcBar.top;
1505 MoveWindow(fe->hwnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, FALSE);
1506
1507 if (thegame.flags & REQUIRE_NUMPAD)
1508 {
1509 fe->numpad = CreateToolbarEx (fe->hwnd,
1510 WS_VISIBLE | WS_CHILD | CCS_NOPARENTALIGN | TBSTYLE_FLAT,
1511 0, 10, inst, IDR_PADTOOLBAR,
1512 tbNumpadButtons, sizeof (tbNumpadButtons) / sizeof (TBBUTTON),
1513 0, 0, 14, 15, sizeof (TBBUTTON));
1514 GetWindowRect(fe->numpad, &rcTB);
1515 GetClientRect(fe->hwnd, &rcClient);
1516 MoveWindow(fe->numpad,
1517 0,
1518 rcClient.bottom - (rcTB.bottom - rcTB.top) - 1,
1519 rcClient.right,
1520 rcTB.bottom - rcTB.top,
1521 FALSE);
1522 SendMessage(fe->numpad, TB_SETINDENT, (rcClient.right - (10 * 21)) / 2, 0);
1523 }
1524 else
1525 fe->numpad = NULL;
1526 }
1527 #else
1528 fe->hwnd = CreateWindowEx(0, thegame.name, thegame.name,
1529 WS_OVERLAPPEDWINDOW &~
1530 (WS_MAXIMIZEBOX),
1531 CW_USEDEFAULT, CW_USEDEFAULT,
1532 r.right - r.left, r.bottom - r.top,
1533 NULL, NULL, inst, NULL);
1534 #endif
1535
1536 if (midend_wants_statusbar(fe->me)) {
1537 RECT sr;
1538 DestroyWindow(fe->statusbar);
1539 fe->statusbar = CreateWindowEx(0, STATUSCLASSNAME, TEXT("ooh"),
1540 WS_CHILD | WS_VISIBLE,
1541 0, 0, 0, 0, /* status bar does these */
1542 fe->hwnd, NULL, inst, NULL);
1543 #ifdef _WIN32_WCE
1544 /* Flat status bar looks better on the Pocket PC */
1545 SendMessage(fe->statusbar, SB_SIMPLE, (WPARAM) TRUE, 0);
1546 SendMessage(fe->statusbar, SB_SETTEXT,
1547 (WPARAM) 255 | SBT_NOBORDERS,
1548 (LPARAM) L"");
1549 #endif
1550
1551 /*
1552 * Now resize the window to take account of the status bar.
1553 */
1554 GetWindowRect(fe->statusbar, &sr);
1555 GetWindowRect(fe->hwnd, &r);
1556 #ifndef _WIN32_WCE
1557 SetWindowPos(fe->hwnd, NULL, 0, 0, r.right - r.left,
1558 r.bottom - r.top + sr.bottom - sr.top,
1559 SWP_NOMOVE | SWP_NOZORDER);
1560 #endif
1561 } else {
1562 fe->statusbar = NULL;
1563 }
1564
1565 {
1566 #ifndef _WIN32_WCE
1567 HMENU bar = CreateMenu();
1568 HMENU menu = CreateMenu();
1569 RECT menusize;
1570
1571 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, "&Game");
1572 #else
1573 HMENU menu = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_GAME);
1574 DeleteMenu(menu, 0, MF_BYPOSITION);
1575 #endif
1576 AppendMenu(menu, MF_ENABLED, IDM_NEW, TEXT("&New"));
1577 AppendMenu(menu, MF_ENABLED, IDM_RESTART, TEXT("&Restart"));
1578 #ifndef _WIN32_WCE
1579 /* ...here I run out of sensible accelerator characters. */
1580 AppendMenu(menu, MF_ENABLED, IDM_DESC, TEXT("Speci&fic..."));
1581 AppendMenu(menu, MF_ENABLED, IDM_SEED, TEXT("Rando&m Seed..."));
1582 #endif
1583
1584 if ((fe->npresets = midend_num_presets(fe->me)) > 0 ||
1585 thegame.can_configure) {
1586 int i;
1587 #ifndef _WIN32_WCE
1588 HMENU sub = CreateMenu();
1589
1590 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)sub, "&Type");
1591 #else
1592 HMENU sub = SHGetSubMenu(SHFindMenuBar(fe->hwnd), ID_TYPE);
1593 DeleteMenu(sub, 0, MF_BYPOSITION);
1594 #endif
1595 fe->presets = snewn(fe->npresets, game_params *);
1596
1597 for (i = 0; i < fe->npresets; i++) {
1598 char *name;
1599 #ifdef _WIN32_WCE
1600 TCHAR wName[255];
1601 #endif
1602
1603 midend_fetch_preset(fe->me, i, &name, &fe->presets[i]);
1604
1605 /*
1606 * FIXME: we ought to go through and do something
1607 * with ampersands here.
1608 */
1609
1610 #ifndef _WIN32_WCE
1611 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, name);
1612 #else
1613 MultiByteToWideChar (CP_ACP, 0, name, -1, wName, 255);
1614 AppendMenu(sub, MF_ENABLED, IDM_PRESETS + 0x10 * i, wName);
1615 #endif
1616 }
1617 if (thegame.can_configure) {
1618 AppendMenu(sub, MF_ENABLED, IDM_CONFIG, TEXT("&Custom..."));
1619 }
1620
1621 fe->typemenu = sub;
1622 } else
1623 fe->typemenu = INVALID_HANDLE_VALUE;
1624
1625 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1626 #ifndef _WIN32_WCE
1627 AppendMenu(menu, MF_ENABLED, IDM_LOAD, TEXT("&Load..."));
1628 AppendMenu(menu, MF_ENABLED, IDM_SAVE, TEXT("&Save..."));
1629 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1630 if (thegame.can_print) {
1631 AppendMenu(menu, MF_ENABLED, IDM_PRINT, TEXT("&Print..."));
1632 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1633 }
1634 #endif
1635 AppendMenu(menu, MF_ENABLED, IDM_UNDO, TEXT("Undo"));
1636 AppendMenu(menu, MF_ENABLED, IDM_REDO, TEXT("Redo"));
1637 #ifndef _WIN32_WCE
1638 if (thegame.can_format_as_text) {
1639 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1640 AppendMenu(menu, MF_ENABLED, IDM_COPY, TEXT("&Copy"));
1641 }
1642 #endif
1643 if (thegame.can_solve) {
1644 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1645 AppendMenu(menu, MF_ENABLED, IDM_SOLVE, TEXT("Sol&ve"));
1646 }
1647 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1648 #ifndef _WIN32_WCE
1649 AppendMenu(menu, MF_ENABLED, IDM_QUIT, TEXT("E&xit"));
1650 menu = CreateMenu();
1651 AppendMenu(bar, MF_ENABLED|MF_POPUP, (UINT)menu, TEXT("&Help"));
1652 #endif
1653 AppendMenu(menu, MF_ENABLED, IDM_ABOUT, TEXT("&About"));
1654 #ifndef _WIN32_WCE
1655 if (help_type != NONE) {
1656 AppendMenu(menu, MF_SEPARATOR, 0, 0);
1657 AppendMenu(menu, MF_ENABLED, IDM_HELPC, TEXT("&Contents"));
1658 if (help_topic) {
1659 char *item;
1660 assert(thegame.name);
1661 item = snewn(10+strlen(thegame.name), char); /*ick*/
1662 sprintf(item, "&Help on %s", thegame.name);
1663 AppendMenu(menu, MF_ENABLED, IDM_GAMEHELP, item);
1664 sfree(item);
1665 }
1666 }
1667 SetMenu(fe->hwnd, bar);
1668 get_menu_size(fe->hwnd, &menusize);
1669 fe->xmin = (menusize.right - menusize.left) + 25;
1670 #endif
1671 }
1672
1673 fe->bitmap = NULL;
1674 new_game_size(fe); /* initialises fe->bitmap */
1675 check_window_size(fe, &x, &y);
1676
1677 SetWindowLong(fe->hwnd, GWL_USERDATA, (LONG)fe);
1678
1679 ShowWindow(fe->hwnd, SW_SHOWNORMAL);
1680 SetForegroundWindow(fe->hwnd);
1681
1682 update_type_menu_tick(fe);
1683
1684 midend_redraw(fe->me);
1685
1686 return fe;
1687 }
1688
1689 #ifdef _WIN32_WCE
1690 static HFONT dialog_title_font()
1691 {
1692 static HFONT hf = NULL;
1693 LOGFONT lf;
1694
1695 if (hf)
1696 return hf;
1697
1698 memset (&lf, 0, sizeof(LOGFONT));
1699 lf.lfHeight = -11; /* - ((8 * GetDeviceCaps(hdc, LOGPIXELSY)) / 72) */
1700 lf.lfWeight = FW_BOLD;
1701 wcscpy(lf.lfFaceName, TEXT("Tahoma"));
1702
1703 return hf = CreateFontIndirect(&lf);
1704 }
1705
1706 static void make_dialog_full_screen(HWND hwnd)
1707 {
1708 SHINITDLGINFO shidi;
1709
1710 /* Make dialog full screen */
1711 shidi.dwMask = SHIDIM_FLAGS;
1712 shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIZEDLGFULLSCREEN |
1713 SHIDIF_EMPTYMENU;
1714 shidi.hDlg = hwnd;
1715 SHInitDialog(&shidi);
1716 }
1717 #endif
1718
1719 static int CALLBACK AboutDlgProc(HWND hwnd, UINT msg,
1720 WPARAM wParam, LPARAM lParam)
1721 {
1722 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1723
1724 switch (msg) {
1725 case WM_INITDIALOG:
1726 #ifdef _WIN32_WCE
1727 {
1728 char title[256];
1729
1730 make_dialog_full_screen(hwnd);
1731
1732 sprintf(title, "About %.250s", thegame.name);
1733 SetDlgItemTextA(hwnd, IDC_ABOUT_CAPTION, title);
1734
1735 SendDlgItemMessage(hwnd, IDC_ABOUT_CAPTION, WM_SETFONT,
1736 (WPARAM) dialog_title_font(), 0);
1737
1738 SetDlgItemTextA(hwnd, IDC_ABOUT_GAME, thegame.name);
1739 SetDlgItemTextA(hwnd, IDC_ABOUT_VERSION, ver);
1740 }
1741 #endif
1742 return TRUE;
1743
1744 case WM_COMMAND:
1745 if (LOWORD(wParam) == IDOK)
1746 #ifdef _WIN32_WCE
1747 EndDialog(hwnd, 1);
1748 #else
1749 fe->dlg_done = 1;
1750 #endif
1751 return 0;
1752
1753 case WM_CLOSE:
1754 #ifdef _WIN32_WCE
1755 EndDialog(hwnd, 1);
1756 #else
1757 fe->dlg_done = 1;
1758 #endif
1759 return 0;
1760 }
1761
1762 return 0;
1763 }
1764
1765 /*
1766 * Wrappers on midend_{get,set}_config, which extend the CFG_*
1767 * enumeration to add CFG_PRINT.
1768 */
1769 static config_item *frontend_get_config(frontend *fe, int which,
1770 char **wintitle)
1771 {
1772 if (which < CFG_FRONTEND_SPECIFIC) {
1773 return midend_get_config(fe->me, which, wintitle);
1774 } else if (which == CFG_PRINT) {
1775 config_item *ret;
1776 int i;
1777
1778 *wintitle = snewn(40 + strlen(thegame.name), char);
1779 sprintf(*wintitle, "%s print setup", thegame.name);
1780
1781 ret = snewn(8, config_item);
1782
1783 i = 0;
1784
1785 ret[i].name = "Number of puzzles to print";
1786 ret[i].type = C_STRING;
1787 ret[i].sval = dupstr("1");
1788 ret[i].ival = 0;
1789 i++;
1790
1791 ret[i].name = "Number of puzzles across the page";
1792 ret[i].type = C_STRING;
1793 ret[i].sval = dupstr("1");
1794 ret[i].ival = 0;
1795 i++;
1796
1797 ret[i].name = "Number of puzzles down the page";
1798 ret[i].type = C_STRING;
1799 ret[i].sval = dupstr("1");
1800 ret[i].ival = 0;
1801 i++;
1802
1803 ret[i].name = "Percentage of standard size";
1804 ret[i].type = C_STRING;
1805 ret[i].sval = dupstr("100.0");
1806 ret[i].ival = 0;
1807 i++;
1808
1809 ret[i].name = "Include currently shown puzzle";
1810 ret[i].type = C_BOOLEAN;
1811 ret[i].sval = NULL;
1812 ret[i].ival = TRUE;
1813 i++;
1814
1815 ret[i].name = "Print solutions";
1816 ret[i].type = C_BOOLEAN;
1817 ret[i].sval = NULL;
1818 ret[i].ival = FALSE;
1819 i++;
1820
1821 if (thegame.can_print_in_colour) {
1822 ret[i].name = "Print in colour";
1823 ret[i].type = C_BOOLEAN;
1824 ret[i].sval = NULL;
1825 ret[i].ival = FALSE;
1826 i++;
1827 }
1828
1829 ret[i].name = NULL;
1830 ret[i].type = C_END;
1831 ret[i].sval = NULL;
1832 ret[i].ival = 0;
1833 i++;
1834
1835 return ret;
1836 } else {
1837 assert(!"We should never get here");
1838 return NULL;
1839 }
1840 }
1841
1842 static char *frontend_set_config(frontend *fe, int which, config_item *cfg)
1843 {
1844 if (which < CFG_FRONTEND_SPECIFIC) {
1845 return midend_set_config(fe->me, which, cfg);
1846 } else if (which == CFG_PRINT) {
1847 if ((fe->printcount = atoi(cfg[0].sval)) <= 0)
1848 return "Number of puzzles to print should be at least one";
1849 if ((fe->printw = atoi(cfg[1].sval)) <= 0)
1850 return "Number of puzzles across the page should be at least one";
1851 if ((fe->printh = atoi(cfg[2].sval)) <= 0)
1852 return "Number of puzzles down the page should be at least one";
1853 if ((fe->printscale = (float)atof(cfg[3].sval)) <= 0)
1854 return "Print size should be positive";
1855 fe->printcurr = cfg[4].ival;
1856 fe->printsolns = cfg[5].ival;
1857 fe->printcolour = thegame.can_print_in_colour && cfg[6].ival;
1858 return NULL;
1859 } else {
1860 assert(!"We should never get here");
1861 return "Internal error";
1862 }
1863 }
1864
1865 #ifdef _WIN32_WCE
1866 /* Separate version of mkctrl function for the Pocket PC. */
1867 /* Control coordinates should be specified in dialog units. */
1868 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
1869 LPCTSTR wclass, int wstyle,
1870 int exstyle, const char *wtext, int wid)
1871 {
1872 RECT rc;
1873 TCHAR wwtext[256];
1874
1875 /* Convert dialog units into pixels */
1876 rc.left = x1; rc.right = x2;
1877 rc.top = y1; rc.bottom = y2;
1878 MapDialogRect(fe->cfgbox, &rc);
1879
1880 MultiByteToWideChar (CP_ACP, 0, wtext, -1, wwtext, 256);
1881
1882 return CreateWindowEx(exstyle, wclass, wwtext,
1883 wstyle | WS_CHILD | WS_VISIBLE,
1884 rc.left, rc.top,
1885 rc.right - rc.left, rc.bottom - rc.top,
1886 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
1887 }
1888
1889 static void create_config_controls(frontend * fe)
1890 {
1891 int id, nctrls;
1892 int col1l, col1r, col2l, col2r, y;
1893 config_item *i;
1894 struct cfg_aux *j;
1895 HWND ctl;
1896
1897 /* Control placement done in dialog units */
1898 col1l = 4; col1r = 96; /* Label column */
1899 col2l = 100; col2r = 154; /* Input column (edit boxes and combo boxes) */
1900
1901 /*
1902 * Count the controls so we can allocate cfgaux.
1903 */
1904 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
1905 nctrls++;
1906 fe->cfgaux = snewn(nctrls, struct cfg_aux);
1907
1908 id = 1000;
1909 y = 22; /* Leave some room for the dialog title */
1910 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
1911 switch (i->type) {
1912 case C_STRING:
1913 /*
1914 * Edit box with a label beside it.
1915 */
1916 mkctrl(fe, col1l, col1r, y + 1, y + 11,
1917 TEXT("Static"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
1918 mkctrl(fe, col2l, col2r, y, y + 12,
1919 TEXT("EDIT"), WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
1920 0, "", (j->ctlid = id++));
1921 SetDlgItemTextA(fe->cfgbox, j->ctlid, i->sval);
1922 break;
1923
1924 case C_BOOLEAN:
1925 /*
1926 * Simple checkbox.
1927 */
1928 mkctrl(fe, col1l, col2r, y + 1, y + 11, TEXT("BUTTON"),
1929 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
1930 0, i->name, (j->ctlid = id++));
1931 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
1932 break;
1933
1934 case C_CHOICES:
1935 /*
1936 * Drop-down list with a label beside it.
1937 */
1938 mkctrl(fe, col1l, col1r, y + 1, y + 11,
1939 TEXT("STATIC"), SS_LEFTNOWORDWRAP, 0, i->name, id++);
1940 ctl = mkctrl(fe, col2l, col2r, y, y + 48,
1941 TEXT("COMBOBOX"), WS_BORDER | WS_TABSTOP |
1942 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
1943 0, "", (j->ctlid = id++));
1944 {
1945 char c, *p, *q, *str;
1946
1947 p = i->sval;
1948 c = *p++;
1949 while (*p) {
1950 q = p;
1951 while (*q && *q != c) q++;
1952 str = snewn(q-p+1, char);
1953 strncpy(str, p, q-p);
1954 str[q-p] = '\0';
1955 {
1956 TCHAR ws[50];
1957 MultiByteToWideChar (CP_ACP, 0, str, -1, ws, 50);
1958 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)ws);
1959 }
1960
1961 sfree(str);
1962 if (*q) q++;
1963 p = q;
1964 }
1965 }
1966 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
1967 break;
1968 }
1969
1970 y += 15;
1971 }
1972
1973 }
1974 #endif
1975
1976 static int CALLBACK ConfigDlgProc(HWND hwnd, UINT msg,
1977 WPARAM wParam, LPARAM lParam)
1978 {
1979 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
1980 config_item *i;
1981 struct cfg_aux *j;
1982
1983 switch (msg) {
1984 case WM_INITDIALOG:
1985 #ifdef _WIN32_WCE
1986 {
1987 char *title;
1988
1989 fe = (frontend *) lParam;
1990 SetWindowLong(hwnd, GWL_USERDATA, lParam);
1991 fe->cfgbox = hwnd;
1992
1993 fe->cfg = frontend_get_config(fe, fe->cfg_which, &title);
1994
1995 make_dialog_full_screen(hwnd);
1996
1997 SetDlgItemTextA(hwnd, IDC_CONFIG_CAPTION, title);
1998 SendDlgItemMessage(hwnd, IDC_CONFIG_CAPTION, WM_SETFONT,
1999 (WPARAM) dialog_title_font(), 0);
2000
2001 create_config_controls(fe);
2002 }
2003 #endif
2004 return TRUE;
2005
2006 case WM_COMMAND:
2007 /*
2008 * OK and Cancel are special cases.
2009 */
2010 if ((LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)) {
2011 if (LOWORD(wParam) == IDOK) {
2012 char *err = frontend_set_config(fe, fe->cfg_which, fe->cfg);
2013
2014 if (err) {
2015 MessageBox(hwnd, err, "Validation error",
2016 MB_ICONERROR | MB_OK);
2017 } else {
2018 #ifdef _WIN32_WCE
2019 EndDialog(hwnd, 2);
2020 #else
2021 fe->dlg_done = 2;
2022 #endif
2023 }
2024 } else {
2025 #ifdef _WIN32_WCE
2026 EndDialog(hwnd, 1);
2027 #else
2028 fe->dlg_done = 1;
2029 #endif
2030 }
2031 return 0;
2032 }
2033
2034 /*
2035 * First find the control whose id this is.
2036 */
2037 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2038 if (j->ctlid == LOWORD(wParam))
2039 break;
2040 }
2041 if (i->type == C_END)
2042 return 0; /* not our problem */
2043
2044 if (i->type == C_STRING && HIWORD(wParam) == EN_CHANGE) {
2045 char buffer[4096];
2046 #ifdef _WIN32_WCE
2047 TCHAR wBuffer[4096];
2048 GetDlgItemText(fe->cfgbox, j->ctlid, wBuffer, 4096);
2049 WideCharToMultiByte(CP_ACP, 0, wBuffer, -1, buffer, 4096, NULL, NULL);
2050 #else
2051 GetDlgItemText(fe->cfgbox, j->ctlid, buffer, lenof(buffer));
2052 #endif
2053 buffer[lenof(buffer)-1] = '\0';
2054 sfree(i->sval);
2055 i->sval = dupstr(buffer);
2056 } else if (i->type == C_BOOLEAN &&
2057 (HIWORD(wParam) == BN_CLICKED ||
2058 HIWORD(wParam) == BN_DBLCLK)) {
2059 i->ival = IsDlgButtonChecked(fe->cfgbox, j->ctlid);
2060 } else if (i->type == C_CHOICES &&
2061 HIWORD(wParam) == CBN_SELCHANGE) {
2062 i->ival = SendDlgItemMessage(fe->cfgbox, j->ctlid,
2063 CB_GETCURSEL, 0, 0);
2064 }
2065
2066 return 0;
2067
2068 case WM_CLOSE:
2069 fe->dlg_done = 1;
2070 return 0;
2071 }
2072
2073 return 0;
2074 }
2075
2076 #ifndef _WIN32_WCE
2077 HWND mkctrl(frontend *fe, int x1, int x2, int y1, int y2,
2078 char *wclass, int wstyle,
2079 int exstyle, const char *wtext, int wid)
2080 {
2081 HWND ret;
2082 ret = CreateWindowEx(exstyle, wclass, wtext,
2083 wstyle | WS_CHILD | WS_VISIBLE, x1, y1, x2-x1, y2-y1,
2084 fe->cfgbox, (HMENU) wid, fe->inst, NULL);
2085 SendMessage(ret, WM_SETFONT, (WPARAM)fe->cfgfont, MAKELPARAM(TRUE, 0));
2086 return ret;
2087 }
2088 #endif
2089
2090 static void about(frontend *fe)
2091 {
2092 #ifdef _WIN32_WCE
2093 DialogBox(fe->inst, MAKEINTRESOURCE(IDD_ABOUT), fe->hwnd, AboutDlgProc);
2094 #else
2095 int i;
2096 WNDCLASS wc;
2097 MSG msg;
2098 TEXTMETRIC tm;
2099 HDC hdc;
2100 HFONT oldfont;
2101 SIZE size;
2102 int gm, id;
2103 int winwidth, winheight, y;
2104 int height, width, maxwid;
2105 const char *strings[16];
2106 int lengths[16];
2107 int nstrings = 0;
2108 char titlebuf[512];
2109
2110 sprintf(titlebuf, "About %.250s", thegame.name);
2111
2112 strings[nstrings++] = thegame.name;
2113 strings[nstrings++] = "from Simon Tatham's Portable Puzzle Collection";
2114 strings[nstrings++] = ver;
2115
2116 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2117 wc.lpfnWndProc = DefDlgProc;
2118 wc.cbClsExtra = 0;
2119 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2120 wc.hInstance = fe->inst;
2121 wc.hIcon = NULL;
2122 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2123 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2124 wc.lpszMenuName = NULL;
2125 wc.lpszClassName = "GameAboutBox";
2126 RegisterClass(&wc);
2127
2128 hdc = GetDC(fe->hwnd);
2129 SetMapMode(hdc, MM_TEXT);
2130
2131 fe->dlg_done = FALSE;
2132
2133 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2134 0, 0, 0, 0,
2135 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2136 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2137 DEFAULT_QUALITY,
2138 FF_SWISS,
2139 "MS Shell Dlg");
2140
2141 oldfont = SelectObject(hdc, fe->cfgfont);
2142 if (GetTextMetrics(hdc, &tm)) {
2143 height = tm.tmAscent + tm.tmDescent;
2144 width = tm.tmAveCharWidth;
2145 } else {
2146 height = width = 30;
2147 }
2148
2149 /*
2150 * Figure out the layout of the About box by measuring the
2151 * length of each piece of text.
2152 */
2153 maxwid = 0;
2154 winheight = height/2;
2155
2156 for (i = 0; i < nstrings; i++) {
2157 if (GetTextExtentPoint32(hdc, strings[i], strlen(strings[i]), &size))
2158 lengths[i] = size.cx;
2159 else
2160 lengths[i] = 0; /* *shrug* */
2161 if (maxwid < lengths[i])
2162 maxwid = lengths[i];
2163 winheight += height * 3 / 2 + (height / 2);
2164 }
2165
2166 winheight += height + height * 7 / 4; /* OK button */
2167 winwidth = maxwid + 4*width;
2168
2169 SelectObject(hdc, oldfont);
2170 ReleaseDC(fe->hwnd, hdc);
2171
2172 /*
2173 * Create the dialog, now that we know its size.
2174 */
2175 {
2176 RECT r, r2;
2177
2178 r.left = r.top = 0;
2179 r.right = winwidth;
2180 r.bottom = winheight;
2181
2182 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2183 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2184 WS_CAPTION | WS_SYSMENU*/) &~
2185 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2186 FALSE, 0);
2187
2188 /*
2189 * Centre the dialog on its parent window.
2190 */
2191 r.right -= r.left;
2192 r.bottom -= r.top;
2193 GetWindowRect(fe->hwnd, &r2);
2194 r.left = (r2.left + r2.right - r.right) / 2;
2195 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2196 r.right += r.left;
2197 r.bottom += r.top;
2198
2199 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, titlebuf,
2200 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2201 WS_CAPTION | WS_SYSMENU,
2202 r.left, r.top,
2203 r.right-r.left, r.bottom-r.top,
2204 fe->hwnd, NULL, fe->inst, NULL);
2205 }
2206
2207 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2208
2209 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2210 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)AboutDlgProc);
2211
2212 id = 1000;
2213 y = height/2;
2214 for (i = 0; i < nstrings; i++) {
2215 int border = width*2 + (maxwid - lengths[i]) / 2;
2216 mkctrl(fe, border, border+lengths[i], y+height*1/8, y+height*9/8,
2217 "Static", 0, 0, strings[i], id++);
2218 y += height*3/2;
2219
2220 assert(y < winheight);
2221 y += height/2;
2222 }
2223
2224 y += height/2; /* extra space before OK */
2225 mkctrl(fe, width*2, maxwid+width*2, y, y+height*7/4, "BUTTON",
2226 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2227 "OK", IDOK);
2228
2229 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2230
2231 EnableWindow(fe->hwnd, FALSE);
2232 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2233 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2234 if (!IsDialogMessage(fe->cfgbox, &msg))
2235 DispatchMessage(&msg);
2236 if (fe->dlg_done)
2237 break;
2238 }
2239 EnableWindow(fe->hwnd, TRUE);
2240 SetForegroundWindow(fe->hwnd);
2241 DestroyWindow(fe->cfgbox);
2242 DeleteObject(fe->cfgfont);
2243 #endif
2244 }
2245
2246 static int get_config(frontend *fe, int which)
2247 {
2248 #ifdef _WIN32_WCE
2249 fe->cfg_which = which;
2250
2251 return DialogBoxParam(fe->inst,
2252 MAKEINTRESOURCE(IDD_CONFIG),
2253 fe->hwnd, ConfigDlgProc,
2254 (LPARAM) fe) == 2;
2255 #else
2256 config_item *i;
2257 struct cfg_aux *j;
2258 char *title;
2259 WNDCLASS wc;
2260 MSG msg;
2261 TEXTMETRIC tm;
2262 HDC hdc;
2263 HFONT oldfont;
2264 SIZE size;
2265 HWND ctl;
2266 int gm, id, nctrls;
2267 int winwidth, winheight, col1l, col1r, col2l, col2r, y;
2268 int height, width, maxlabel, maxcheckbox;
2269
2270 wc.style = CS_DBLCLKS | CS_SAVEBITS;
2271 wc.lpfnWndProc = DefDlgProc;
2272 wc.cbClsExtra = 0;
2273 wc.cbWndExtra = DLGWINDOWEXTRA + 8;
2274 wc.hInstance = fe->inst;
2275 wc.hIcon = NULL;
2276 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2277 wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
2278 wc.lpszMenuName = NULL;
2279 wc.lpszClassName = "GameConfigBox";
2280 RegisterClass(&wc);
2281
2282 hdc = GetDC(fe->hwnd);
2283 SetMapMode(hdc, MM_TEXT);
2284
2285 fe->dlg_done = FALSE;
2286
2287 fe->cfgfont = CreateFont(-MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72),
2288 0, 0, 0, 0,
2289 FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2290 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2291 DEFAULT_QUALITY,
2292 FF_SWISS,
2293 "MS Shell Dlg");
2294
2295 oldfont = SelectObject(hdc, fe->cfgfont);
2296 if (GetTextMetrics(hdc, &tm)) {
2297 height = tm.tmAscent + tm.tmDescent;
2298 width = tm.tmAveCharWidth;
2299 } else {
2300 height = width = 30;
2301 }
2302
2303 fe->cfg = frontend_get_config(fe, which, &title);
2304 fe->cfg_which = which;
2305
2306 /*
2307 * Figure out the layout of the config box by measuring the
2308 * length of each piece of text.
2309 */
2310 maxlabel = maxcheckbox = 0;
2311 winheight = height/2;
2312
2313 for (i = fe->cfg; i->type != C_END; i++) {
2314 switch (i->type) {
2315 case C_STRING:
2316 case C_CHOICES:
2317 /*
2318 * Both these control types have a label filling only
2319 * the left-hand column of the box.
2320 */
2321 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2322 maxlabel < size.cx)
2323 maxlabel = size.cx;
2324 winheight += height * 3 / 2 + (height / 2);
2325 break;
2326
2327 case C_BOOLEAN:
2328 /*
2329 * Checkboxes take up the whole of the box width.
2330 */
2331 if (GetTextExtentPoint32(hdc, i->name, strlen(i->name), &size) &&
2332 maxcheckbox < size.cx)
2333 maxcheckbox = size.cx;
2334 winheight += height + (height / 2);
2335 break;
2336 }
2337 }
2338
2339 winheight += height + height * 7 / 4; /* OK / Cancel buttons */
2340
2341 col1l = 2*width;
2342 col1r = col1l + maxlabel;
2343 col2l = col1r + 2*width;
2344 col2r = col2l + 30*width;
2345 if (col2r < col1l+2*height+maxcheckbox)
2346 col2r = col1l+2*height+maxcheckbox;
2347 winwidth = col2r + 2*width;
2348
2349 SelectObject(hdc, oldfont);
2350 ReleaseDC(fe->hwnd, hdc);
2351
2352 /*
2353 * Create the dialog, now that we know its size.
2354 */
2355 {
2356 RECT r, r2;
2357
2358 r.left = r.top = 0;
2359 r.right = winwidth;
2360 r.bottom = winheight;
2361
2362 AdjustWindowRectEx(&r, (WS_OVERLAPPEDWINDOW /*|
2363 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2364 WS_CAPTION | WS_SYSMENU*/) &~
2365 (WS_MAXIMIZEBOX | WS_OVERLAPPED),
2366 FALSE, 0);
2367
2368 /*
2369 * Centre the dialog on its parent window.
2370 */
2371 r.right -= r.left;
2372 r.bottom -= r.top;
2373 GetWindowRect(fe->hwnd, &r2);
2374 r.left = (r2.left + r2.right - r.right) / 2;
2375 r.top = (r2.top + r2.bottom - r.bottom) / 2;
2376 r.right += r.left;
2377 r.bottom += r.top;
2378
2379 fe->cfgbox = CreateWindowEx(0, wc.lpszClassName, title,
2380 DS_MODALFRAME | WS_POPUP | WS_VISIBLE |
2381 WS_CAPTION | WS_SYSMENU,
2382 r.left, r.top,
2383 r.right-r.left, r.bottom-r.top,
2384 fe->hwnd, NULL, fe->inst, NULL);
2385 sfree(title);
2386 }
2387
2388 SendMessage(fe->cfgbox, WM_SETFONT, (WPARAM)fe->cfgfont, FALSE);
2389
2390 SetWindowLong(fe->cfgbox, GWL_USERDATA, (LONG)fe);
2391 SetWindowLong(fe->cfgbox, DWL_DLGPROC, (LONG)ConfigDlgProc);
2392
2393 /*
2394 * Count the controls so we can allocate cfgaux.
2395 */
2396 for (nctrls = 0, i = fe->cfg; i->type != C_END; i++)
2397 nctrls++;
2398 fe->cfgaux = snewn(nctrls, struct cfg_aux);
2399
2400 id = 1000;
2401 y = height/2;
2402 for (i = fe->cfg, j = fe->cfgaux; i->type != C_END; i++, j++) {
2403 switch (i->type) {
2404 case C_STRING:
2405 /*
2406 * Edit box with a label beside it.
2407 */
2408 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2409 "Static", 0, 0, i->name, id++);
2410 ctl = mkctrl(fe, col2l, col2r, y, y+height*3/2,
2411 "EDIT", WS_TABSTOP | ES_AUTOHSCROLL,
2412 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2413 SetWindowText(ctl, i->sval);
2414 y += height*3/2;
2415 break;
2416
2417 case C_BOOLEAN:
2418 /*
2419 * Simple checkbox.
2420 */
2421 mkctrl(fe, col1l, col2r, y, y+height, "BUTTON",
2422 BS_NOTIFY | BS_AUTOCHECKBOX | WS_TABSTOP,
2423 0, i->name, (j->ctlid = id++));
2424 CheckDlgButton(fe->cfgbox, j->ctlid, (i->ival != 0));
2425 y += height;
2426 break;
2427
2428 case C_CHOICES:
2429 /*
2430 * Drop-down list with a label beside it.
2431 */
2432 mkctrl(fe, col1l, col1r, y+height*1/8, y+height*9/8,
2433 "STATIC", 0, 0, i->name, id++);
2434 ctl = mkctrl(fe, col2l, col2r, y, y+height*41/2,
2435 "COMBOBOX", WS_TABSTOP |
2436 CBS_DROPDOWNLIST | CBS_HASSTRINGS,
2437 WS_EX_CLIENTEDGE, "", (j->ctlid = id++));
2438 {
2439 char c, *p, *q, *str;
2440
2441 SendMessage(ctl, CB_RESETCONTENT, 0, 0);
2442 p = i->sval;
2443 c = *p++;
2444 while (*p) {
2445 q = p;
2446 while (*q && *q != c) q++;
2447 str = snewn(q-p+1, char);
2448 strncpy(str, p, q-p);
2449 str[q-p] = '\0';
2450 SendMessage(ctl, CB_ADDSTRING, 0, (LPARAM)str);
2451 sfree(str);
2452 if (*q) q++;
2453 p = q;
2454 }
2455 }
2456
2457 SendMessage(ctl, CB_SETCURSEL, i->ival, 0);
2458
2459 y += height*3/2;
2460 break;
2461 }
2462
2463 assert(y < winheight);
2464 y += height/2;
2465 }
2466
2467 y += height/2; /* extra space before OK and Cancel */
2468 mkctrl(fe, col1l, (col1l+col2r)/2-width, y, y+height*7/4, "BUTTON",
2469 BS_PUSHBUTTON | WS_TABSTOP | BS_DEFPUSHBUTTON, 0,
2470 "OK", IDOK);
2471 mkctrl(fe, (col1l+col2r)/2+width, col2r, y, y+height*7/4, "BUTTON",
2472 BS_PUSHBUTTON | WS_TABSTOP, 0, "Cancel", IDCANCEL);
2473
2474 SendMessage(fe->cfgbox, WM_INITDIALOG, 0, 0);
2475
2476 EnableWindow(fe->hwnd, FALSE);
2477 ShowWindow(fe->cfgbox, SW_SHOWNORMAL);
2478 while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) {
2479 if (!IsDialogMessage(fe->cfgbox, &msg))
2480 DispatchMessage(&msg);
2481 if (fe->dlg_done)
2482 break;
2483 }
2484 EnableWindow(fe->hwnd, TRUE);
2485 SetForegroundWindow(fe->hwnd);
2486 DestroyWindow(fe->cfgbox);
2487 DeleteObject(fe->cfgfont);
2488
2489 free_cfg(fe->cfg);
2490 sfree(fe->cfgaux);
2491
2492 return (fe->dlg_done == 2);
2493 #endif
2494 }
2495
2496 #ifdef _WIN32_WCE
2497 static void calculate_bitmap_position(frontend *fe, int x, int y)
2498 {
2499 /* Pocket PC - center the game in the full screen window */
2500 int yMargin;
2501 RECT rcClient;
2502
2503 GetClientRect(fe->hwnd, &rcClient);
2504 fe->bitmapPosition.left = (rcClient.right - x) / 2;
2505 yMargin = rcClient.bottom - y;
2506
2507 if (fe->numpad != NULL) {
2508 RECT rcPad;
2509 GetWindowRect(fe->numpad, &rcPad);
2510 yMargin -= rcPad.bottom - rcPad.top;
2511 }
2512
2513 if (fe->statusbar != NULL) {
2514 RECT rcStatus;
2515 GetWindowRect(fe->statusbar, &rcStatus);
2516 yMargin -= rcStatus.bottom - rcStatus.top;
2517 }
2518
2519 fe->bitmapPosition.top = yMargin / 2;
2520
2521 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2522 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2523 }
2524 #else
2525 static void calculate_bitmap_position(frontend *fe, int x, int y)
2526 {
2527 /* Plain Windows - position the game in the upper-left corner */
2528 fe->bitmapPosition.left = 0;
2529 fe->bitmapPosition.top = 0;
2530 fe->bitmapPosition.right = fe->bitmapPosition.left + x;
2531 fe->bitmapPosition.bottom = fe->bitmapPosition.top + y;
2532 }
2533 #endif
2534
2535 static void new_bitmap(frontend *fe, int x, int y)
2536 {
2537 HDC hdc;
2538
2539 if (fe->bitmap) DeleteObject(fe->bitmap);
2540
2541 hdc = GetDC(fe->hwnd);
2542 fe->bitmap = CreateCompatibleBitmap(hdc, x, y);
2543 calculate_bitmap_position(fe, x, y);
2544 ReleaseDC(fe->hwnd, hdc);
2545 }
2546
2547 static void new_game_size(frontend *fe)
2548 {
2549 RECT r, sr;
2550 int x, y;
2551
2552 get_max_puzzle_size(fe, &x, &y);
2553 midend_size(fe->me, &x, &y, FALSE);
2554 fe->ymin = (fe->xmin * y) / x;
2555
2556 r.left = r.top = 0;
2557 r.right = x;
2558 r.bottom = y;
2559 AdjustWindowRectEx(&r, WINFLAGS, TRUE, 0);
2560
2561 if (fe->statusbar != NULL) {
2562 GetWindowRect(fe->statusbar, &sr);
2563 } else {
2564 sr.left = sr.right = sr.top = sr.bottom = 0;
2565 }
2566 #ifndef _WIN32_WCE
2567 SetWindowPos(fe->hwnd, NULL, 0, 0,
2568 r.right - r.left,
2569 r.bottom - r.top + sr.bottom - sr.top,
2570 SWP_NOMOVE | SWP_NOZORDER);
2571 #endif
2572
2573 check_window_size(fe, &x, &y);
2574
2575 #ifndef _WIN32_WCE
2576 if (fe->statusbar != NULL)
2577 SetWindowPos(fe->statusbar, NULL, 0, y, x,
2578 sr.bottom - sr.top, SWP_NOZORDER);
2579 #endif
2580
2581 new_bitmap(fe, x, y);
2582
2583 #ifdef _WIN32_WCE
2584 InvalidateRect(fe->hwnd, NULL, TRUE);
2585 #endif
2586 midend_redraw(fe->me);
2587 }
2588
2589 /*
2590 * Given a proposed new window rect, work out the resulting
2591 * difference in client size (from current), and use to try
2592 * and resize the puzzle, returning (wx,wy) as the actual
2593 * new window size.
2594 */
2595
2596 static void adjust_game_size(frontend *fe, RECT *proposed, int isedge,
2597 int *wx_r, int *wy_r)
2598 {
2599 RECT cr, wr;
2600 int nx, ny, xdiff, ydiff, wx, wy;
2601
2602 /* Work out the current window sizing, and thus the
2603 * difference in size we're asking for. */
2604 GetClientRect(fe->hwnd, &cr);
2605 wr = cr;
2606 AdjustWindowRectEx(&wr, WINFLAGS, TRUE, 0);
2607
2608 xdiff = (proposed->right - proposed->left) - (wr.right - wr.left);
2609 ydiff = (proposed->bottom - proposed->top) - (wr.bottom - wr.top);
2610
2611 if (isedge) {
2612 /* These next four lines work around the fact that midend_size
2613 * is happy to shrink _but not grow_ if you change one dimension
2614 * but not the other. */
2615 if (xdiff > 0 && ydiff == 0)
2616 ydiff = (xdiff * (wr.right - wr.left)) / (wr.bottom - wr.top);
2617 if (xdiff == 0 && ydiff > 0)
2618 xdiff = (ydiff * (wr.bottom - wr.top)) / (wr.right - wr.left);
2619 }
2620
2621 if (check_window_resize(fe,
2622 (cr.right - cr.left) + xdiff,
2623 (cr.bottom - cr.top) + ydiff,
2624 &nx, &ny, &wx, &wy, TRUE)) {
2625 new_bitmap(fe, nx, ny);
2626 midend_force_redraw(fe->me);
2627 } else {
2628 /* reset size to current window size */
2629 wx = wr.right - wr.left;
2630 wy = wr.bottom - wr.top;
2631 }
2632 /* Re-fetch rectangle; size limits mean we might not have
2633 * taken it quite to the mouse drag positions. */
2634 GetClientRect(fe->hwnd, &cr);
2635 adjust_statusbar(fe, &cr);
2636
2637 *wx_r = wx; *wy_r = wy;
2638 }
2639
2640 static void update_type_menu_tick(frontend *fe)
2641 {
2642 int total, n, i;
2643
2644 if (fe->typemenu == INVALID_HANDLE_VALUE)
2645 return;
2646
2647 total = GetMenuItemCount(fe->typemenu);
2648 n = midend_which_preset(fe->me);
2649 if (n < 0)
2650 n = total - 1; /* "Custom" item */
2651
2652 for (i = 0; i < total; i++) {
2653 int flag = (i == n ? MF_CHECKED : MF_UNCHECKED);
2654 CheckMenuItem(fe->typemenu, i, MF_BYPOSITION | flag);
2655 }
2656
2657 DrawMenuBar(fe->hwnd);
2658 }
2659
2660 static void new_game_type(frontend *fe)
2661 {
2662 midend_new_game(fe->me);
2663 new_game_size(fe);
2664 update_type_menu_tick(fe);
2665 }
2666
2667 static int is_alt_pressed(void)
2668 {
2669 BYTE keystate[256];
2670 int r = GetKeyboardState(keystate);
2671 if (!r)
2672 return FALSE;
2673 if (keystate[VK_MENU] & 0x80)
2674 return TRUE;
2675 if (keystate[VK_RMENU] & 0x80)
2676 return TRUE;
2677 return FALSE;
2678 }
2679
2680 static void savefile_write(void *wctx, void *buf, int len)
2681 {
2682 FILE *fp = (FILE *)wctx;
2683 fwrite(buf, 1, len, fp);
2684 }
2685
2686 static int savefile_read(void *wctx, void *buf, int len)
2687 {
2688 FILE *fp = (FILE *)wctx;
2689 int ret;
2690
2691 ret = fread(buf, 1, len, fp);
2692 return (ret == len);
2693 }
2694
2695 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2696 WPARAM wParam, LPARAM lParam)
2697 {
2698 frontend *fe = (frontend *)GetWindowLong(hwnd, GWL_USERDATA);
2699 int cmd;
2700
2701 switch (message) {
2702 case WM_CLOSE:
2703 DestroyWindow(hwnd);
2704 return 0;
2705 case WM_COMMAND:
2706 #ifdef _WIN32_WCE
2707 /* Numeric pad sends WM_COMMAND messages */
2708 if ((wParam >= IDM_KEYEMUL) && (wParam < IDM_KEYEMUL + 256))
2709 {
2710 midend_process_key(fe->me, 0, 0, wParam - IDM_KEYEMUL);
2711 }
2712 #endif
2713 cmd = wParam & ~0xF; /* low 4 bits reserved to Windows */
2714 switch (cmd) {
2715 case IDM_NEW:
2716 if (!midend_process_key(fe->me, 0, 0, 'n'))
2717 PostQuitMessage(0);
2718 break;
2719 case IDM_RESTART:
2720 midend_restart_game(fe->me);
2721 break;
2722 case IDM_UNDO:
2723 if (!midend_process_key(fe->me, 0, 0, 'u'))
2724 PostQuitMessage(0);
2725 break;
2726 case IDM_REDO:
2727 if (!midend_process_key(fe->me, 0, 0, '\x12'))
2728 PostQuitMessage(0);
2729 break;
2730 case IDM_COPY:
2731 {
2732 char *text = midend_text_format(fe->me);
2733 if (text)
2734 write_clip(hwnd, text);
2735 else
2736 MessageBeep(MB_ICONWARNING);
2737 sfree(text);
2738 }
2739 break;
2740 case IDM_SOLVE:
2741 {
2742 char *msg = midend_solve(fe->me);
2743 if (msg)
2744 MessageBox(hwnd, msg, "Unable to solve",
2745 MB_ICONERROR | MB_OK);
2746 }
2747 break;
2748 case IDM_QUIT:
2749 if (!midend_process_key(fe->me, 0, 0, 'q'))
2750 PostQuitMessage(0);
2751 break;
2752 case IDM_CONFIG:
2753 if (get_config(fe, CFG_SETTINGS))
2754 new_game_type(fe);
2755 break;
2756 case IDM_SEED:
2757 if (get_config(fe, CFG_SEED))
2758 new_game_type(fe);
2759 break;
2760 case IDM_DESC:
2761 if (get_config(fe, CFG_DESC))
2762 new_game_type(fe);
2763 break;
2764 case IDM_PRINT:
2765 if (get_config(fe, CFG_PRINT))
2766 print(fe);
2767 break;
2768 case IDM_ABOUT:
2769 about(fe);
2770 break;
2771 case IDM_LOAD:
2772 case IDM_SAVE:
2773 {
2774 OPENFILENAME of;
2775 char filename[FILENAME_MAX];
2776 int ret;
2777
2778 memset(&of, 0, sizeof(of));
2779 of.hwndOwner = hwnd;
2780 of.lpstrFilter = "All Files (*.*)\0*\0\0\0";
2781 of.lpstrCustomFilter = NULL;
2782 of.nFilterIndex = 1;
2783 of.lpstrFile = filename;
2784 filename[0] = '\0';
2785 of.nMaxFile = lenof(filename);
2786 of.lpstrFileTitle = NULL;
2787 of.lpstrTitle = (cmd == IDM_SAVE ?
2788 "Enter name of game file to save" :
2789 "Enter name of saved game file to load");
2790 of.Flags = 0;
2791 #ifdef OPENFILENAME_SIZE_VERSION_400
2792 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
2793 #else
2794 of.lStructSize = sizeof(of);
2795 #endif
2796 of.lpstrInitialDir = NULL;
2797
2798 if (cmd == IDM_SAVE)
2799 ret = GetSaveFileName(&of);
2800 else
2801 ret = GetOpenFileName(&of);
2802
2803 if (ret) {
2804 if (cmd == IDM_SAVE) {
2805 FILE *fp;
2806
2807 if ((fp = fopen(filename, "r")) != NULL) {
2808 char buf[256 + FILENAME_MAX];
2809 fclose(fp);
2810 /* file exists */
2811
2812 sprintf(buf, "Are you sure you want to overwrite"
2813 " the file \"%.*s\"?",
2814 FILENAME_MAX, filename);
2815 if (MessageBox(hwnd, buf, "Question",
2816 MB_YESNO | MB_ICONQUESTION)
2817 != IDYES)
2818 break;
2819 }
2820
2821 fp = fopen(filename, "w");
2822
2823 if (!fp) {
2824 MessageBox(hwnd, "Unable to open save file",
2825 "Error", MB_ICONERROR | MB_OK);
2826 break;
2827 }
2828
2829 midend_serialise(fe->me, savefile_write, fp);
2830
2831 fclose(fp);
2832 } else {
2833 FILE *fp = fopen(filename, "r");
2834 char *err;
2835
2836 if (!fp) {
2837 MessageBox(hwnd, "Unable to open saved game file",
2838 "Error", MB_ICONERROR | MB_OK);
2839 break;
2840 }
2841
2842 err = midend_deserialise(fe->me, savefile_read, fp);
2843
2844 fclose(fp);
2845
2846 if (err) {
2847 MessageBox(hwnd, err, "Error", MB_ICONERROR|MB_OK);
2848 break;
2849 }
2850
2851 new_game_size(fe);
2852 }
2853 }
2854 }
2855
2856 break;
2857 #ifndef _WIN32_WCE
2858 case IDM_HELPC:
2859 start_help(fe, NULL);
2860 break;
2861 case IDM_GAMEHELP:
2862 start_help(fe, help_topic);
2863 break;
2864 #endif
2865 default:
2866 {
2867 int p = ((wParam &~ 0xF) - IDM_PRESETS) / 0x10;
2868
2869 if (p >= 0 && p < fe->npresets) {
2870 midend_set_params(fe->me, fe->presets[p]);
2871 new_game_type(fe);
2872 }
2873 }
2874 break;
2875 }
2876 break;
2877 case WM_DESTROY:
2878 #ifndef _WIN32_WCE
2879 stop_help(fe);
2880 #endif
2881 PostQuitMessage(0);
2882 return 0;
2883 case WM_PAINT:
2884 {
2885 PAINTSTRUCT p;
2886 HDC hdc, hdc2;
2887 HBITMAP prevbm;
2888 RECT rcDest;
2889
2890 hdc = BeginPaint(hwnd, &p);
2891 hdc2 = CreateCompatibleDC(hdc);
2892 prevbm = SelectObject(hdc2, fe->bitmap);
2893 #ifdef _WIN32_WCE
2894 FillRect(hdc, &(p.rcPaint), (HBRUSH) GetStockObject(WHITE_BRUSH));
2895 #endif
2896 IntersectRect(&rcDest, &(fe->bitmapPosition), &(p.rcPaint));
2897 BitBlt(hdc,
2898 rcDest.left, rcDest.top,
2899 rcDest.right - rcDest.left,
2900 rcDest.bottom - rcDest.top,
2901 hdc2,
2902 rcDest.left - fe->bitmapPosition.left,
2903 rcDest.top - fe->bitmapPosition.top,
2904 SRCCOPY);
2905 SelectObject(hdc2, prevbm);
2906 DeleteDC(hdc2);
2907 EndPaint(hwnd, &p);
2908 }
2909 return 0;
2910 case WM_KEYDOWN:
2911 {
2912 int key = -1;
2913 BYTE keystate[256];
2914 int r = GetKeyboardState(keystate);
2915 int shift = (r && (keystate[VK_SHIFT] & 0x80)) ? MOD_SHFT : 0;
2916 int ctrl = (r && (keystate[VK_CONTROL] & 0x80)) ? MOD_CTRL : 0;
2917
2918 switch (wParam) {
2919 case VK_LEFT:
2920 if (!(lParam & 0x01000000))
2921 key = MOD_NUM_KEYPAD | '4';
2922 else
2923 key = shift | ctrl | CURSOR_LEFT;
2924 break;
2925 case VK_RIGHT:
2926 if (!(lParam & 0x01000000))
2927 key = MOD_NUM_KEYPAD | '6';
2928 else
2929 key = shift | ctrl | CURSOR_RIGHT;
2930 break;
2931 case VK_UP:
2932 if (!(lParam & 0x01000000))
2933 key = MOD_NUM_KEYPAD | '8';
2934 else
2935 key = shift | ctrl | CURSOR_UP;
2936 break;
2937 case VK_DOWN:
2938 if (!(lParam & 0x01000000))
2939 key = MOD_NUM_KEYPAD | '2';
2940 else
2941 key = shift | ctrl | CURSOR_DOWN;
2942 break;
2943 /*
2944 * Diagonal keys on the numeric keypad.
2945 */
2946 case VK_PRIOR:
2947 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '9';
2948 break;
2949 case VK_NEXT:
2950 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '3';
2951 break;
2952 case VK_HOME:
2953 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '7';
2954 break;
2955 case VK_END:
2956 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '1';
2957 break;
2958 case VK_INSERT:
2959 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '0';
2960 break;
2961 case VK_CLEAR:
2962 if (!(lParam & 0x01000000)) key = MOD_NUM_KEYPAD | '5';
2963 break;
2964 /*
2965 * Numeric keypad keys with Num Lock on.
2966 */
2967 case VK_NUMPAD4: key = MOD_NUM_KEYPAD | '4'; break;
2968 case VK_NUMPAD6: key = MOD_NUM_KEYPAD | '6'; break;
2969 case VK_NUMPAD8: key = MOD_NUM_KEYPAD | '8'; break;
2970 case VK_NUMPAD2: key = MOD_NUM_KEYPAD | '2'; break;
2971 case VK_NUMPAD5: key = MOD_NUM_KEYPAD | '5'; break;
2972 case VK_NUMPAD9: key = MOD_NUM_KEYPAD | '9'; break;
2973 case VK_NUMPAD3: key = MOD_NUM_KEYPAD | '3'; break;
2974 case VK_NUMPAD7: key = MOD_NUM_KEYPAD | '7'; break;
2975 case VK_NUMPAD1: key = MOD_NUM_KEYPAD | '1'; break;
2976 case VK_NUMPAD0: key = MOD_NUM_KEYPAD | '0'; break;
2977 }
2978
2979 if (key != -1) {
2980 if (!midend_process_key(fe->me, 0, 0, key))
2981 PostQuitMessage(0);
2982 } else {
2983 MSG m;
2984 m.hwnd = hwnd;
2985 m.message = WM_KEYDOWN;
2986 m.wParam = wParam;
2987 m.lParam = lParam & 0xdfff;
2988 TranslateMessage(&m);
2989 }
2990 }
2991 break;
2992 case WM_LBUTTONDOWN:
2993 case WM_RBUTTONDOWN:
2994 case WM_MBUTTONDOWN:
2995 {
2996 int button;
2997
2998 /*
2999 * Shift-clicks count as middle-clicks, since otherwise
3000 * two-button Windows users won't have any kind of
3001 * middle click to use.
3002 */
3003 if (message == WM_MBUTTONDOWN || (wParam & MK_SHIFT))
3004 button = MIDDLE_BUTTON;
3005 else if (message == WM_RBUTTONDOWN || is_alt_pressed())
3006 button = RIGHT_BUTTON;
3007 else
3008 #ifndef _WIN32_WCE
3009 button = LEFT_BUTTON;
3010 #else
3011 if ((thegame.flags & REQUIRE_RBUTTON) == 0)
3012 button = LEFT_BUTTON;
3013 else
3014 {
3015 SHRGINFO shrgi;
3016
3017 shrgi.cbSize = sizeof(SHRGINFO);
3018 shrgi.hwndClient = hwnd;
3019 shrgi.ptDown.x = (signed short)LOWORD(lParam);
3020 shrgi.ptDown.y = (signed short)HIWORD(lParam);
3021 shrgi.dwFlags = SHRG_RETURNCMD;
3022
3023 if (GN_CONTEXTMENU == SHRecognizeGesture(&shrgi))
3024 button = RIGHT_BUTTON;
3025 else
3026 button = LEFT_BUTTON;
3027 }
3028 #endif
3029
3030 if (!midend_process_key(fe->me,
3031 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3032 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3033 button))
3034 PostQuitMessage(0);
3035
3036 SetCapture(hwnd);
3037 }
3038 break;
3039 case WM_LBUTTONUP:
3040 case WM_RBUTTONUP:
3041 case WM_MBUTTONUP:
3042 {
3043 int button;
3044
3045 /*
3046 * Shift-clicks count as middle-clicks, since otherwise
3047 * two-button Windows users won't have any kind of
3048 * middle click to use.
3049 */
3050 if (message == WM_MBUTTONUP || (wParam & MK_SHIFT))
3051 button = MIDDLE_RELEASE;
3052 else if (message == WM_RBUTTONUP || is_alt_pressed())
3053 button = RIGHT_RELEASE;
3054 else
3055 button = LEFT_RELEASE;
3056
3057 if (!midend_process_key(fe->me,
3058 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3059 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3060 button))
3061 PostQuitMessage(0);
3062
3063 ReleaseCapture();
3064 }
3065 break;
3066 case WM_MOUSEMOVE:
3067 {
3068 int button;
3069
3070 if (wParam & (MK_MBUTTON | MK_SHIFT))
3071 button = MIDDLE_DRAG;
3072 else if (wParam & MK_RBUTTON || is_alt_pressed())
3073 button = RIGHT_DRAG;
3074 else
3075 button = LEFT_DRAG;
3076
3077 if (!midend_process_key(fe->me,
3078 (signed short)LOWORD(lParam) - fe->bitmapPosition.left,
3079 (signed short)HIWORD(lParam) - fe->bitmapPosition.top,
3080 button))
3081 PostQuitMessage(0);
3082 }
3083 break;
3084 case WM_CHAR:
3085 if (!midend_process_key(fe->me, 0, 0, (unsigned char)wParam))
3086 PostQuitMessage(0);
3087 return 0;
3088 case WM_TIMER:
3089 if (fe->timer) {
3090 DWORD now = GetTickCount();
3091 float elapsed = (float) (now - fe->timer_last_tickcount) * 0.001F;
3092 midend_timer(fe->me, elapsed);
3093 fe->timer_last_tickcount = now;
3094 }
3095 return 0;
3096 #ifndef _WIN32_WCE
3097 case WM_SIZING:
3098 {
3099 RECT *sr = (RECT *)lParam;
3100 int wx, wy, isedge = 0;
3101
3102 if (wParam == WMSZ_TOP ||
3103 wParam == WMSZ_RIGHT ||
3104 wParam == WMSZ_BOTTOM ||
3105 wParam == WMSZ_LEFT) isedge = 1;
3106 adjust_game_size(fe, sr, isedge, &wx, &wy);
3107
3108 /* Given the window size the puzzles constrain
3109 * us to, work out which edge we should be moving. */
3110 if (wParam == WMSZ_TOP ||
3111 wParam == WMSZ_TOPLEFT ||
3112 wParam == WMSZ_TOPRIGHT) {
3113 sr->top = sr->bottom - wy;
3114 } else {
3115 sr->bottom = sr->top + wy;
3116 }
3117 if (wParam == WMSZ_LEFT ||
3118 wParam == WMSZ_TOPLEFT ||
3119 wParam == WMSZ_BOTTOMLEFT) {
3120 sr->left = sr->right - wx;
3121 } else {
3122 sr->right = sr->left + wx;
3123 }
3124 return TRUE;
3125 }
3126 break;
3127 #endif
3128 }
3129
3130 return DefWindowProc(hwnd, message, wParam, lParam);
3131 }
3132
3133 #ifdef _WIN32_WCE
3134 static int FindPreviousInstance()
3135 {
3136 /* Check if application is running. If it's running then focus on the window */
3137 HWND hOtherWnd = NULL;
3138
3139 hOtherWnd = FindWindow (wGameName, wGameName);
3140 if (hOtherWnd)
3141 {
3142 SetForegroundWindow (hOtherWnd);
3143 return TRUE;
3144 }
3145
3146 return FALSE;
3147 }
3148 #endif
3149
3150 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
3151 {
3152 MSG msg;
3153 char *error;
3154
3155 #ifdef _WIN32_WCE
3156 MultiByteToWideChar (CP_ACP, 0, thegame.name, -1, wGameName, 256);
3157 if (FindPreviousInstance ())
3158 return 0;
3159 #endif
3160
3161 InitCommonControls();
3162
3163 if (!prev) {
3164 WNDCLASS wndclass;
3165
3166 wndclass.style = 0;
3167 wndclass.lpfnWndProc = WndProc;
3168 wndclass.cbClsExtra = 0;
3169 wndclass.cbWndExtra = 0;
3170 wndclass.hInstance = inst;
3171 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(200));
3172 #ifndef _WIN32_WCE
3173 if (!wndclass.hIcon) /* in case resource file is absent */
3174 wndclass.hIcon = LoadIcon(inst, IDI_APPLICATION);
3175 #endif
3176 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
3177 wndclass.hbrBackground = NULL;
3178 wndclass.lpszMenuName = NULL;
3179 #ifdef _WIN32_WCE
3180 wndclass.lpszClassName = wGameName;
3181 #else
3182 wndclass.lpszClassName = thegame.name;
3183 #endif
3184
3185 RegisterClass(&wndclass);
3186 }
3187
3188 while (*cmdline && isspace((unsigned char)*cmdline))
3189 cmdline++;
3190
3191 init_help();
3192
3193 if (!new_window(inst, *cmdline ? cmdline : NULL, &error)) {
3194 char buf[128];
3195 sprintf(buf, "%.100s Error", thegame.name);
3196 MessageBox(NULL, error, buf, MB_OK|MB_ICONERROR);
3197 return 1;
3198 }
3199
3200 while (GetMessage(&msg, NULL, 0, 0)) {
3201 DispatchMessage(&msg);
3202 }
3203
3204 cleanup_help();
3205
3206 return msg.wParam;
3207 }