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